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
| 39,987 |
[Bug]: build fails with `enable_electron_extensions=false`
|
### 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.8.2
### What operating system are you using?
Other Linux
### Operating System Version
openSUSE Tumbleweed
### What arch are you using?
ia32
### Last Known Working Electron version
_No response_
### Expected Behavior
I am trying to build Electron 25.8.2 with `enable_electron_extensions=false`.
### Actual Behavior
After fixing the <a href="https://gist.github.com/brjsp/b003b7062be0e080d55235cb8449b09e">obvious misguarded sections of code</a> we are left with several <a href="https://gist.github.com/brjsp/fe8e7342534ae347eeb3a66932e91ad2">linker errors</a>, mostly to stuff under //extensions/browser. I am not sure how to remove the dependency, as some of the uses of the offending types are in constructors eg. <a href=https://github.com/electron/electron/blob/v25.8.2/shell/browser/net/proxying_websocket.cc#L38>in proxying_websocket</a>.
### Testcase Gist URL
_No response_
### Additional Information
(Ignore the fact that the attached buildlog is from ix86 which is unsupported β I only used that architecture because it builds way faster and has clearer linker messages due to no LTO, the problem will be the same on any target)
|
https://github.com/electron/electron/issues/39987
|
https://github.com/electron/electron/pull/40032
|
713d8c4167a07971775db847adca880f49e8d381
|
b0590b6ee874fbeac49bb5615525d145835eb64f
| 2023-09-27T05:22:12Z |
c++
| 2023-10-04T08:40:01Z |
shell/browser/usb/electron_usb_delegate.cc
|
// Copyright (c) 2022 Microsoft, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/usb/electron_usb_delegate.h"
#include <utility>
#include "base/containers/contains.h"
#include "base/containers/cxx20_erase.h"
#include "base/observer_list.h"
#include "base/observer_list_types.h"
#include "base/scoped_observation.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "extensions/buildflags/buildflags.h"
#include "services/device/public/mojom/usb_enumeration_options.mojom.h"
#include "shell/browser/electron_permission_manager.h"
#include "shell/browser/usb/usb_chooser_context.h"
#include "shell/browser/usb/usb_chooser_context_factory.h"
#include "shell/browser/usb/usb_chooser_controller.h"
#include "shell/browser/web_contents_permission_helper.h"
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "base/containers/fixed_flat_set.h"
#include "chrome/common/chrome_features.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/guest_view/web_view/web_view_guest.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension.h"
#include "services/device/public/mojom/usb_device.mojom.h"
#endif
namespace {
using ::content::UsbChooser;
electron::UsbChooserContext* GetChooserContext(
content::BrowserContext* browser_context) {
return electron::UsbChooserContextFactory::GetForBrowserContext(
browser_context);
}
#if BUILDFLAG(ENABLE_EXTENSIONS)
// These extensions can claim the smart card USB class and automatically gain
// permissions for devices that have an interface with this class.
constexpr auto kSmartCardPrivilegedExtensionIds =
base::MakeFixedFlatSetSorted<base::StringPiece>({
// Smart Card Connector Extension and its Beta version, see
// crbug.com/1233881.
"khpfeaanjngmcnplbdlpegiifgpfgdco",
"mockcojkppdndnhgonljagclgpkjbkek",
});
bool DeviceHasInterfaceWithClass(
const device::mojom::UsbDeviceInfo& device_info,
uint8_t interface_class) {
for (const auto& configuration : device_info.configurations) {
for (const auto& interface : configuration->interfaces) {
for (const auto& alternate : interface->alternates) {
if (alternate->class_code == interface_class)
return true;
}
}
}
return false;
}
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
bool IsDevicePermissionAutoGranted(
const url::Origin& origin,
const device::mojom::UsbDeviceInfo& device_info) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
// Note: The `DeviceHasInterfaceWithClass()` call is made after checking the
// origin, since that method call is expensive.
if (origin.scheme() == extensions::kExtensionScheme &&
base::Contains(kSmartCardPrivilegedExtensionIds, origin.host()) &&
DeviceHasInterfaceWithClass(device_info,
device::mojom::kUsbSmartCardClass)) {
return true;
}
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
return false;
}
} // namespace
namespace electron {
// Manages the UsbDelegate observers for a single browser context.
class ElectronUsbDelegate::ContextObservation
: public UsbChooserContext::DeviceObserver {
public:
ContextObservation(ElectronUsbDelegate* parent,
content::BrowserContext* browser_context)
: parent_(parent), browser_context_(browser_context) {
auto* chooser_context = GetChooserContext(browser_context_);
device_observation_.Observe(chooser_context);
}
ContextObservation(ContextObservation&) = delete;
ContextObservation& operator=(ContextObservation&) = delete;
~ContextObservation() override = default;
// UsbChooserContext::DeviceObserver:
void OnDeviceAdded(const device::mojom::UsbDeviceInfo& device_info) override {
for (auto& observer : observer_list_)
observer.OnDeviceAdded(device_info);
}
void OnDeviceRemoved(
const device::mojom::UsbDeviceInfo& device_info) override {
for (auto& observer : observer_list_)
observer.OnDeviceRemoved(device_info);
}
void OnDeviceManagerConnectionError() override {
for (auto& observer : observer_list_)
observer.OnDeviceManagerConnectionError();
}
void OnBrowserContextShutdown() override {
parent_->observations_.erase(browser_context_);
// Return since `this` is now deleted.
}
void AddObserver(content::UsbDelegate::Observer* observer) {
observer_list_.AddObserver(observer);
}
void RemoveObserver(content::UsbDelegate::Observer* observer) {
observer_list_.RemoveObserver(observer);
}
private:
// Safe because `parent_` owns `this`.
const raw_ptr<ElectronUsbDelegate> parent_;
// Safe because `this` is destroyed when the context is lost.
const raw_ptr<content::BrowserContext> browser_context_;
base::ScopedObservation<UsbChooserContext, UsbChooserContext::DeviceObserver>
device_observation_{this};
base::ObserverList<content::UsbDelegate::Observer> observer_list_;
};
ElectronUsbDelegate::ElectronUsbDelegate() = default;
ElectronUsbDelegate::~ElectronUsbDelegate() = default;
void ElectronUsbDelegate::AdjustProtectedInterfaceClasses(
content::BrowserContext* browser_context,
const url::Origin& origin,
content::RenderFrameHost* frame,
std::vector<uint8_t>& classes) {
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context->GetPermissionControllerDelegate());
classes = permission_manager->CheckProtectedUSBClasses(classes);
}
std::unique_ptr<UsbChooser> ElectronUsbDelegate::RunChooser(
content::RenderFrameHost& frame,
blink::mojom::WebUsbRequestDeviceOptionsPtr options,
blink::mojom::WebUsbService::GetPermissionCallback callback) {
UsbChooserController* controller = ControllerForFrame(&frame);
if (controller) {
DeleteControllerForFrame(&frame);
}
AddControllerForFrame(&frame, std::move(options), std::move(callback));
// Return a nullptr because the return value isn't used for anything. The
// return value is simply used in Chromium to cleanup the chooser UI once the
// usb service is destroyed.
return nullptr;
}
bool ElectronUsbDelegate::CanRequestDevicePermission(
content::BrowserContext* browser_context,
const url::Origin& origin) {
base::Value::Dict details;
details.Set("securityOrigin", origin.GetURL().spec());
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context->GetPermissionControllerDelegate());
return permission_manager->CheckPermissionWithDetails(
static_cast<blink::PermissionType>(
WebContentsPermissionHelper::PermissionType::USB),
nullptr, origin.GetURL(), std::move(details));
}
void ElectronUsbDelegate::RevokeDevicePermissionWebInitiated(
content::BrowserContext* browser_context,
const url::Origin& origin,
const device::mojom::UsbDeviceInfo& device) {
GetChooserContext(browser_context)
->RevokeDevicePermissionWebInitiated(origin, device);
}
const device::mojom::UsbDeviceInfo* ElectronUsbDelegate::GetDeviceInfo(
content::BrowserContext* browser_context,
const std::string& guid) {
return GetChooserContext(browser_context)->GetDeviceInfo(guid);
}
bool ElectronUsbDelegate::HasDevicePermission(
content::BrowserContext* browser_context,
const url::Origin& origin,
const device::mojom::UsbDeviceInfo& device) {
if (IsDevicePermissionAutoGranted(origin, device))
return true;
return GetChooserContext(browser_context)
->HasDevicePermission(origin, device);
}
void ElectronUsbDelegate::GetDevices(
content::BrowserContext* browser_context,
blink::mojom::WebUsbService::GetDevicesCallback callback) {
GetChooserContext(browser_context)->GetDevices(std::move(callback));
}
void ElectronUsbDelegate::GetDevice(
content::BrowserContext* browser_context,
const std::string& guid,
base::span<const uint8_t> blocked_interface_classes,
mojo::PendingReceiver<device::mojom::UsbDevice> device_receiver,
mojo::PendingRemote<device::mojom::UsbDeviceClient> device_client) {
GetChooserContext(browser_context)
->GetDevice(guid, blocked_interface_classes, std::move(device_receiver),
std::move(device_client));
}
void ElectronUsbDelegate::AddObserver(content::BrowserContext* browser_context,
Observer* observer) {
GetContextObserver(browser_context)->AddObserver(observer);
}
void ElectronUsbDelegate::RemoveObserver(
content::BrowserContext* browser_context,
Observer* observer) {
GetContextObserver(browser_context)->RemoveObserver(observer);
}
ElectronUsbDelegate::ContextObservation*
ElectronUsbDelegate::GetContextObserver(
content::BrowserContext* browser_context) {
if (!base::Contains(observations_, browser_context)) {
observations_.emplace(browser_context, std::make_unique<ContextObservation>(
this, browser_context));
}
return observations_[browser_context].get();
}
bool ElectronUsbDelegate::IsServiceWorkerAllowedForOrigin(
const url::Origin& origin) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
// WebUSB is only available on extension service workers for now.
if (base::FeatureList::IsEnabled(
features::kEnableWebUsbOnExtensionServiceWorker) &&
origin.scheme() == extensions::kExtensionScheme) {
return true;
}
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
return false;
}
UsbChooserController* ElectronUsbDelegate::ControllerForFrame(
content::RenderFrameHost* render_frame_host) {
auto mapping = controller_map_.find(render_frame_host);
return mapping == controller_map_.end() ? nullptr : mapping->second.get();
}
UsbChooserController* ElectronUsbDelegate::AddControllerForFrame(
content::RenderFrameHost* render_frame_host,
blink::mojom::WebUsbRequestDeviceOptionsPtr options,
blink::mojom::WebUsbService::GetPermissionCallback callback) {
auto* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host);
auto controller = std::make_unique<UsbChooserController>(
render_frame_host, std::move(options), std::move(callback), web_contents,
weak_factory_.GetWeakPtr());
controller_map_.insert(
std::make_pair(render_frame_host, std::move(controller)));
return ControllerForFrame(render_frame_host);
}
void ElectronUsbDelegate::DeleteControllerForFrame(
content::RenderFrameHost* render_frame_host) {
controller_map_.erase(render_frame_host);
}
bool ElectronUsbDelegate::PageMayUseUsb(content::Page& page) {
content::RenderFrameHost& main_rfh = page.GetMainDocument();
#if BUILDFLAG(ENABLE_EXTENSIONS)
// WebViewGuests have no mechanism to show permission prompts and their
// embedder can't grant USB access through its permissionrequest API. Also
// since webviews use a separate StoragePartition, they must not gain access
// through permissions granted in non-webview contexts.
if (extensions::WebViewGuest::FromRenderFrameHost(&main_rfh)) {
return false;
}
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
// USB permissions are scoped to a BrowserContext instead of a
// StoragePartition, so we need to be careful about usage across
// StoragePartitions. Until this is scoped correctly, we'll try to avoid
// inappropriate sharing by restricting access to the API. We can't be as
// strict as we'd like, as cases like extensions and Isolated Web Apps still
// need USB access in non-default partitions, so we'll just guard against
// HTTP(S) as that presents a clear risk for inappropriate sharing.
// TODO(crbug.com/1469672): USB permissions should be explicitly scoped to
// StoragePartitions.
if (main_rfh.GetStoragePartition() !=
main_rfh.GetBrowserContext()->GetDefaultStoragePartition()) {
return !main_rfh.GetLastCommittedURL().SchemeIsHTTPOrHTTPS();
}
return true;
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 39,987 |
[Bug]: build fails with `enable_electron_extensions=false`
|
### 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.8.2
### What operating system are you using?
Other Linux
### Operating System Version
openSUSE Tumbleweed
### What arch are you using?
ia32
### Last Known Working Electron version
_No response_
### Expected Behavior
I am trying to build Electron 25.8.2 with `enable_electron_extensions=false`.
### Actual Behavior
After fixing the <a href="https://gist.github.com/brjsp/b003b7062be0e080d55235cb8449b09e">obvious misguarded sections of code</a> we are left with several <a href="https://gist.github.com/brjsp/fe8e7342534ae347eeb3a66932e91ad2">linker errors</a>, mostly to stuff under //extensions/browser. I am not sure how to remove the dependency, as some of the uses of the offending types are in constructors eg. <a href=https://github.com/electron/electron/blob/v25.8.2/shell/browser/net/proxying_websocket.cc#L38>in proxying_websocket</a>.
### Testcase Gist URL
_No response_
### Additional Information
(Ignore the fact that the attached buildlog is from ix86 which is unsupported β I only used that architecture because it builds way faster and has clearer linker messages due to no LTO, the problem will be the same on any target)
|
https://github.com/electron/electron/issues/39987
|
https://github.com/electron/electron/pull/40032
|
713d8c4167a07971775db847adca880f49e8d381
|
b0590b6ee874fbeac49bb5615525d145835eb64f
| 2023-09-27T05:22:12Z |
c++
| 2023-10-04T08:40:01Z |
shell/renderer/printing/print_render_frame_helper_delegate.cc
|
// 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/renderer/printing/print_render_frame_helper_delegate.h"
#include <utility>
#include "content/public/renderer/render_frame.h"
#include "extensions/buildflags/buildflags.h"
#include "third_party/blink/public/web/web_element.h"
#include "third_party/blink/public/web/web_local_frame.h"
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "chrome/common/pdf_util.h"
#include "extensions/common/constants.h"
#include "extensions/renderer/guest_view/mime_handler_view/post_message_support.h"
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
namespace electron {
PrintRenderFrameHelperDelegate::PrintRenderFrameHelperDelegate() = default;
PrintRenderFrameHelperDelegate::~PrintRenderFrameHelperDelegate() = default;
// Return the PDF object element if |frame| is the out of process PDF extension.
blink::WebElement PrintRenderFrameHelperDelegate::GetPdfElement(
blink::WebLocalFrame* frame) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
if (frame->Parent() &&
IsPdfInternalPluginAllowedOrigin(frame->Parent()->GetSecurityOrigin())) {
auto plugin_element = frame->GetDocument().QuerySelector("embed");
DCHECK(!plugin_element.IsNull());
return plugin_element;
}
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
return blink::WebElement();
}
bool PrintRenderFrameHelperDelegate::IsPrintPreviewEnabled() {
return false;
}
bool PrintRenderFrameHelperDelegate::OverridePrint(
blink::WebLocalFrame* frame) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
auto* post_message_support =
extensions::PostMessageSupport::FromWebLocalFrame(frame);
if (post_message_support) {
// This message is handled in chrome/browser/resources/pdf/pdf_viewer.js and
// instructs the PDF plugin to print. This is to make window.print() on a
// PDF plugin document correctly print the PDF. See
// https://crbug.com/448720.
base::Value::Dict message;
message.Set("type", "print");
post_message_support->PostMessageFromValue(base::Value(std::move(message)));
return true;
}
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
return false;
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 39,987 |
[Bug]: build fails with `enable_electron_extensions=false`
|
### 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.8.2
### What operating system are you using?
Other Linux
### Operating System Version
openSUSE Tumbleweed
### What arch are you using?
ia32
### Last Known Working Electron version
_No response_
### Expected Behavior
I am trying to build Electron 25.8.2 with `enable_electron_extensions=false`.
### Actual Behavior
After fixing the <a href="https://gist.github.com/brjsp/b003b7062be0e080d55235cb8449b09e">obvious misguarded sections of code</a> we are left with several <a href="https://gist.github.com/brjsp/fe8e7342534ae347eeb3a66932e91ad2">linker errors</a>, mostly to stuff under //extensions/browser. I am not sure how to remove the dependency, as some of the uses of the offending types are in constructors eg. <a href=https://github.com/electron/electron/blob/v25.8.2/shell/browser/net/proxying_websocket.cc#L38>in proxying_websocket</a>.
### Testcase Gist URL
_No response_
### Additional Information
(Ignore the fact that the attached buildlog is from ix86 which is unsupported β I only used that architecture because it builds way faster and has clearer linker messages due to no LTO, the problem will be the same on any target)
|
https://github.com/electron/electron/issues/39987
|
https://github.com/electron/electron/pull/40032
|
713d8c4167a07971775db847adca880f49e8d381
|
b0590b6ee874fbeac49bb5615525d145835eb64f
| 2023-09-27T05:22:12Z |
c++
| 2023-10-04T08:40:01Z |
shell/renderer/renderer_client_base.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/renderer_client_base.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/command_line.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "components/network_hints/renderer/web_prescient_networking_impl.h"
#include "content/common/buildflags.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_switches.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_thread.h"
#include "electron/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "shell/browser/api/electron_api_protocol.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/color_util.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/node_includes.h"
#include "shell/common/node_util.h"
#include "shell/common/options_switches.h"
#include "shell/common/world_ids.h"
#include "shell/renderer/api/context_bridge/object_cache.h"
#include "shell/renderer/api/electron_api_context_bridge.h"
#include "shell/renderer/browser_exposed_renderer_interfaces.h"
#include "shell/renderer/content_settings_observer.h"
#include "shell/renderer/electron_api_service_impl.h"
#include "shell/renderer/electron_autofill_agent.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "third_party/blink/public/common/web_preferences/web_preferences.h"
#include "third_party/blink/public/web/blink.h"
#include "third_party/blink/public/web/web_custom_element.h" // NOLINT(build/include_alpha)
#include "third_party/blink/public/web/web_frame_widget.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_plugin_params.h"
#include "third_party/blink/public/web/web_script_source.h"
#include "third_party/blink/public/web/web_security_policy.h"
#include "third_party/blink/public/web/web_view.h"
#include "third_party/blink/renderer/platform/media/multi_buffer_data_source.h" // nogncheck
#include "third_party/blink/renderer/platform/weborigin/scheme_registry.h" // nogncheck
#include "third_party/widevine/cdm/buildflags.h"
#if BUILDFLAG(IS_MAC)
#include "base/strings/sys_string_conversions.h"
#endif
#if BUILDFLAG(IS_WIN)
#include <shlobj.h>
#endif
#if BUILDFLAG(ENABLE_WIDEVINE)
#include "chrome/renderer/media/chrome_key_systems.h" // nogncheck
#endif
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
#include "components/spellcheck/renderer/spellcheck.h"
#include "components/spellcheck/renderer/spellcheck_provider.h"
#endif
#if BUILDFLAG(ENABLE_PDF_VIEWER)
#include "chrome/common/pdf_util.h"
#include "components/pdf/common/internal_plugin_helpers.h"
#include "components/pdf/renderer/pdf_internal_plugin_delegate.h"
#include "shell/common/electron_constants.h"
#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
#if BUILDFLAG(ENABLE_PLUGINS)
#include "shell/common/plugin_info.h"
#include "shell/renderer/pepper_helper.h"
#endif // BUILDFLAG(ENABLE_PLUGINS)
#if BUILDFLAG(ENABLE_PRINTING)
#include "components/printing/renderer/print_render_frame_helper.h"
#include "printing/metafile_agent.h" // nogncheck
#include "shell/renderer/printing/print_render_frame_helper_delegate.h"
#endif // BUILDFLAG(ENABLE_PRINTING)
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "base/strings/utf_string_conversions.h"
#include "content/public/common/webplugininfo.h"
#include "extensions/common/constants.h"
#include "extensions/common/extensions_client.h"
#include "extensions/renderer/dispatcher.h"
#include "extensions/renderer/extension_frame_helper.h"
#include "extensions/renderer/extension_web_view_helper.h"
#include "extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container_manager.h"
#include "shell/common/extensions/electron_extensions_client.h"
#include "shell/renderer/extensions/electron_extensions_renderer_client.h"
#endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
namespace electron {
content::RenderFrame* GetRenderFrame(v8::Local<v8::Object> value);
namespace {
void SetIsWebView(v8::Isolate* isolate, v8::Local<v8::Object> object) {
gin_helper::Dictionary dict(isolate, object);
dict.SetHidden("isWebView", true);
}
std::vector<std::string> ParseSchemesCLISwitch(base::CommandLine* command_line,
const char* switch_name) {
std::string custom_schemes = command_line->GetSwitchValueASCII(switch_name);
return base::SplitString(custom_schemes, ",", base::TRIM_WHITESPACE,
base::SPLIT_WANT_NONEMPTY);
}
#if BUILDFLAG(ENABLE_PDF_VIEWER)
class ChromePdfInternalPluginDelegate final
: public pdf::PdfInternalPluginDelegate {
public:
ChromePdfInternalPluginDelegate() = default;
ChromePdfInternalPluginDelegate(const ChromePdfInternalPluginDelegate&) =
delete;
ChromePdfInternalPluginDelegate& operator=(
const ChromePdfInternalPluginDelegate&) = delete;
~ChromePdfInternalPluginDelegate() override = default;
// `pdf::PdfInternalPluginDelegate`:
bool IsAllowedOrigin(const url::Origin& origin) const override {
return origin.scheme() == extensions::kExtensionScheme &&
origin.host() == extension_misc::kPdfExtensionId;
}
};
#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
// static
RendererClientBase* g_renderer_client_base = nullptr;
bool IsDevTools(content::RenderFrame* render_frame) {
return render_frame->GetWebFrame()->GetDocument().Url().ProtocolIs(
"devtools");
}
bool IsDevToolsExtension(content::RenderFrame* render_frame) {
return render_frame->GetWebFrame()->GetDocument().Url().ProtocolIs(
"chrome-extension");
}
} // namespace
RendererClientBase::RendererClientBase() {
auto* command_line = base::CommandLine::ForCurrentProcess();
// Parse --service-worker-schemes=scheme1,scheme2
std::vector<std::string> service_worker_schemes_list =
ParseSchemesCLISwitch(command_line, switches::kServiceWorkerSchemes);
for (const std::string& scheme : service_worker_schemes_list)
electron::api::AddServiceWorkerScheme(scheme);
// Parse --standard-schemes=scheme1,scheme2
std::vector<std::string> standard_schemes_list =
ParseSchemesCLISwitch(command_line, switches::kStandardSchemes);
for (const std::string& scheme : standard_schemes_list)
url::AddStandardScheme(scheme.c_str(), url::SCHEME_WITH_HOST);
// Parse --cors-schemes=scheme1,scheme2
std::vector<std::string> cors_schemes_list =
ParseSchemesCLISwitch(command_line, switches::kCORSSchemes);
for (const std::string& scheme : cors_schemes_list)
url::AddCorsEnabledScheme(scheme.c_str());
// Parse --streaming-schemes=scheme1,scheme2
std::vector<std::string> streaming_schemes_list =
ParseSchemesCLISwitch(command_line, switches::kStreamingSchemes);
for (const std::string& scheme : streaming_schemes_list)
blink::AddStreamingScheme(scheme.c_str());
// Parse --secure-schemes=scheme1,scheme2
std::vector<std::string> secure_schemes_list =
ParseSchemesCLISwitch(command_line, switches::kSecureSchemes);
for (const std::string& scheme : secure_schemes_list)
url::AddSecureScheme(scheme.data());
// We rely on the unique process host id which is notified to the
// renderer process via command line switch from the content layer,
// if this switch is removed from the content layer for some reason,
// we should define our own.
DCHECK(command_line->HasSwitch(::switches::kRendererClientId));
renderer_client_id_ =
command_line->GetSwitchValueASCII(::switches::kRendererClientId);
g_renderer_client_base = this;
}
RendererClientBase::~RendererClientBase() {
g_renderer_client_base = nullptr;
}
// static
RendererClientBase* RendererClientBase::Get() {
DCHECK(g_renderer_client_base);
return g_renderer_client_base;
}
void RendererClientBase::BindProcess(v8::Isolate* isolate,
gin_helper::Dictionary* process,
content::RenderFrame* render_frame) {
auto context_id = base::StringPrintf(
"%s-%" PRId64, renderer_client_id_.c_str(), ++next_context_id_);
process->SetReadOnly("isMainFrame", render_frame->IsMainFrame());
process->SetReadOnly("contextIsolated",
render_frame->GetBlinkPreferences().context_isolation);
process->SetReadOnly("contextId", context_id);
}
bool RendererClientBase::ShouldLoadPreload(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) const {
auto prefs = render_frame->GetBlinkPreferences();
bool is_main_frame = render_frame->IsMainFrame();
bool is_devtools =
IsDevTools(render_frame) || IsDevToolsExtension(render_frame);
bool allow_node_in_sub_frames = prefs.node_integration_in_sub_frames;
return (is_main_frame || is_devtools || allow_node_in_sub_frames) &&
!IsWebViewFrame(context, render_frame);
}
void RendererClientBase::RenderThreadStarted() {
auto* command_line = base::CommandLine::ForCurrentProcess();
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
auto* thread = content::RenderThread::Get();
extensions_client_.reset(CreateExtensionsClient());
extensions::ExtensionsClient::Set(extensions_client_.get());
extensions_renderer_client_ =
std::make_unique<ElectronExtensionsRendererClient>();
extensions::ExtensionsRendererClient::Set(extensions_renderer_client_.get());
thread->AddObserver(extensions_renderer_client_->GetDispatcher());
#endif
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
spellcheck_ = std::make_unique<SpellCheck>(this);
#endif
blink::WebCustomElement::AddEmbedderCustomElementName("webview");
blink::WebCustomElement::AddEmbedderCustomElementName("browserplugin");
WTF::String extension_scheme(extensions::kExtensionScheme);
// Extension resources are HTTP-like and safe to expose to the fetch API. The
// rules for the fetch API are consistent with XHR.
blink::SchemeRegistry::RegisterURLSchemeAsSupportingFetchAPI(
extension_scheme);
// Extension resources, when loaded as the top-level document, should bypass
// Blink's strict first-party origin checks.
blink::SchemeRegistry::RegisterURLSchemeAsFirstPartyWhenTopLevel(
extension_scheme);
blink::SchemeRegistry::RegisterURLSchemeAsBypassingContentSecurityPolicy(
extension_scheme);
std::vector<std::string> fetch_enabled_schemes =
ParseSchemesCLISwitch(command_line, switches::kFetchSchemes);
for (const std::string& scheme : fetch_enabled_schemes) {
blink::WebSecurityPolicy::RegisterURLSchemeAsSupportingFetchAPI(
blink::WebString::FromASCII(scheme));
}
std::vector<std::string> service_worker_schemes =
ParseSchemesCLISwitch(command_line, switches::kServiceWorkerSchemes);
for (const std::string& scheme : service_worker_schemes)
blink::WebSecurityPolicy::RegisterURLSchemeAsAllowingServiceWorkers(
blink::WebString::FromASCII(scheme));
std::vector<std::string> csp_bypassing_schemes =
ParseSchemesCLISwitch(command_line, switches::kBypassCSPSchemes);
for (const std::string& scheme : csp_bypassing_schemes)
blink::SchemeRegistry::RegisterURLSchemeAsBypassingContentSecurityPolicy(
WTF::String::FromUTF8(scheme.data(), scheme.length()));
// Allow file scheme to handle service worker by default.
// FIXME(zcbenz): Can this be moved elsewhere?
blink::WebSecurityPolicy::RegisterURLSchemeAsAllowingServiceWorkers("file");
blink::SchemeRegistry::RegisterURLSchemeAsSupportingFetchAPI("file");
#if BUILDFLAG(IS_WIN)
// Set ApplicationUserModelID in renderer process.
std::wstring app_id =
command_line->GetSwitchValueNative(switches::kAppUserModelId);
if (!app_id.empty()) {
SetCurrentProcessExplicitAppUserModelID(app_id.c_str());
}
#endif
}
void RendererClientBase::ExposeInterfacesToBrowser(mojo::BinderMap* binders) {
// NOTE: Do not add binders directly within this method. Instead, modify the
// definition of |ExposeElectronRendererInterfacesToBrowser()| to ensure
// security review coverage.
ExposeElectronRendererInterfacesToBrowser(this, binders);
}
void RendererClientBase::RenderFrameCreated(
content::RenderFrame* render_frame) {
#if defined(TOOLKIT_VIEWS)
new AutofillAgent(render_frame,
render_frame->GetAssociatedInterfaceRegistry());
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
new PepperHelper(render_frame);
#endif
new ContentSettingsObserver(render_frame);
#if BUILDFLAG(ENABLE_PRINTING)
new printing::PrintRenderFrameHelper(
render_frame,
std::make_unique<electron::PrintRenderFrameHelperDelegate>());
#endif
// Note: ElectronApiServiceImpl has to be created now to capture the
// DidCreateDocumentElement event.
new ElectronApiServiceImpl(render_frame, this);
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
auto* dispatcher = extensions_renderer_client_->GetDispatcher();
// ExtensionFrameHelper destroys itself when the RenderFrame is destroyed.
new extensions::ExtensionFrameHelper(render_frame, dispatcher);
dispatcher->OnRenderFrameCreated(render_frame);
render_frame->GetAssociatedInterfaceRegistry()
->AddInterface<extensions::mojom::MimeHandlerViewContainerManager>(
base::BindRepeating(
&extensions::MimeHandlerViewContainerManager::BindReceiver,
render_frame->GetRoutingID()));
#endif
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
if (render_frame->GetBlinkPreferences().enable_spellcheck)
new SpellCheckProvider(render_frame, spellcheck_.get(), this);
#endif
}
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
void RendererClientBase::GetInterface(
const std::string& interface_name,
mojo::ScopedMessagePipeHandle interface_pipe) {
// TODO(crbug.com/977637): Get rid of the use of this implementation of
// |service_manager::LocalInterfaceProvider|. This was done only to avoid
// churning spellcheck code while eliminating the "chrome" and
// "chrome_renderer" services. Spellcheck is (and should remain) the only
// consumer of this implementation.
content::RenderThread::Get()->BindHostReceiver(
mojo::GenericPendingReceiver(interface_name, std::move(interface_pipe)));
}
#endif
void RendererClientBase::DidClearWindowObject(
content::RenderFrame* render_frame) {
// Make sure every page will get a script context created.
render_frame->GetWebFrame()->ExecuteScript(blink::WebScriptSource("void 0"));
}
bool RendererClientBase::OverrideCreatePlugin(
content::RenderFrame* render_frame,
const blink::WebPluginParams& params,
blink::WebPlugin** plugin) {
#if BUILDFLAG(ENABLE_PDF_VIEWER)
if (params.mime_type.Utf8() == pdf::kInternalPluginMimeType) {
*plugin = pdf::CreateInternalPlugin(
std::move(params), render_frame,
std::make_unique<ChromePdfInternalPluginDelegate>());
return true;
}
#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
if (params.mime_type.Utf8() == content::kBrowserPluginMimeType ||
render_frame->GetBlinkPreferences().enable_plugins)
return false;
*plugin = nullptr;
return true;
}
void RendererClientBase::GetSupportedKeySystems(
media::GetSupportedKeySystemsCB cb) {
#if BUILDFLAG(ENABLE_WIDEVINE)
GetChromeKeySystems(std::move(cb));
#else
std::move(cb).Run({});
#endif
}
void RendererClientBase::DidSetUserAgent(const std::string& user_agent) {
#if BUILDFLAG(ENABLE_PRINTING)
printing::SetAgent(user_agent);
#endif
}
bool RendererClientBase::IsPluginHandledExternally(
content::RenderFrame* render_frame,
const blink::WebElement& plugin_element,
const GURL& original_url,
const std::string& mime_type) {
#if BUILDFLAG(ENABLE_PDF_VIEWER)
DCHECK(plugin_element.HasHTMLTagName("object") ||
plugin_element.HasHTMLTagName("embed"));
if (mime_type == pdf::kInternalPluginMimeType) {
if (IsPdfInternalPluginAllowedOrigin(
render_frame->GetWebFrame()->GetSecurityOrigin())) {
return true;
}
content::WebPluginInfo info;
info.type = content::WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS;
info.name = base::ASCIIToUTF16(kPDFInternalPluginName);
info.path = base::FilePath(kPdfPluginPath);
info.background_color = content::WebPluginInfo::kDefaultBackgroundColor;
info.mime_types.emplace_back(pdf::kInternalPluginMimeType, "pdf",
"Portable Document Format");
return extensions::MimeHandlerViewContainerManager::Get(
content::RenderFrame::FromWebFrame(
plugin_element.GetDocument().GetFrame()),
true /* create_if_does_not_exist */)
->CreateFrameContainer(plugin_element, original_url, mime_type, info);
}
return extensions::MimeHandlerViewContainerManager::Get(
content::RenderFrame::FromWebFrame(
plugin_element.GetDocument().GetFrame()),
true /* create_if_does_not_exist */)
->CreateFrameContainer(plugin_element, original_url, mime_type,
GetPDFPluginInfo());
#else
return false;
#endif
}
v8::Local<v8::Object> RendererClientBase::GetScriptableObject(
const blink::WebElement& plugin_element,
v8::Isolate* isolate) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// If there is a MimeHandlerView that can provide the scriptable object then
// MaybeCreateMimeHandlerView must have been called before and a container
// manager should exist.
auto* container_manager = extensions::MimeHandlerViewContainerManager::Get(
content::RenderFrame::FromWebFrame(
plugin_element.GetDocument().GetFrame()),
false /* create_if_does_not_exist */);
if (container_manager)
return container_manager->GetScriptableObject(plugin_element, isolate);
#endif
return v8::Local<v8::Object>();
}
std::unique_ptr<blink::WebPrescientNetworking>
RendererClientBase::CreatePrescientNetworking(
content::RenderFrame* render_frame) {
return std::make_unique<network_hints::WebPrescientNetworkingImpl>(
render_frame);
}
void RendererClientBase::RunScriptsAtDocumentStart(
content::RenderFrame* render_frame) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_.get()->RunScriptsAtDocumentStart(render_frame);
#endif
}
void RendererClientBase::RunScriptsAtDocumentIdle(
content::RenderFrame* render_frame) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_.get()->RunScriptsAtDocumentIdle(render_frame);
#endif
}
void RendererClientBase::RunScriptsAtDocumentEnd(
content::RenderFrame* render_frame) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_.get()->RunScriptsAtDocumentEnd(render_frame);
#endif
}
bool RendererClientBase::AllowScriptExtensionForServiceWorker(
const url::Origin& script_origin) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
return script_origin.scheme() == extensions::kExtensionScheme;
#else
return false;
#endif
}
void RendererClientBase::DidInitializeServiceWorkerContextOnWorkerThread(
blink::WebServiceWorkerContextProxy* context_proxy,
const GURL& service_worker_scope,
const GURL& script_url) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_->GetDispatcher()
->DidInitializeServiceWorkerContextOnWorkerThread(
context_proxy, service_worker_scope, script_url);
#endif
}
void RendererClientBase::WillEvaluateServiceWorkerOnWorkerThread(
blink::WebServiceWorkerContextProxy* context_proxy,
v8::Local<v8::Context> v8_context,
int64_t service_worker_version_id,
const GURL& service_worker_scope,
const GURL& script_url) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_->GetDispatcher()
->WillEvaluateServiceWorkerOnWorkerThread(
context_proxy, v8_context, service_worker_version_id,
service_worker_scope, script_url);
#endif
}
void RendererClientBase::DidStartServiceWorkerContextOnWorkerThread(
int64_t service_worker_version_id,
const GURL& service_worker_scope,
const GURL& script_url) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_->GetDispatcher()
->DidStartServiceWorkerContextOnWorkerThread(
service_worker_version_id, service_worker_scope, script_url);
#endif
}
void RendererClientBase::WillDestroyServiceWorkerContextOnWorkerThread(
v8::Local<v8::Context> context,
int64_t service_worker_version_id,
const GURL& service_worker_scope,
const GURL& script_url) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_->GetDispatcher()
->WillDestroyServiceWorkerContextOnWorkerThread(
context, service_worker_version_id, service_worker_scope, script_url);
#endif
}
void RendererClientBase::WebViewCreated(blink::WebView* web_view,
bool was_created_by_renderer,
const url::Origin* outermost_origin) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
new extensions::ExtensionWebViewHelper(web_view, outermost_origin);
#endif
}
v8::Local<v8::Context> RendererClientBase::GetContext(
blink::WebLocalFrame* frame,
v8::Isolate* isolate) const {
auto* render_frame = content::RenderFrame::FromWebFrame(frame);
DCHECK(render_frame);
if (render_frame && render_frame->GetBlinkPreferences().context_isolation)
return frame->GetScriptContextFromWorldId(isolate,
WorldIDs::ISOLATED_WORLD_ID);
else
return frame->MainWorldScriptContext();
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ExtensionsClient* RendererClientBase::CreateExtensionsClient() {
return new ElectronExtensionsClient;
}
#endif
bool RendererClientBase::IsWebViewFrame(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) const {
auto* isolate = context->GetIsolate();
if (render_frame->IsMainFrame())
return false;
gin::Dictionary window_dict(
isolate, GetContext(render_frame->GetWebFrame(), isolate)->Global());
v8::Local<v8::Object> frame_element;
if (!window_dict.Get("frameElement", &frame_element))
return false;
gin_helper::Dictionary frame_element_dict(isolate, frame_element);
bool is_webview = false;
return frame_element_dict.GetHidden("isWebView", &is_webview) && is_webview;
}
void RendererClientBase::SetupMainWorldOverrides(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) {
auto prefs = render_frame->GetBlinkPreferences();
// We only need to run the isolated bundle if webview is enabled
if (!prefs.webview_tag)
return;
// Setup window overrides in the main world context
// Wrap the bundle into a function that receives the isolatedApi as
// an argument.
auto* isolate = context->GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context);
auto isolated_api = gin_helper::Dictionary::CreateEmpty(isolate);
isolated_api.SetMethod("allowGuestViewElementDefinition",
&AllowGuestViewElementDefinition);
isolated_api.SetMethod("setIsWebView", &SetIsWebView);
auto source_context = GetContext(render_frame->GetWebFrame(), isolate);
gin_helper::Dictionary global(isolate, source_context->Global());
v8::Local<v8::Value> guest_view_internal;
if (global.GetHidden("guestViewInternal", &guest_view_internal)) {
api::context_bridge::ObjectCache object_cache;
auto result = api::PassValueToOtherContext(
source_context, context, guest_view_internal, &object_cache, false, 0,
api::BridgeErrorTarget::kSource);
if (!result.IsEmpty()) {
isolated_api.Set("guestViewInternal", result.ToLocalChecked());
}
}
std::vector<v8::Local<v8::String>> isolated_bundle_params = {
node::FIXED_ONE_BYTE_STRING(isolate, "isolatedApi")};
std::vector<v8::Local<v8::Value>> isolated_bundle_args = {
isolated_api.GetHandle()};
util::CompileAndCall(context, "electron/js2c/isolated_bundle",
&isolated_bundle_params, &isolated_bundle_args, nullptr);
}
// static
void RendererClientBase::AllowGuestViewElementDefinition(
v8::Isolate* isolate,
v8::Local<v8::Object> context,
v8::Local<v8::Function> register_cb) {
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context->GetCreationContextChecked());
blink::WebCustomElement::EmbedderNamesAllowedScope embedder_names_scope;
content::RenderFrame* render_frame = GetRenderFrame(context);
if (!render_frame)
return;
render_frame->GetWebFrame()->RequestExecuteV8Function(
context->GetCreationContextChecked(), register_cb, v8::Null(isolate), 0,
nullptr, base::NullCallback());
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,002 |
[Bug]: SubtleCrypto.importKey crash with "Cannot read properties of undefined" on Electron 27 Beta
|
### 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
27.0.0-beta.7
### What operating system are you using?
Other Linux
### Operating System Version
Arch Linux: Linux jabba 6.4.12-arch1-1 #1 SMP PREEMPT_DYNAMIC Thu, 24 Aug 2023 00:38:14 +0000 x86_64 GNU/Linux
### What arch are you using?
x64
### Last Known Working Electron version
26.2.2
### Expected Behavior
Web Crypto APIs should work in the worker.
### Actual Behavior
The call to `webcrypto.subtle.importKey(...)` fails in the worker on Electron 27.0.0-beta.7, but not on 26.2.2.
```
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'prototype')
at isSharedArrayBuffer (node:internal/crypto/webidl:187:57)
at Object.BufferSource (node:internal/crypto/webidl:208:9)
at SubtleCrypto.importKey (node:internal/crypto/webcrypto:585:36)
at worker.js:6:18
```
### Testcase Gist URL
https://gist.github.com/threema-danilo/a53a94800e258a0c2a6adb67ac7bfa72
### Additional Information
Check out the fiddle. Start it and open the debug console. On Electron 26.2.2, it prints "AES key was loaded". On Electron 27.0.0-beta.7, it prints the exception.
|
https://github.com/electron/electron/issues/40002
|
https://github.com/electron/electron/pull/40070
|
b0590b6ee874fbeac49bb5615525d145835eb64f
|
b3a1c6d13cfad8b0519dd7957c2f2db10acf98e8
| 2023-09-27T14:30:16Z |
c++
| 2023-10-05T08:46:53Z |
patches/node/.patches
|
refactor_alter_child_process_fork_to_use_execute_script_with.patch
feat_initialize_asar_support.patch
expose_get_builtin_module_function.patch
build_add_gn_build_files.patch
fix_add_default_values_for_variables_in_common_gypi.patch
fix_expose_tracing_agent_and_use_tracing_tracingcontroller_instead.patch
pass_all_globals_through_require.patch
build_modify_js2c_py_to_allow_injection_of_original-fs_and_custom_embedder_js.patch
refactor_allow_embedder_overriding_of_internal_fs_calls.patch
chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch
chore_add_context_to_context_aware_module_prevention.patch
fix_handle_boringssl_and_openssl_incompatibilities.patch
fix_crypto_tests_to_run_with_bssl.patch
fix_account_for_debugger_agent_race_condition.patch
fix_readbarrier_undefined_symbol_error_on_woa_arm64.patch
fix_suppress_clang_-wdeprecated-declarations_in_libuv.patch
fix_serdes_test.patch
feat_add_knostartdebugsignalhandler_to_environment_to_prevent.patch
feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch
json_parse_errors_made_user-friendly.patch
support_v8_sandboxed_pointers.patch
build_ensure_v8_pointer_compression_sandbox_is_enabled_on_64bit.patch
build_ensure_native_module_compilation_fails_if_not_using_a_new.patch
fix_override_createjob_in_node_platform.patch
v8_api_advance_api_deprecation.patch
fix_parallel_test-v8-stats.patch
fix_expose_the_built-in_electron_module_via_the_esm_loader.patch
api_pass_oomdetails_to_oomerrorcallback.patch
fix_expose_lookupandcompile_with_parameters.patch
enable_crashpad_linux_node_processes.patch
fix_lazyload_fs_in_esm_loaders_to_apply_asar_patches.patch
chore_expose_importmoduledynamically_and.patch
test_formally_mark_some_tests_as_flaky.patch
fix_adapt_debugger_tests_for_upstream_v8_changes.patch
chore_remove_--no-harmony-atomics_related_code.patch
fix_account_for_createexternalizablestring_v8_global.patch
fix_wunreachable-code_warning_in_ares_init_rand_engine.patch
fix_-wshadow_warning.patch
fix_do_not_resolve_electron_entrypoints.patch
fix_ftbfs_werror_wextra-semi.patch
fix_isurl_implementation.patch
ci_ensure_node_tests_set_electron_run_as_node.patch
chore_update_fixtures_errors_force_colors_snapshot.patch
fix_assert_module_in_the_renderer_process.patch
src_cast_v8_object_getinternalfield_return_value_to_v8_value.patch
fix_add_trusted_space_and_trusted_lo_space_to_the_v8_heap.patch
tls_ensure_tls_sockets_are_closed_if_the_underlying_wrap_closes.patch
test_deflake_test-tls-socket-close.patch
net_fix_crash_due_to_simultaneous_close_shutdown_on_js_stream.patch
net_use_asserts_in_js_socket_stream_to_catch_races_in_future.patch
lib_fix_broadcastchannel_initialization_location.patch
src_adapt_to_v8_exception_api_change.patch
lib_test_do_not_hardcode_buffer_kmaxlength.patch
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,002 |
[Bug]: SubtleCrypto.importKey crash with "Cannot read properties of undefined" on Electron 27 Beta
|
### 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
27.0.0-beta.7
### What operating system are you using?
Other Linux
### Operating System Version
Arch Linux: Linux jabba 6.4.12-arch1-1 #1 SMP PREEMPT_DYNAMIC Thu, 24 Aug 2023 00:38:14 +0000 x86_64 GNU/Linux
### What arch are you using?
x64
### Last Known Working Electron version
26.2.2
### Expected Behavior
Web Crypto APIs should work in the worker.
### Actual Behavior
The call to `webcrypto.subtle.importKey(...)` fails in the worker on Electron 27.0.0-beta.7, but not on 26.2.2.
```
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'prototype')
at isSharedArrayBuffer (node:internal/crypto/webidl:187:57)
at Object.BufferSource (node:internal/crypto/webidl:208:9)
at SubtleCrypto.importKey (node:internal/crypto/webcrypto:585:36)
at worker.js:6:18
```
### Testcase Gist URL
https://gist.github.com/threema-danilo/a53a94800e258a0c2a6adb67ac7bfa72
### Additional Information
Check out the fiddle. Start it and open the debug console. On Electron 26.2.2, it prints "AES key was loaded". On Electron 27.0.0-beta.7, it prints the exception.
|
https://github.com/electron/electron/issues/40002
|
https://github.com/electron/electron/pull/40070
|
b0590b6ee874fbeac49bb5615525d145835eb64f
|
b3a1c6d13cfad8b0519dd7957c2f2db10acf98e8
| 2023-09-27T14:30:16Z |
c++
| 2023-10-05T08:46:53Z |
patches/node/fix_handle_possible_disabled_sharedarraybuffer.patch
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,002 |
[Bug]: SubtleCrypto.importKey crash with "Cannot read properties of undefined" on Electron 27 Beta
|
### 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
27.0.0-beta.7
### What operating system are you using?
Other Linux
### Operating System Version
Arch Linux: Linux jabba 6.4.12-arch1-1 #1 SMP PREEMPT_DYNAMIC Thu, 24 Aug 2023 00:38:14 +0000 x86_64 GNU/Linux
### What arch are you using?
x64
### Last Known Working Electron version
26.2.2
### Expected Behavior
Web Crypto APIs should work in the worker.
### Actual Behavior
The call to `webcrypto.subtle.importKey(...)` fails in the worker on Electron 27.0.0-beta.7, but not on 26.2.2.
```
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'prototype')
at isSharedArrayBuffer (node:internal/crypto/webidl:187:57)
at Object.BufferSource (node:internal/crypto/webidl:208:9)
at SubtleCrypto.importKey (node:internal/crypto/webcrypto:585:36)
at worker.js:6:18
```
### Testcase Gist URL
https://gist.github.com/threema-danilo/a53a94800e258a0c2a6adb67ac7bfa72
### Additional Information
Check out the fiddle. Start it and open the debug console. On Electron 26.2.2, it prints "AES key was loaded". On Electron 27.0.0-beta.7, it prints the exception.
|
https://github.com/electron/electron/issues/40002
|
https://github.com/electron/electron/pull/40070
|
b0590b6ee874fbeac49bb5615525d145835eb64f
|
b3a1c6d13cfad8b0519dd7957c2f2db10acf98e8
| 2023-09-27T14:30:16Z |
c++
| 2023-10-05T08:46:53Z |
patches/node/.patches
|
refactor_alter_child_process_fork_to_use_execute_script_with.patch
feat_initialize_asar_support.patch
expose_get_builtin_module_function.patch
build_add_gn_build_files.patch
fix_add_default_values_for_variables_in_common_gypi.patch
fix_expose_tracing_agent_and_use_tracing_tracingcontroller_instead.patch
pass_all_globals_through_require.patch
build_modify_js2c_py_to_allow_injection_of_original-fs_and_custom_embedder_js.patch
refactor_allow_embedder_overriding_of_internal_fs_calls.patch
chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch
chore_add_context_to_context_aware_module_prevention.patch
fix_handle_boringssl_and_openssl_incompatibilities.patch
fix_crypto_tests_to_run_with_bssl.patch
fix_account_for_debugger_agent_race_condition.patch
fix_readbarrier_undefined_symbol_error_on_woa_arm64.patch
fix_suppress_clang_-wdeprecated-declarations_in_libuv.patch
fix_serdes_test.patch
feat_add_knostartdebugsignalhandler_to_environment_to_prevent.patch
feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch
json_parse_errors_made_user-friendly.patch
support_v8_sandboxed_pointers.patch
build_ensure_v8_pointer_compression_sandbox_is_enabled_on_64bit.patch
build_ensure_native_module_compilation_fails_if_not_using_a_new.patch
fix_override_createjob_in_node_platform.patch
v8_api_advance_api_deprecation.patch
fix_parallel_test-v8-stats.patch
fix_expose_the_built-in_electron_module_via_the_esm_loader.patch
api_pass_oomdetails_to_oomerrorcallback.patch
fix_expose_lookupandcompile_with_parameters.patch
enable_crashpad_linux_node_processes.patch
fix_lazyload_fs_in_esm_loaders_to_apply_asar_patches.patch
chore_expose_importmoduledynamically_and.patch
test_formally_mark_some_tests_as_flaky.patch
fix_adapt_debugger_tests_for_upstream_v8_changes.patch
chore_remove_--no-harmony-atomics_related_code.patch
fix_account_for_createexternalizablestring_v8_global.patch
fix_wunreachable-code_warning_in_ares_init_rand_engine.patch
fix_-wshadow_warning.patch
fix_do_not_resolve_electron_entrypoints.patch
fix_ftbfs_werror_wextra-semi.patch
fix_isurl_implementation.patch
ci_ensure_node_tests_set_electron_run_as_node.patch
chore_update_fixtures_errors_force_colors_snapshot.patch
fix_assert_module_in_the_renderer_process.patch
src_cast_v8_object_getinternalfield_return_value_to_v8_value.patch
fix_add_trusted_space_and_trusted_lo_space_to_the_v8_heap.patch
tls_ensure_tls_sockets_are_closed_if_the_underlying_wrap_closes.patch
test_deflake_test-tls-socket-close.patch
net_fix_crash_due_to_simultaneous_close_shutdown_on_js_stream.patch
net_use_asserts_in_js_socket_stream_to_catch_races_in_future.patch
lib_fix_broadcastchannel_initialization_location.patch
src_adapt_to_v8_exception_api_change.patch
lib_test_do_not_hardcode_buffer_kmaxlength.patch
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,002 |
[Bug]: SubtleCrypto.importKey crash with "Cannot read properties of undefined" on Electron 27 Beta
|
### 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
27.0.0-beta.7
### What operating system are you using?
Other Linux
### Operating System Version
Arch Linux: Linux jabba 6.4.12-arch1-1 #1 SMP PREEMPT_DYNAMIC Thu, 24 Aug 2023 00:38:14 +0000 x86_64 GNU/Linux
### What arch are you using?
x64
### Last Known Working Electron version
26.2.2
### Expected Behavior
Web Crypto APIs should work in the worker.
### Actual Behavior
The call to `webcrypto.subtle.importKey(...)` fails in the worker on Electron 27.0.0-beta.7, but not on 26.2.2.
```
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'prototype')
at isSharedArrayBuffer (node:internal/crypto/webidl:187:57)
at Object.BufferSource (node:internal/crypto/webidl:208:9)
at SubtleCrypto.importKey (node:internal/crypto/webcrypto:585:36)
at worker.js:6:18
```
### Testcase Gist URL
https://gist.github.com/threema-danilo/a53a94800e258a0c2a6adb67ac7bfa72
### Additional Information
Check out the fiddle. Start it and open the debug console. On Electron 26.2.2, it prints "AES key was loaded". On Electron 27.0.0-beta.7, it prints the exception.
|
https://github.com/electron/electron/issues/40002
|
https://github.com/electron/electron/pull/40070
|
b0590b6ee874fbeac49bb5615525d145835eb64f
|
b3a1c6d13cfad8b0519dd7957c2f2db10acf98e8
| 2023-09-27T14:30:16Z |
c++
| 2023-10-05T08:46:53Z |
patches/node/fix_handle_possible_disabled_sharedarraybuffer.patch
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 39,704 |
[Bug]: calling show() on child browser window will show all other children starting [email protected]
|
### 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.7.0
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.0.1
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
24.6.5
### Expected Behavior
`show()` should only display the browser window on which it is called
### Actual Behavior
When calling `show()` on a child browser window that is hidden, all child windows linked to its parent show up
### Testcase Gist URL
https://gist.github.com/Maxime117/17e8c7427184038d00e333d4eb0154d8
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39704
|
https://github.com/electron/electron/pull/40062
|
5ad69df52ea16a21561992f63b17cbaae866b77d
|
3392d9a2e74973960ca516adc1c1684e03f78414
| 2023-08-31T15:32:38Z |
c++
| 2023-10-05T13:19:57Z |
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 SetSizeConstraints(
const extensions::SizeConstraints& window_constraints) 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;
absl::optional<std::string> GetTabbingIdentifier() const 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() override;
// 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
| 39,704 |
[Bug]: calling show() on child browser window will show all other children starting [email protected]
|
### 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.7.0
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.0.1
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
24.6.5
### Expected Behavior
`show()` should only display the browser window on which it is called
### Actual Behavior
When calling `show()` on a child browser window that is hidden, all child windows linked to its parent show up
### Testcase Gist URL
https://gist.github.com/Maxime117/17e8c7427184038d00e333d4eb0154d8
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39704
|
https://github.com/electron/electron/pull/40062
|
5ad69df52ea16a21561992f63b17cbaae866b77d
|
3392d9a2e74973960ca516adc1c1684e03f78414
| 2023-08-31T15:32:38Z |
c++
| 2023-10-05T13:19:57Z |
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/apple/scoped_cftyperef.h"
#include "base/mac/mac_util.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 "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]];
}
// -[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_);
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();
while (!child_windows_.empty()) {
auto* child = child_windows_.back();
child->RemoveChildFromParentWindow();
}
// 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() {
// Ensure we're detached from the parent window before closing.
RemoveChildFromParentWindow();
while (!child_windows_.empty()) {
auto* child = child_windows_.back();
child->RemoveChildFromParentWindow();
}
[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() {
if (parent() && !is_modal()) {
parent()->RemoveChildWindow(this);
NativeWindow::SetParentWindow(nullptr);
}
}
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) {
// [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;
if (![window_ toggleFullScreenMode:nil])
fullscreen_transition_state_ = FullScreenTransitionState::kNone;
}
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::SetSizeConstraints(
const extensions::SizeConstraints& window_constraints) {
// Apply the size constraints to NSWindow.
if (window_constraints.HasMinimumSize())
[window_ setMinSize:window_constraints.GetMinimumSize().ToCGSize()];
if (window_constraints.HasMaximumSize())
[window_ setMaxSize:window_constraints.GetMaximumSize().ToCGSize()];
NativeWindow::SetSizeConstraints(window_constraints);
}
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());
}
};
// Apply the size constraints to NSWindow.
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() || is_modal()) {
[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() || is_modal()) {
[window_ orderWindow:NSWindowAbove relativeTo:0];
} else {
ReorderChildWindowAbove(window_, nullptr);
}
}
void NativeWindowMac::SetResizable(bool resizable) {
ScopedDisableResize disable_resize;
SetStyleMask(resizable, NSWindowStyleMaskResizable);
bool was_fullscreenable = IsFullScreenable();
// Right now, resizable and fullscreenable are decoupled in
// documentation and on Windows/Linux. Chromium disables
// fullscreen collection behavior as well as the maximize traffic
// light in SetCanResize if resizability is false on macOS unless
// the window is both resizable and maximizable. We want consistent
// cross-platform behavior, so if resizability is disabled we disable
// the maximize button and ensure fullscreenability matches user setting.
SetCanResize(resizable);
SetFullScreenable(was_fullscreenable);
[[window_ standardWindowButton:NSWindowZoomButton]
setEnabled:resizable ? was_fullscreenable : false];
}
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::apple::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);
const int macos_version = base::mac::MacOSMajorVersion();
// Modal window corners are rounded on macOS >= 11 or higher if the user
// hasn't passed noRoundedCorners.
bool should_round_modal =
!no_rounded_corner && (macos_version >= 11 ? true : !is_modal());
// Nonmodal window corners are rounded if they're frameless and the user
// hasn't passed noRoundedCorners.
bool should_round_nonmodal = !no_rounded_corner && !has_frame();
if (should_round_nonmodal || should_round_modal) {
CGFloat radius;
if (fullscreen) {
radius = 0.0f;
} else if (macos_version >= 11) {
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) {
NativeWindow::SetVibrancy(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;
}
absl::optional<std::string> NativeWindowMac::GetTabbingIdentifier() const {
if ([window_ tabbingMode] == NSWindowTabbingModeDisallowed)
return absl::nullopt;
return base::SysNSStringToUTF8([window_ tabbingIdentifier]);
}
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];
if (transparent() || !has_frame())
[window_ setTitlebarAppearsTransparent:NO];
}
void NativeWindowMac::NotifyWindowLeaveFullScreen() {
NativeWindow::NotifyWindowLeaveFullScreen();
// Restore window buttons.
if (buttons_proxy_ && window_button_visibility_.value_or(true)) {
[buttons_proxy_ redraw];
[buttons_proxy_ setVisible:YES];
}
if (transparent() || !has_frame())
[window_ setTitlebarAppearsTransparent: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();
// Set new parent window.
if (new_parent) {
new_parent->add_child_window(this);
if (attach)
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,704 |
[Bug]: calling show() on child browser window will show all other children starting [email protected]
|
### 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.7.0
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.0.1
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
24.6.5
### Expected Behavior
`show()` should only display the browser window on which it is called
### Actual Behavior
When calling `show()` on a child browser window that is hidden, all child windows linked to its parent show up
### Testcase Gist URL
https://gist.github.com/Maxime117/17e8c7427184038d00e333d4eb0154d8
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39704
|
https://github.com/electron/electron/pull/40062
|
5ad69df52ea16a21561992f63b17cbaae866b77d
|
3392d9a2e74973960ca516adc1c1684e03f78414
| 2023-08-31T15:32:38Z |
c++
| 2023-10-05T13:19:57Z |
shell/browser/ui/cocoa/electron_ns_window_delegate.mm
|
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/ui/cocoa/electron_ns_window_delegate.h"
#include <algorithm>
#include "base/mac/mac_util.h"
#include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h"
#include "shell/browser/browser.h"
#include "shell/browser/native_window_mac.h"
#include "shell/browser/ui/cocoa/electron_preview_item.h"
#include "shell/browser/ui/cocoa/electron_touch_bar.h"
#include "ui/gfx/geometry/resize_utils.h"
#include "ui/gfx/mac/coordinate_conversion.h"
#include "ui/views/cocoa/native_widget_mac_ns_window_host.h"
#include "ui/views/widget/native_widget_mac.h"
using TitleBarStyle = electron::NativeWindowMac::TitleBarStyle;
using FullScreenTransitionState =
electron::NativeWindow::FullScreenTransitionState;
@implementation ElectronNSWindowDelegate
- (id)initWithShell:(electron::NativeWindowMac*)shell {
// The views library assumes the window delegate must be an instance of
// ViewsNSWindowDelegate, since we don't have a way to override the creation
// of NSWindowDelegate, we have to dynamically replace the window delegate
// on the fly.
// TODO(zcbenz): Add interface in NativeWidgetMac to allow overriding creating
// window delegate.
auto* bridge_host = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow(
shell->GetNativeWindow());
auto* bridged_view = bridge_host->GetInProcessNSWindowBridge();
if ((self = [super initWithBridgedNativeWidget:bridged_view])) {
shell_ = shell;
is_zooming_ = false;
level_ = [shell_->GetNativeWindow().GetNativeNSWindow() level];
}
return self;
}
#pragma mark - NSWindowDelegate
- (void)windowDidChangeOcclusionState:(NSNotification*)notification {
// notification.object is the window that changed its state.
// It's safe to use self.window instead if you don't assign one delegate to
// many windows
NSWindow* window = notification.object;
// check occlusion binary flag
if (window.occlusionState & NSWindowOcclusionStateVisible) {
// There's a macOS bug where if a child window is minimized, and then both
// windows are restored via activation of the parent window, the child
// window is not properly deminiaturized. This causes traffic light bugs
// like the close and miniaturize buttons having no effect. We need to call
// deminiaturize on the child window to fix this. Unfortunately, this also
// hits ANOTHER bug where even after calling deminiaturize,
// windowDidDeminiaturize is not posted on the child window if it was
// incidentally restored by the parent, so we need to manually reset
// is_minimized_ here.
if (shell_->parent() && is_minimized_) {
shell_->Restore();
is_minimized_ = false;
}
shell_->NotifyWindowShow();
} else {
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];
is_minimized_ = true;
shell_->NotifyWindowMinimize();
}
- (void)windowDidDeminiaturize:(NSNotification*)notification {
[super windowDidDeminiaturize:notification];
is_minimized_ = false;
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,704 |
[Bug]: calling show() on child browser window will show all other children starting [email protected]
|
### 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.7.0
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.0.1
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
24.6.5
### Expected Behavior
`show()` should only display the browser window on which it is called
### Actual Behavior
When calling `show()` on a child browser window that is hidden, all child windows linked to its parent show up
### Testcase Gist URL
https://gist.github.com/Maxime117/17e8c7427184038d00e333d4eb0154d8
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39704
|
https://github.com/electron/electron/pull/40062
|
5ad69df52ea16a21561992f63b17cbaae866b77d
|
3392d9a2e74973960ca516adc1c1684e03f78414
| 2023-08-31T15:32:38Z |
c++
| 2023-10-05T13:19:57Z |
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));
for (const win of windows) win.show();
for (const win of windows) win.focus();
for (const win of windows) 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(async () => {
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('');
}
});
url = (await listen(server)).url;
});
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(async () => {
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('');
}
});
url = (await listen(server)).url;
});
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()', () => {
afterEach(closeAllWindows);
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);
});
it('should not crash when called on a modal child window', async () => {
const shown = once(w, 'show');
w.show();
await shown;
const child = new BrowserWindow({ modal: true, parent: w });
expect(() => { child.moveTop(); }).to.not.throw();
});
});
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'
];
for (const sourceId of fakeSourceIds) {
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];
for (const sourceId of fakeSourceIds) {
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'];
for (const sourceId of fakeSourceIds) {
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(closeAllWindows);
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('BrowserWindow.tabbingIdentifier', () => {
it('is undefined if no tabbingIdentifier was set', () => {
const w = new BrowserWindow({ show: false });
expect(w.tabbingIdentifier).to.be.undefined('tabbingIdentifier');
});
it('returns the window tabbingIdentifier', () => {
const w = new BrowserWindow({ show: false, tabbingIdentifier: 'group1' });
expect(w.tabbingIdentifier).to.equal('group1');
});
});
});
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._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);
});
});
});
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.replaceAll('\\', '/')
: 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.replaceAll('\\', '/')
: 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 });
const errorPattern = /Failed to read a named property 'document' from 'Window': Blocked a frame with origin "(.*?)" from accessing a cross-origin frame./;
expect(popupAccessMessage).to.be.a('string',
'child\'s .document is accessible from its parent window');
expect(popupAccessMessage).to.match(errorPattern);
expect(openerAccessMessage).to.be.a('string',
'opener .document is accessible from a popup window');
expect(openerAccessMessage).to.match(errorPattern);
});
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('Failed to read a named property \'toString\' from \'Location\': 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');
});
});
// TODO(codebytere): figure out how to make these pass in CI on Windows.
ifdescribe(process.platform !== 'win32')('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');
});
it('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');
}
});
it('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');
});
it('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');
});
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');
}
});
it('visibilityState remains visible if backgroundThrottling is disabled', async () => {
const w = new BrowserWindow({
show: false,
width: 100,
height: 100,
webPreferences: {
backgroundThrottling: false,
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');
}
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', async () => {
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();
const closed = once(childWindow, 'closed');
window.close();
await closed;
expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw();
});
});
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');
});
});
it('does not open non-fullscreenable child windows in fullscreen if parent is fullscreen', async () => {
const w = new BrowserWindow();
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
const child = new BrowserWindow({ parent: w, resizable: false, fullscreenable: false });
const shown = once(child, 'show');
await shown;
expect(child.resizable).to.be.false('resizable');
expect(child.fullScreen).to.be.false('fullscreen');
expect(child.fullScreenable).to.be.false('fullscreenable');
});
it('is set correctly with different resizable values', async () => {
const w1 = new BrowserWindow({
resizable: false,
fullscreenable: false
});
const w2 = new BrowserWindow({
resizable: true,
fullscreenable: false
});
const w3 = new BrowserWindow({
fullscreenable: false
});
expect(w1.isFullScreenable()).to.be.false('isFullScreenable');
expect(w2.isFullScreenable()).to.be.false('isFullScreenable');
expect(w3.isFullScreenable()).to.be.false('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 });
const isValidWindow = require('@electron-ci/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,704 |
[Bug]: calling show() on child browser window will show all other children starting [email protected]
|
### 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.7.0
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.0.1
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
24.6.5
### Expected Behavior
`show()` should only display the browser window on which it is called
### Actual Behavior
When calling `show()` on a child browser window that is hidden, all child windows linked to its parent show up
### Testcase Gist URL
https://gist.github.com/Maxime117/17e8c7427184038d00e333d4eb0154d8
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39704
|
https://github.com/electron/electron/pull/40062
|
5ad69df52ea16a21561992f63b17cbaae866b77d
|
3392d9a2e74973960ca516adc1c1684e03f78414
| 2023-08-31T15:32:38Z |
c++
| 2023-10-05T13:19:57Z |
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 SetSizeConstraints(
const extensions::SizeConstraints& window_constraints) 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;
absl::optional<std::string> GetTabbingIdentifier() const 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() override;
// 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
| 39,704 |
[Bug]: calling show() on child browser window will show all other children starting [email protected]
|
### 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.7.0
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.0.1
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
24.6.5
### Expected Behavior
`show()` should only display the browser window on which it is called
### Actual Behavior
When calling `show()` on a child browser window that is hidden, all child windows linked to its parent show up
### Testcase Gist URL
https://gist.github.com/Maxime117/17e8c7427184038d00e333d4eb0154d8
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39704
|
https://github.com/electron/electron/pull/40062
|
5ad69df52ea16a21561992f63b17cbaae866b77d
|
3392d9a2e74973960ca516adc1c1684e03f78414
| 2023-08-31T15:32:38Z |
c++
| 2023-10-05T13:19:57Z |
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/apple/scoped_cftyperef.h"
#include "base/mac/mac_util.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 "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]];
}
// -[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_);
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();
while (!child_windows_.empty()) {
auto* child = child_windows_.back();
child->RemoveChildFromParentWindow();
}
// 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() {
// Ensure we're detached from the parent window before closing.
RemoveChildFromParentWindow();
while (!child_windows_.empty()) {
auto* child = child_windows_.back();
child->RemoveChildFromParentWindow();
}
[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() {
if (parent() && !is_modal()) {
parent()->RemoveChildWindow(this);
NativeWindow::SetParentWindow(nullptr);
}
}
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) {
// [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;
if (![window_ toggleFullScreenMode:nil])
fullscreen_transition_state_ = FullScreenTransitionState::kNone;
}
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::SetSizeConstraints(
const extensions::SizeConstraints& window_constraints) {
// Apply the size constraints to NSWindow.
if (window_constraints.HasMinimumSize())
[window_ setMinSize:window_constraints.GetMinimumSize().ToCGSize()];
if (window_constraints.HasMaximumSize())
[window_ setMaxSize:window_constraints.GetMaximumSize().ToCGSize()];
NativeWindow::SetSizeConstraints(window_constraints);
}
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());
}
};
// Apply the size constraints to NSWindow.
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() || is_modal()) {
[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() || is_modal()) {
[window_ orderWindow:NSWindowAbove relativeTo:0];
} else {
ReorderChildWindowAbove(window_, nullptr);
}
}
void NativeWindowMac::SetResizable(bool resizable) {
ScopedDisableResize disable_resize;
SetStyleMask(resizable, NSWindowStyleMaskResizable);
bool was_fullscreenable = IsFullScreenable();
// Right now, resizable and fullscreenable are decoupled in
// documentation and on Windows/Linux. Chromium disables
// fullscreen collection behavior as well as the maximize traffic
// light in SetCanResize if resizability is false on macOS unless
// the window is both resizable and maximizable. We want consistent
// cross-platform behavior, so if resizability is disabled we disable
// the maximize button and ensure fullscreenability matches user setting.
SetCanResize(resizable);
SetFullScreenable(was_fullscreenable);
[[window_ standardWindowButton:NSWindowZoomButton]
setEnabled:resizable ? was_fullscreenable : false];
}
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::apple::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);
const int macos_version = base::mac::MacOSMajorVersion();
// Modal window corners are rounded on macOS >= 11 or higher if the user
// hasn't passed noRoundedCorners.
bool should_round_modal =
!no_rounded_corner && (macos_version >= 11 ? true : !is_modal());
// Nonmodal window corners are rounded if they're frameless and the user
// hasn't passed noRoundedCorners.
bool should_round_nonmodal = !no_rounded_corner && !has_frame();
if (should_round_nonmodal || should_round_modal) {
CGFloat radius;
if (fullscreen) {
radius = 0.0f;
} else if (macos_version >= 11) {
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) {
NativeWindow::SetVibrancy(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;
}
absl::optional<std::string> NativeWindowMac::GetTabbingIdentifier() const {
if ([window_ tabbingMode] == NSWindowTabbingModeDisallowed)
return absl::nullopt;
return base::SysNSStringToUTF8([window_ tabbingIdentifier]);
}
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];
if (transparent() || !has_frame())
[window_ setTitlebarAppearsTransparent:NO];
}
void NativeWindowMac::NotifyWindowLeaveFullScreen() {
NativeWindow::NotifyWindowLeaveFullScreen();
// Restore window buttons.
if (buttons_proxy_ && window_button_visibility_.value_or(true)) {
[buttons_proxy_ redraw];
[buttons_proxy_ setVisible:YES];
}
if (transparent() || !has_frame())
[window_ setTitlebarAppearsTransparent: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();
// Set new parent window.
if (new_parent) {
new_parent->add_child_window(this);
if (attach)
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,704 |
[Bug]: calling show() on child browser window will show all other children starting [email protected]
|
### 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.7.0
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.0.1
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
24.6.5
### Expected Behavior
`show()` should only display the browser window on which it is called
### Actual Behavior
When calling `show()` on a child browser window that is hidden, all child windows linked to its parent show up
### Testcase Gist URL
https://gist.github.com/Maxime117/17e8c7427184038d00e333d4eb0154d8
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39704
|
https://github.com/electron/electron/pull/40062
|
5ad69df52ea16a21561992f63b17cbaae866b77d
|
3392d9a2e74973960ca516adc1c1684e03f78414
| 2023-08-31T15:32:38Z |
c++
| 2023-10-05T13:19:57Z |
shell/browser/ui/cocoa/electron_ns_window_delegate.mm
|
// Copyright (c) 2018 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/ui/cocoa/electron_ns_window_delegate.h"
#include <algorithm>
#include "base/mac/mac_util.h"
#include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h"
#include "shell/browser/browser.h"
#include "shell/browser/native_window_mac.h"
#include "shell/browser/ui/cocoa/electron_preview_item.h"
#include "shell/browser/ui/cocoa/electron_touch_bar.h"
#include "ui/gfx/geometry/resize_utils.h"
#include "ui/gfx/mac/coordinate_conversion.h"
#include "ui/views/cocoa/native_widget_mac_ns_window_host.h"
#include "ui/views/widget/native_widget_mac.h"
using TitleBarStyle = electron::NativeWindowMac::TitleBarStyle;
using FullScreenTransitionState =
electron::NativeWindow::FullScreenTransitionState;
@implementation ElectronNSWindowDelegate
- (id)initWithShell:(electron::NativeWindowMac*)shell {
// The views library assumes the window delegate must be an instance of
// ViewsNSWindowDelegate, since we don't have a way to override the creation
// of NSWindowDelegate, we have to dynamically replace the window delegate
// on the fly.
// TODO(zcbenz): Add interface in NativeWidgetMac to allow overriding creating
// window delegate.
auto* bridge_host = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow(
shell->GetNativeWindow());
auto* bridged_view = bridge_host->GetInProcessNSWindowBridge();
if ((self = [super initWithBridgedNativeWidget:bridged_view])) {
shell_ = shell;
is_zooming_ = false;
level_ = [shell_->GetNativeWindow().GetNativeNSWindow() level];
}
return self;
}
#pragma mark - NSWindowDelegate
- (void)windowDidChangeOcclusionState:(NSNotification*)notification {
// notification.object is the window that changed its state.
// It's safe to use self.window instead if you don't assign one delegate to
// many windows
NSWindow* window = notification.object;
// check occlusion binary flag
if (window.occlusionState & NSWindowOcclusionStateVisible) {
// There's a macOS bug where if a child window is minimized, and then both
// windows are restored via activation of the parent window, the child
// window is not properly deminiaturized. This causes traffic light bugs
// like the close and miniaturize buttons having no effect. We need to call
// deminiaturize on the child window to fix this. Unfortunately, this also
// hits ANOTHER bug where even after calling deminiaturize,
// windowDidDeminiaturize is not posted on the child window if it was
// incidentally restored by the parent, so we need to manually reset
// is_minimized_ here.
if (shell_->parent() && is_minimized_) {
shell_->Restore();
is_minimized_ = false;
}
shell_->NotifyWindowShow();
} else {
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];
is_minimized_ = true;
shell_->NotifyWindowMinimize();
}
- (void)windowDidDeminiaturize:(NSNotification*)notification {
[super windowDidDeminiaturize:notification];
is_minimized_ = false;
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,704 |
[Bug]: calling show() on child browser window will show all other children starting [email protected]
|
### 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.7.0
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.0.1
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
24.6.5
### Expected Behavior
`show()` should only display the browser window on which it is called
### Actual Behavior
When calling `show()` on a child browser window that is hidden, all child windows linked to its parent show up
### Testcase Gist URL
https://gist.github.com/Maxime117/17e8c7427184038d00e333d4eb0154d8
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39704
|
https://github.com/electron/electron/pull/40062
|
5ad69df52ea16a21561992f63b17cbaae866b77d
|
3392d9a2e74973960ca516adc1c1684e03f78414
| 2023-08-31T15:32:38Z |
c++
| 2023-10-05T13:19:57Z |
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));
for (const win of windows) win.show();
for (const win of windows) win.focus();
for (const win of windows) 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(async () => {
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('');
}
});
url = (await listen(server)).url;
});
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(async () => {
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('');
}
});
url = (await listen(server)).url;
});
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()', () => {
afterEach(closeAllWindows);
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);
});
it('should not crash when called on a modal child window', async () => {
const shown = once(w, 'show');
w.show();
await shown;
const child = new BrowserWindow({ modal: true, parent: w });
expect(() => { child.moveTop(); }).to.not.throw();
});
});
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'
];
for (const sourceId of fakeSourceIds) {
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];
for (const sourceId of fakeSourceIds) {
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'];
for (const sourceId of fakeSourceIds) {
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(closeAllWindows);
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('BrowserWindow.tabbingIdentifier', () => {
it('is undefined if no tabbingIdentifier was set', () => {
const w = new BrowserWindow({ show: false });
expect(w.tabbingIdentifier).to.be.undefined('tabbingIdentifier');
});
it('returns the window tabbingIdentifier', () => {
const w = new BrowserWindow({ show: false, tabbingIdentifier: 'group1' });
expect(w.tabbingIdentifier).to.equal('group1');
});
});
});
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._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);
});
});
});
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.replaceAll('\\', '/')
: 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.replaceAll('\\', '/')
: 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 });
const errorPattern = /Failed to read a named property 'document' from 'Window': Blocked a frame with origin "(.*?)" from accessing a cross-origin frame./;
expect(popupAccessMessage).to.be.a('string',
'child\'s .document is accessible from its parent window');
expect(popupAccessMessage).to.match(errorPattern);
expect(openerAccessMessage).to.be.a('string',
'opener .document is accessible from a popup window');
expect(openerAccessMessage).to.match(errorPattern);
});
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('Failed to read a named property \'toString\' from \'Location\': 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');
});
});
// TODO(codebytere): figure out how to make these pass in CI on Windows.
ifdescribe(process.platform !== 'win32')('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');
});
it('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');
}
});
it('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');
});
it('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');
});
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');
}
});
it('visibilityState remains visible if backgroundThrottling is disabled', async () => {
const w = new BrowserWindow({
show: false,
width: 100,
height: 100,
webPreferences: {
backgroundThrottling: false,
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');
}
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', async () => {
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();
const closed = once(childWindow, 'closed');
window.close();
await closed;
expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw();
});
});
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');
});
});
it('does not open non-fullscreenable child windows in fullscreen if parent is fullscreen', async () => {
const w = new BrowserWindow();
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
const child = new BrowserWindow({ parent: w, resizable: false, fullscreenable: false });
const shown = once(child, 'show');
await shown;
expect(child.resizable).to.be.false('resizable');
expect(child.fullScreen).to.be.false('fullscreen');
expect(child.fullScreenable).to.be.false('fullscreenable');
});
it('is set correctly with different resizable values', async () => {
const w1 = new BrowserWindow({
resizable: false,
fullscreenable: false
});
const w2 = new BrowserWindow({
resizable: true,
fullscreenable: false
});
const w3 = new BrowserWindow({
fullscreenable: false
});
expect(w1.isFullScreenable()).to.be.false('isFullScreenable');
expect(w2.isFullScreenable()).to.be.false('isFullScreenable');
expect(w3.isFullScreenable()).to.be.false('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 });
const isValidWindow = require('@electron-ci/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,991 |
[Bug]: After minimizing the devtool window and opening it again, the devtool window cannot be found
|
### 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.1.0
### What operating system are you using?
Windows
### Operating System Version
win 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
After minimizing the devtool window, open it again and you can see the window normally
### Actual Behavior
After minimizing the devtool window and opening it again, the devtool window cannot be found
### Testcase Gist URL
https://gist.github.com/c985de2d95ffedb47bc966edaf3bfe8c
### Additional Information
https://github.com/electron/electron/assets/71307878/2b8bc4f7-e33a-415c-8033-76ad46f11954
|
https://github.com/electron/electron/issues/39991
|
https://github.com/electron/electron/pull/40091
|
8f7a48879ef8633a76279803637cdee7f7c6cd4f
|
73553032ea99929b1511d6e873ec81328a42a356
| 2023-09-27T09:08:02Z |
c++
| 2023-10-06T00:26:31Z |
shell/browser/ui/views/inspectable_web_contents_view_views.cc
|
// Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "shell/browser/ui/views/inspectable_web_contents_view_views.h"
#include <memory>
#include <utility>
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_delegate.h"
#include "shell/browser/ui/inspectable_web_contents_view_delegate.h"
#include "ui/base/models/image_model.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/client_view.h"
namespace electron {
namespace {
class DevToolsWindowDelegate : public views::ClientView,
public views::WidgetDelegate {
public:
DevToolsWindowDelegate(InspectableWebContentsViewViews* shell,
views::View* view,
views::Widget* widget)
: views::ClientView(widget, view),
shell_(shell),
view_(view),
widget_(widget) {
SetOwnedByWidget(true);
set_owned_by_client();
if (shell->GetDelegate())
icon_ = shell->GetDelegate()->GetDevToolsWindowIcon();
}
~DevToolsWindowDelegate() override = default;
// disable copy
DevToolsWindowDelegate(const DevToolsWindowDelegate&) = delete;
DevToolsWindowDelegate& operator=(const DevToolsWindowDelegate&) = delete;
// views::WidgetDelegate:
views::View* GetInitiallyFocusedView() override { return view_; }
std::u16string GetWindowTitle() const override { return shell_->GetTitle(); }
ui::ImageModel GetWindowAppIcon() override { return GetWindowIcon(); }
ui::ImageModel GetWindowIcon() override { return icon_; }
views::Widget* GetWidget() override { return widget_; }
const views::Widget* GetWidget() const override { return widget_; }
views::View* GetContentsView() override { return view_; }
views::ClientView* CreateClientView(views::Widget* widget) override {
return this;
}
// views::ClientView:
views::CloseRequestResult OnWindowCloseRequested() override {
shell_->inspectable_web_contents()->CloseDevTools();
return views::CloseRequestResult::kCannotClose;
}
private:
raw_ptr<InspectableWebContentsViewViews> shell_;
raw_ptr<views::View> view_;
raw_ptr<views::Widget> widget_;
ui::ImageModel icon_;
};
} // namespace
InspectableWebContentsView* CreateInspectableContentsView(
InspectableWebContents* inspectable_web_contents) {
return new InspectableWebContentsViewViews(inspectable_web_contents);
}
InspectableWebContentsViewViews::InspectableWebContentsViewViews(
InspectableWebContents* inspectable_web_contents)
: InspectableWebContentsView(inspectable_web_contents),
devtools_web_view_(new views::WebView(nullptr)),
title_(u"Developer Tools") {
if (!inspectable_web_contents_->IsGuest() &&
inspectable_web_contents_->GetWebContents()->GetNativeView()) {
auto* contents_web_view = new views::WebView(nullptr);
contents_web_view->SetWebContents(
inspectable_web_contents_->GetWebContents());
contents_web_view_ = contents_web_view;
} else {
contents_web_view_ = new views::Label(u"No content under offscreen mode");
}
devtools_web_view_->SetVisible(false);
AddChildView(devtools_web_view_.get());
AddChildView(contents_web_view_.get());
}
InspectableWebContentsViewViews::~InspectableWebContentsViewViews() {
if (devtools_window_)
inspectable_web_contents()->SaveDevToolsBounds(
devtools_window_->GetWindowBoundsInScreen());
}
views::View* InspectableWebContentsViewViews::GetView() {
return this;
}
void InspectableWebContentsViewViews::ShowDevTools(bool activate) {
if (devtools_visible_)
return;
devtools_visible_ = true;
if (devtools_window_) {
devtools_window_web_view_->SetWebContents(
inspectable_web_contents_->GetDevToolsWebContents());
devtools_window_->SetBounds(
inspectable_web_contents()->GetDevToolsBounds());
if (activate) {
devtools_window_->Show();
} else {
devtools_window_->ShowInactive();
}
// Update draggable regions to account for the new dock position.
if (GetDelegate())
GetDelegate()->DevToolsResized();
} else {
devtools_web_view_->SetVisible(true);
devtools_web_view_->SetWebContents(
inspectable_web_contents_->GetDevToolsWebContents());
devtools_web_view_->RequestFocus();
Layout();
}
}
void InspectableWebContentsViewViews::CloseDevTools() {
if (!devtools_visible_)
return;
devtools_visible_ = false;
if (devtools_window_) {
inspectable_web_contents()->SaveDevToolsBounds(
devtools_window_->GetWindowBoundsInScreen());
devtools_window_.reset();
devtools_window_web_view_ = nullptr;
devtools_window_delegate_ = nullptr;
} else {
devtools_web_view_->SetVisible(false);
devtools_web_view_->SetWebContents(nullptr);
Layout();
}
}
bool InspectableWebContentsViewViews::IsDevToolsViewShowing() {
return devtools_visible_;
}
bool InspectableWebContentsViewViews::IsDevToolsViewFocused() {
if (devtools_window_web_view_)
return devtools_window_web_view_->HasFocus();
else if (devtools_web_view_)
return devtools_web_view_->HasFocus();
else
return false;
}
void InspectableWebContentsViewViews::SetIsDocked(bool docked, bool activate) {
CloseDevTools();
if (!docked) {
devtools_window_ = std::make_unique<views::Widget>();
devtools_window_web_view_ = new views::WebView(nullptr);
devtools_window_delegate_ = new DevToolsWindowDelegate(
this, devtools_window_web_view_, devtools_window_.get());
views::Widget::InitParams params;
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.delegate = devtools_window_delegate_;
params.bounds = inspectable_web_contents()->GetDevToolsBounds();
#if BUILDFLAG(IS_LINUX)
params.wm_role_name = "devtools";
if (GetDelegate())
GetDelegate()->GetDevToolsWindowWMClass(¶ms.wm_class_name,
¶ms.wm_class_class);
#endif
devtools_window_->Init(std::move(params));
devtools_window_->UpdateWindowIcon();
devtools_window_->widget_delegate()->SetHasWindowSizeControls(true);
}
ShowDevTools(activate);
}
void InspectableWebContentsViewViews::SetContentsResizingStrategy(
const DevToolsContentsResizingStrategy& strategy) {
strategy_.CopyFrom(strategy);
Layout();
}
void InspectableWebContentsViewViews::SetTitle(const std::u16string& title) {
if (devtools_window_) {
title_ = title;
devtools_window_->UpdateWindowTitle();
}
}
const std::u16string InspectableWebContentsViewViews::GetTitle() {
return title_;
}
void InspectableWebContentsViewViews::Layout() {
if (!devtools_web_view_->GetVisible()) {
contents_web_view_->SetBoundsRect(GetContentsBounds());
// Propagate layout call to all children, for example browser views.
View::Layout();
return;
}
gfx::Size container_size(width(), height());
gfx::Rect new_devtools_bounds;
gfx::Rect new_contents_bounds;
ApplyDevToolsContentsResizingStrategy(
strategy_, container_size, &new_devtools_bounds, &new_contents_bounds);
// DevTools cares about the specific position, so we have to compensate RTL
// layout here.
new_devtools_bounds.set_x(GetMirroredXForRect(new_devtools_bounds));
new_contents_bounds.set_x(GetMirroredXForRect(new_contents_bounds));
devtools_web_view_->SetBoundsRect(new_devtools_bounds);
contents_web_view_->SetBoundsRect(new_contents_bounds);
// Propagate layout call to all children, for example browser views.
View::Layout();
if (GetDelegate())
GetDelegate()->DevToolsResized();
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 39,991 |
[Bug]: After minimizing the devtool window and opening it again, the devtool window cannot be found
|
### 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.1.0
### What operating system are you using?
Windows
### Operating System Version
win 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
After minimizing the devtool window, open it again and you can see the window normally
### Actual Behavior
After minimizing the devtool window and opening it again, the devtool window cannot be found
### Testcase Gist URL
https://gist.github.com/c985de2d95ffedb47bc966edaf3bfe8c
### Additional Information
https://github.com/electron/electron/assets/71307878/2b8bc4f7-e33a-415c-8033-76ad46f11954
|
https://github.com/electron/electron/issues/39991
|
https://github.com/electron/electron/pull/40091
|
8f7a48879ef8633a76279803637cdee7f7c6cd4f
|
73553032ea99929b1511d6e873ec81328a42a356
| 2023-09-27T09:08:02Z |
c++
| 2023-10-06T00:26:31Z |
shell/browser/ui/views/inspectable_web_contents_view_views.cc
|
// Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "shell/browser/ui/views/inspectable_web_contents_view_views.h"
#include <memory>
#include <utility>
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_delegate.h"
#include "shell/browser/ui/inspectable_web_contents_view_delegate.h"
#include "ui/base/models/image_model.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/client_view.h"
namespace electron {
namespace {
class DevToolsWindowDelegate : public views::ClientView,
public views::WidgetDelegate {
public:
DevToolsWindowDelegate(InspectableWebContentsViewViews* shell,
views::View* view,
views::Widget* widget)
: views::ClientView(widget, view),
shell_(shell),
view_(view),
widget_(widget) {
SetOwnedByWidget(true);
set_owned_by_client();
if (shell->GetDelegate())
icon_ = shell->GetDelegate()->GetDevToolsWindowIcon();
}
~DevToolsWindowDelegate() override = default;
// disable copy
DevToolsWindowDelegate(const DevToolsWindowDelegate&) = delete;
DevToolsWindowDelegate& operator=(const DevToolsWindowDelegate&) = delete;
// views::WidgetDelegate:
views::View* GetInitiallyFocusedView() override { return view_; }
std::u16string GetWindowTitle() const override { return shell_->GetTitle(); }
ui::ImageModel GetWindowAppIcon() override { return GetWindowIcon(); }
ui::ImageModel GetWindowIcon() override { return icon_; }
views::Widget* GetWidget() override { return widget_; }
const views::Widget* GetWidget() const override { return widget_; }
views::View* GetContentsView() override { return view_; }
views::ClientView* CreateClientView(views::Widget* widget) override {
return this;
}
// views::ClientView:
views::CloseRequestResult OnWindowCloseRequested() override {
shell_->inspectable_web_contents()->CloseDevTools();
return views::CloseRequestResult::kCannotClose;
}
private:
raw_ptr<InspectableWebContentsViewViews> shell_;
raw_ptr<views::View> view_;
raw_ptr<views::Widget> widget_;
ui::ImageModel icon_;
};
} // namespace
InspectableWebContentsView* CreateInspectableContentsView(
InspectableWebContents* inspectable_web_contents) {
return new InspectableWebContentsViewViews(inspectable_web_contents);
}
InspectableWebContentsViewViews::InspectableWebContentsViewViews(
InspectableWebContents* inspectable_web_contents)
: InspectableWebContentsView(inspectable_web_contents),
devtools_web_view_(new views::WebView(nullptr)),
title_(u"Developer Tools") {
if (!inspectable_web_contents_->IsGuest() &&
inspectable_web_contents_->GetWebContents()->GetNativeView()) {
auto* contents_web_view = new views::WebView(nullptr);
contents_web_view->SetWebContents(
inspectable_web_contents_->GetWebContents());
contents_web_view_ = contents_web_view;
} else {
contents_web_view_ = new views::Label(u"No content under offscreen mode");
}
devtools_web_view_->SetVisible(false);
AddChildView(devtools_web_view_.get());
AddChildView(contents_web_view_.get());
}
InspectableWebContentsViewViews::~InspectableWebContentsViewViews() {
if (devtools_window_)
inspectable_web_contents()->SaveDevToolsBounds(
devtools_window_->GetWindowBoundsInScreen());
}
views::View* InspectableWebContentsViewViews::GetView() {
return this;
}
void InspectableWebContentsViewViews::ShowDevTools(bool activate) {
if (devtools_visible_)
return;
devtools_visible_ = true;
if (devtools_window_) {
devtools_window_web_view_->SetWebContents(
inspectable_web_contents_->GetDevToolsWebContents());
devtools_window_->SetBounds(
inspectable_web_contents()->GetDevToolsBounds());
if (activate) {
devtools_window_->Show();
} else {
devtools_window_->ShowInactive();
}
// Update draggable regions to account for the new dock position.
if (GetDelegate())
GetDelegate()->DevToolsResized();
} else {
devtools_web_view_->SetVisible(true);
devtools_web_view_->SetWebContents(
inspectable_web_contents_->GetDevToolsWebContents());
devtools_web_view_->RequestFocus();
Layout();
}
}
void InspectableWebContentsViewViews::CloseDevTools() {
if (!devtools_visible_)
return;
devtools_visible_ = false;
if (devtools_window_) {
inspectable_web_contents()->SaveDevToolsBounds(
devtools_window_->GetWindowBoundsInScreen());
devtools_window_.reset();
devtools_window_web_view_ = nullptr;
devtools_window_delegate_ = nullptr;
} else {
devtools_web_view_->SetVisible(false);
devtools_web_view_->SetWebContents(nullptr);
Layout();
}
}
bool InspectableWebContentsViewViews::IsDevToolsViewShowing() {
return devtools_visible_;
}
bool InspectableWebContentsViewViews::IsDevToolsViewFocused() {
if (devtools_window_web_view_)
return devtools_window_web_view_->HasFocus();
else if (devtools_web_view_)
return devtools_web_view_->HasFocus();
else
return false;
}
void InspectableWebContentsViewViews::SetIsDocked(bool docked, bool activate) {
CloseDevTools();
if (!docked) {
devtools_window_ = std::make_unique<views::Widget>();
devtools_window_web_view_ = new views::WebView(nullptr);
devtools_window_delegate_ = new DevToolsWindowDelegate(
this, devtools_window_web_view_, devtools_window_.get());
views::Widget::InitParams params;
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.delegate = devtools_window_delegate_;
params.bounds = inspectable_web_contents()->GetDevToolsBounds();
#if BUILDFLAG(IS_LINUX)
params.wm_role_name = "devtools";
if (GetDelegate())
GetDelegate()->GetDevToolsWindowWMClass(¶ms.wm_class_name,
¶ms.wm_class_class);
#endif
devtools_window_->Init(std::move(params));
devtools_window_->UpdateWindowIcon();
devtools_window_->widget_delegate()->SetHasWindowSizeControls(true);
}
ShowDevTools(activate);
}
void InspectableWebContentsViewViews::SetContentsResizingStrategy(
const DevToolsContentsResizingStrategy& strategy) {
strategy_.CopyFrom(strategy);
Layout();
}
void InspectableWebContentsViewViews::SetTitle(const std::u16string& title) {
if (devtools_window_) {
title_ = title;
devtools_window_->UpdateWindowTitle();
}
}
const std::u16string InspectableWebContentsViewViews::GetTitle() {
return title_;
}
void InspectableWebContentsViewViews::Layout() {
if (!devtools_web_view_->GetVisible()) {
contents_web_view_->SetBoundsRect(GetContentsBounds());
// Propagate layout call to all children, for example browser views.
View::Layout();
return;
}
gfx::Size container_size(width(), height());
gfx::Rect new_devtools_bounds;
gfx::Rect new_contents_bounds;
ApplyDevToolsContentsResizingStrategy(
strategy_, container_size, &new_devtools_bounds, &new_contents_bounds);
// DevTools cares about the specific position, so we have to compensate RTL
// layout here.
new_devtools_bounds.set_x(GetMirroredXForRect(new_devtools_bounds));
new_contents_bounds.set_x(GetMirroredXForRect(new_contents_bounds));
devtools_web_view_->SetBoundsRect(new_devtools_bounds);
contents_web_view_->SetBoundsRect(new_contents_bounds);
// Propagate layout call to all children, for example browser views.
View::Layout();
if (GetDelegate())
GetDelegate()->DevToolsResized();
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,039 |
[Bug]: BrowserWindow vibrancy doesn't apply without transparency
|
### 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
27.0.0-beta.2
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.5.2
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
27.0.0-beta.1
### Expected Behavior
Including `vibrancy: 'titlebar'` in BrowserWindow constructor options results in a window with background vibrancy.
### Actual Behavior
A white background is displayed without window vibrancy.
### Testcase Gist URL
https://gist.github.com/df665de6732858c3536198cef517fae9
### Additional Information
Regression from https://github.com/electron/electron/pull/39708
|
https://github.com/electron/electron/issues/40039
|
https://github.com/electron/electron/pull/40109
|
a55c163db02a3092226ba20731b08292404561d4
|
cff50ac65a9c6d4f53aa74570ea42859466c4469
| 2023-09-28T16:54:55Z |
c++
| 2023-10-06T18:57:26Z |
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 "include/core/SkColor.h"
#include "shell/browser/background_throttling_source.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/compositor/compositor.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, ¢er) && 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 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
}
options.Get(options::kFullScreenable, &fullscreenable);
SetFullScreenable(fullscreenable);
if (fullscreen)
SetFullScreen(true);
bool resizable;
if (options.Get(options::kResizable, &resizable)) {
SetResizable(resizable);
}
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
SkColor background_color = SK_ColorWHITE;
if (std::string color; options.Get(options::kBackgroundColor, &color)) {
background_color = ParseCSSColor(color);
} else if (IsTranslucent()) {
background_color = SK_ColorTRANSPARENT;
}
SetBackgroundColor(background_color);
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();
}
// Windows/Linux:
// 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.
//
// macOS:
// The min/max sizes are set directly by calling NSWindow's methods.
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
}
absl::optional<std::string> NativeWindow::GetTabbingIdentifier() const {
return ""; // for non-Mac platforms
}
void NativeWindow::SetVibrancy(const std::string& type) {
vibrancy_ = type;
}
void NativeWindow::SetBackgroundMaterial(const std::string& type) {
background_material_ = 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; });
}
void NativeWindow::AddBackgroundThrottlingSource(
BackgroundThrottlingSource* source) {
auto result = background_throttling_sources_.insert(source);
DCHECK(result.second) << "Added already stored BackgroundThrottlingSource.";
UpdateBackgroundThrottlingState();
}
void NativeWindow::RemoveBackgroundThrottlingSource(
BackgroundThrottlingSource* source) {
auto result = background_throttling_sources_.erase(source);
DCHECK(result == 1)
<< "Tried to remove non existing BackgroundThrottlingSource.";
UpdateBackgroundThrottlingState();
}
void NativeWindow::UpdateBackgroundThrottlingState() {
if (!GetWidget() || !GetWidget()->GetCompositor()) {
return;
}
bool enable_background_throttling = true;
for (const auto* background_throttling_source :
background_throttling_sources_) {
if (!background_throttling_source->GetBackgroundThrottling()) {
enable_background_throttling = false;
break;
}
}
GetWidget()->GetCompositor()->SetBackgroundThrottling(
enable_background_throttling);
}
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;
bool NativeWindow::IsTranslucent() const {
// Transparent windows are translucent
if (transparent()) {
return true;
}
#if BUILDFLAG(IS_MAC)
// Windows with vibrancy set are translucent
if (!vibrancy().empty()) {
return true;
}
#endif
#if BUILDFLAG(IS_WIN)
// Windows with certain background materials may be translucent
const std::string& bg_material = background_material();
if (!bg_material.empty() && bg_material != "none") {
return true;
}
#endif
return false;
}
// 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
| 40,039 |
[Bug]: BrowserWindow vibrancy doesn't apply without transparency
|
### 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
27.0.0-beta.2
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.5.2
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
27.0.0-beta.1
### Expected Behavior
Including `vibrancy: 'titlebar'` in BrowserWindow constructor options results in a window with background vibrancy.
### Actual Behavior
A white background is displayed without window vibrancy.
### Testcase Gist URL
https://gist.github.com/df665de6732858c3536198cef517fae9
### Additional Information
Regression from https://github.com/electron/electron/pull/39708
|
https://github.com/electron/electron/issues/40039
|
https://github.com/electron/electron/pull/40109
|
a55c163db02a3092226ba20731b08292404561d4
|
cff50ac65a9c6d4f53aa74570ea42859466c4469
| 2023-09-28T16:54:55Z |
c++
| 2023-10-06T18:57:26Z |
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 "include/core/SkColor.h"
#include "shell/browser/background_throttling_source.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/compositor/compositor.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, ¢er) && 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 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
}
options.Get(options::kFullScreenable, &fullscreenable);
SetFullScreenable(fullscreenable);
if (fullscreen)
SetFullScreen(true);
bool resizable;
if (options.Get(options::kResizable, &resizable)) {
SetResizable(resizable);
}
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
SkColor background_color = SK_ColorWHITE;
if (std::string color; options.Get(options::kBackgroundColor, &color)) {
background_color = ParseCSSColor(color);
} else if (IsTranslucent()) {
background_color = SK_ColorTRANSPARENT;
}
SetBackgroundColor(background_color);
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();
}
// Windows/Linux:
// 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.
//
// macOS:
// The min/max sizes are set directly by calling NSWindow's methods.
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
}
absl::optional<std::string> NativeWindow::GetTabbingIdentifier() const {
return ""; // for non-Mac platforms
}
void NativeWindow::SetVibrancy(const std::string& type) {
vibrancy_ = type;
}
void NativeWindow::SetBackgroundMaterial(const std::string& type) {
background_material_ = 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; });
}
void NativeWindow::AddBackgroundThrottlingSource(
BackgroundThrottlingSource* source) {
auto result = background_throttling_sources_.insert(source);
DCHECK(result.second) << "Added already stored BackgroundThrottlingSource.";
UpdateBackgroundThrottlingState();
}
void NativeWindow::RemoveBackgroundThrottlingSource(
BackgroundThrottlingSource* source) {
auto result = background_throttling_sources_.erase(source);
DCHECK(result == 1)
<< "Tried to remove non existing BackgroundThrottlingSource.";
UpdateBackgroundThrottlingState();
}
void NativeWindow::UpdateBackgroundThrottlingState() {
if (!GetWidget() || !GetWidget()->GetCompositor()) {
return;
}
bool enable_background_throttling = true;
for (const auto* background_throttling_source :
background_throttling_sources_) {
if (!background_throttling_source->GetBackgroundThrottling()) {
enable_background_throttling = false;
break;
}
}
GetWidget()->GetCompositor()->SetBackgroundThrottling(
enable_background_throttling);
}
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;
bool NativeWindow::IsTranslucent() const {
// Transparent windows are translucent
if (transparent()) {
return true;
}
#if BUILDFLAG(IS_MAC)
// Windows with vibrancy set are translucent
if (!vibrancy().empty()) {
return true;
}
#endif
#if BUILDFLAG(IS_WIN)
// Windows with certain background materials may be translucent
const std::string& bg_material = background_material();
if (!bg_material.empty() && bg_material != "none") {
return true;
}
#endif
return false;
}
// 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
| 19,847 |
[Bug]: loadURL after did-start-loading crashes electron
|
### Preflight Checklist
* [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project.
* [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to.
* [X] I have searched the issue tracker for an issue that matches the one I want to file, without success.
### Issue Details
* **Electron Version:**
* 5.0.10 , 6 ,7
* **Operating System:**
* Windows 10
* **Last Known Working Electron version:** ?
### Expected Behavior
No crash
### Actual Behavior
In electron 5 it crashes with the following code: 2147483651
in electron 6 and 7 it just seems to hang but is basically dead
### To Reproduce
```
const { app, BrowserWindow, BrowserView } = require("electron");
const init = () => {
let browserWindow = new BrowserWindow({
show: true,
});
browserWindow.loadURL("https://www.google.com");
let browserWindow2 = new BrowserWindow({
show: true,
});
browserWindow2.webContents.once("did-start-loading", () => {
browserWindow2.loadURL("https://www.google.com");
});
browserWindow2.loadURL("https://www.test.com");
};
app.on("ready", () => {
init();
});
```
<!--
If you provide a URL, please list the commands required to clone/setup/run your repo e.g.
```sh
$ git clone $YOUR_URL -b $BRANCH
$ npm install
$ npm start || electron .
```
-->
### Additional Information
<!-- Add any other context about the problem here. -->
|
https://github.com/electron/electron/issues/19847
|
https://github.com/electron/electron/pull/40143
|
563c370d51f302b6d4a7fee8b47e1cc3e1ca2fe3
|
86df4db6f10afbe5872f8ecbcbfe6191374fc1f7
| 2019-08-20T20:05:40Z |
c++
| 2023-10-10T10:46:04Z |
shell/browser/api/electron_api_web_contents.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_web_contents.h"
#include <limits>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/containers/contains.h"
#include "base/containers/fixed_flat_map.h"
#include "base/containers/id_map.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/current_thread.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
#include "chrome/browser/ui/views/eye_dropper/eye_dropper.h"
#include "chrome/common/pref_names.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/security_state/content/content_utils.h"
#include "components/security_state/core/security_state.h"
#include "content/browser/renderer_host/frame_tree_node.h" // nogncheck
#include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/desktop_media_id.h"
#include "content/public/browser/desktop_streams_registry.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/service_worker_context.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/input/native_web_keyboard_event.h"
#include "content/public/common/referrer_type_converters.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/webplugininfo.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "gin/arguments.h"
#include "gin/data_object_builder.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "media/base/mime_util.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "ppapi/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "printing/print_job_constants.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/browser/api/electron_api_browser_window.h"
#include "shell/browser/api/electron_api_debugger.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/api/electron_api_web_frame_main.h"
#include "shell/browser/api/message_port.h"
#include "shell/browser/browser.h"
#include "shell/browser/child_web_contents_tracker.h"
#include "shell/browser/electron_autofill_driver_factory.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/electron_javascript_dialog_manager.h"
#include "shell/browser/electron_navigation_throttle.h"
#include "shell/browser/file_select_helper.h"
#include "shell/browser/native_window.h"
#include "shell/browser/osr/osr_render_widget_host_view.h"
#include "shell/browser/osr/osr_web_contents_view.h"
#include "shell/browser/session_preferences.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/file_dialog.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/browser/web_contents_zoom_controller.h"
#include "shell/browser/web_view_guest_delegate.h"
#include "shell/browser/web_view_manager.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/color_util.h"
#include "shell/common/electron_constants.h"
#include "shell/common/gin_converters/base_converter.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/content_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/frame_converter.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/optional_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/language_util.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "shell/common/thread_restrictions.h"
#include "shell/common/v8_value_serializer.h"
#include "storage/browser/file_system/isolated_context.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/mojom/frame/find_in_page.mojom.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h"
#include "third_party/blink/public/mojom/renderer_preferences.mojom.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
#if BUILDFLAG(IS_WIN)
#include "shell/browser/native_window_views.h"
#endif
#if !BUILDFLAG(IS_MAC)
#include "ui/aura/window.h"
#else
#include "ui/base/cocoa/defaults_utils.h"
#endif
#if BUILDFLAG(IS_LINUX)
#include "ui/linux/linux_ui.h"
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
#include "ui/gfx/font_render_params.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/script_executor.h"
#include "extensions/browser/view_type_utils.h"
#include "extensions/common/mojom/view_type.mojom.h"
#include "shell/browser/extensions/electron_extension_web_contents_observer.h"
#endif
#if BUILDFLAG(ENABLE_PRINTING)
#include "chrome/browser/printing/print_view_manager_base.h"
#include "components/printing/browser/print_manager_utils.h"
#include "components/printing/browser/print_to_pdf/pdf_print_result.h"
#include "components/printing/browser/print_to_pdf/pdf_print_utils.h"
#include "printing/backend/print_backend.h" // nogncheck
#include "printing/mojom/print.mojom.h" // nogncheck
#include "printing/page_range.h"
#include "shell/browser/printing/print_view_manager_electron.h"
#if BUILDFLAG(IS_WIN)
#include "printing/backend/win_helper.h"
#endif
#endif // BUILDFLAG(ENABLE_PRINTING)
#if BUILDFLAG(ENABLE_PDF_VIEWER)
#include "components/pdf/browser/pdf_document_helper.h" // nogncheck
#include "shell/browser/electron_pdf_document_helper_client.h"
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/public/browser/plugin_service.h"
#endif
#if !IS_MAS_BUILD()
#include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck
#endif
namespace gin {
#if BUILDFLAG(ENABLE_PRINTING)
template <>
struct Converter<printing::mojom::MarginType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::MarginType* out) {
using Val = printing::mojom::MarginType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"custom", Val::kCustomMargins},
{"default", Val::kDefaultMargins},
{"none", Val::kNoMargins},
{"printableArea", Val::kPrintableAreaMargins},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<printing::mojom::DuplexMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::DuplexMode* out) {
using Val = printing::mojom::DuplexMode;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"longEdge", Val::kLongEdge},
{"shortEdge", Val::kShortEdge},
{"simplex", Val::kSimplex},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
#endif
template <>
struct Converter<WindowOpenDisposition> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
WindowOpenDisposition val) {
std::string disposition = "other";
switch (val) {
case WindowOpenDisposition::CURRENT_TAB:
disposition = "default";
break;
case WindowOpenDisposition::NEW_FOREGROUND_TAB:
disposition = "foreground-tab";
break;
case WindowOpenDisposition::NEW_BACKGROUND_TAB:
disposition = "background-tab";
break;
case WindowOpenDisposition::NEW_POPUP:
case WindowOpenDisposition::NEW_WINDOW:
disposition = "new-window";
break;
case WindowOpenDisposition::SAVE_TO_DISK:
disposition = "save-to-disk";
break;
default:
break;
}
return gin::ConvertToV8(isolate, disposition);
}
};
template <>
struct Converter<content::SavePageType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
content::SavePageType* out) {
using Val = content::SavePageType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"htmlcomplete", Val::SAVE_PAGE_TYPE_AS_COMPLETE_HTML},
{"htmlonly", Val::SAVE_PAGE_TYPE_AS_ONLY_HTML},
{"mhtml", Val::SAVE_PAGE_TYPE_AS_MHTML},
});
return FromV8WithLowerLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<electron::api::WebContents::Type> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
electron::api::WebContents::Type val) {
using Type = electron::api::WebContents::Type;
std::string type;
switch (val) {
case Type::kBackgroundPage:
type = "backgroundPage";
break;
case Type::kBrowserWindow:
type = "window";
break;
case Type::kBrowserView:
type = "browserView";
break;
case Type::kRemote:
type = "remote";
break;
case Type::kWebView:
type = "webview";
break;
case Type::kOffScreen:
type = "offscreen";
break;
default:
break;
}
return gin::ConvertToV8(isolate, type);
}
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::api::WebContents::Type* out) {
using Val = electron::api::WebContents::Type;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"backgroundPage", Val::kBackgroundPage},
{"browserView", Val::kBrowserView},
{"offscreen", Val::kOffScreen},
{"webview", Val::kWebView},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<scoped_refptr<content::DevToolsAgentHost>> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const scoped_refptr<content::DevToolsAgentHost>& val) {
gin_helper::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("id", val->GetId());
dict.Set("url", val->GetURL().spec());
return dict.GetHandle();
}
};
} // namespace gin
namespace electron::api {
namespace {
constexpr base::StringPiece CursorTypeToString(
ui::mojom::CursorType cursor_type) {
switch (cursor_type) {
case ui::mojom::CursorType::kPointer:
return "pointer";
case ui::mojom::CursorType::kCross:
return "crosshair";
case ui::mojom::CursorType::kHand:
return "hand";
case ui::mojom::CursorType::kIBeam:
return "text";
case ui::mojom::CursorType::kWait:
return "wait";
case ui::mojom::CursorType::kHelp:
return "help";
case ui::mojom::CursorType::kEastResize:
return "e-resize";
case ui::mojom::CursorType::kNorthResize:
return "n-resize";
case ui::mojom::CursorType::kNorthEastResize:
return "ne-resize";
case ui::mojom::CursorType::kNorthWestResize:
return "nw-resize";
case ui::mojom::CursorType::kSouthResize:
return "s-resize";
case ui::mojom::CursorType::kSouthEastResize:
return "se-resize";
case ui::mojom::CursorType::kSouthWestResize:
return "sw-resize";
case ui::mojom::CursorType::kWestResize:
return "w-resize";
case ui::mojom::CursorType::kNorthSouthResize:
return "ns-resize";
case ui::mojom::CursorType::kEastWestResize:
return "ew-resize";
case ui::mojom::CursorType::kNorthEastSouthWestResize:
return "nesw-resize";
case ui::mojom::CursorType::kNorthWestSouthEastResize:
return "nwse-resize";
case ui::mojom::CursorType::kColumnResize:
return "col-resize";
case ui::mojom::CursorType::kRowResize:
return "row-resize";
case ui::mojom::CursorType::kMiddlePanning:
return "m-panning";
case ui::mojom::CursorType::kMiddlePanningVertical:
return "m-panning-vertical";
case ui::mojom::CursorType::kMiddlePanningHorizontal:
return "m-panning-horizontal";
case ui::mojom::CursorType::kEastPanning:
return "e-panning";
case ui::mojom::CursorType::kNorthPanning:
return "n-panning";
case ui::mojom::CursorType::kNorthEastPanning:
return "ne-panning";
case ui::mojom::CursorType::kNorthWestPanning:
return "nw-panning";
case ui::mojom::CursorType::kSouthPanning:
return "s-panning";
case ui::mojom::CursorType::kSouthEastPanning:
return "se-panning";
case ui::mojom::CursorType::kSouthWestPanning:
return "sw-panning";
case ui::mojom::CursorType::kWestPanning:
return "w-panning";
case ui::mojom::CursorType::kMove:
return "move";
case ui::mojom::CursorType::kVerticalText:
return "vertical-text";
case ui::mojom::CursorType::kCell:
return "cell";
case ui::mojom::CursorType::kContextMenu:
return "context-menu";
case ui::mojom::CursorType::kAlias:
return "alias";
case ui::mojom::CursorType::kProgress:
return "progress";
case ui::mojom::CursorType::kNoDrop:
return "nodrop";
case ui::mojom::CursorType::kCopy:
return "copy";
case ui::mojom::CursorType::kNone:
return "none";
case ui::mojom::CursorType::kNotAllowed:
return "not-allowed";
case ui::mojom::CursorType::kZoomIn:
return "zoom-in";
case ui::mojom::CursorType::kZoomOut:
return "zoom-out";
case ui::mojom::CursorType::kGrab:
return "grab";
case ui::mojom::CursorType::kGrabbing:
return "grabbing";
case ui::mojom::CursorType::kCustom:
return "custom";
case ui::mojom::CursorType::kNull:
return "null";
case ui::mojom::CursorType::kDndNone:
return "drag-drop-none";
case ui::mojom::CursorType::kDndMove:
return "drag-drop-move";
case ui::mojom::CursorType::kDndCopy:
return "drag-drop-copy";
case ui::mojom::CursorType::kDndLink:
return "drag-drop-link";
case ui::mojom::CursorType::kNorthSouthNoResize:
return "ns-no-resize";
case ui::mojom::CursorType::kEastWestNoResize:
return "ew-no-resize";
case ui::mojom::CursorType::kNorthEastSouthWestNoResize:
return "nesw-no-resize";
case ui::mojom::CursorType::kNorthWestSouthEastNoResize:
return "nwse-no-resize";
default:
return "default";
}
}
base::IDMap<WebContents*>& GetAllWebContents() {
static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents;
return *s_all_web_contents;
}
void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise,
base::ScopedClosureRunner capture_handle,
const SkBitmap& bitmap) {
// Hack to enable transparency in captured image
promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap));
capture_handle.RunAndReset();
}
absl::optional<base::TimeDelta> GetCursorBlinkInterval() {
#if BUILDFLAG(IS_MAC)
absl::optional<base::TimeDelta> system_value(
ui::TextInsertionCaretBlinkPeriodFromDefaults());
if (system_value)
return *system_value;
#elif BUILDFLAG(IS_LINUX)
if (auto* linux_ui = ui::LinuxUi::instance())
return linux_ui->GetCursorBlinkInterval();
#elif BUILDFLAG(IS_WIN)
const auto system_msec = ::GetCaretBlinkTime();
if (system_msec != 0) {
return (system_msec == INFINITE) ? base::TimeDelta()
: base::Milliseconds(system_msec);
}
#endif
return absl::nullopt;
}
#if BUILDFLAG(ENABLE_PRINTING)
// This will return false if no printer with the provided device_name can be
// found on the network. We need to check this because Chromium does not do
// sanity checking of device_name validity and so will crash on invalid names.
bool IsDeviceNameValid(const std::u16string& device_name) {
#if BUILDFLAG(IS_MAC)
base::apple::ScopedCFTypeRef<CFStringRef> new_printer_id(
base::SysUTF16ToCFStringRef(device_name));
PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get());
bool printer_exists = new_printer != nullptr;
PMRelease(new_printer);
return printer_exists;
#else
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name));
#endif
}
// This function returns a validated device name.
// If the user passed one to webContents.print(), we check that it's valid and
// return it or fail if the network doesn't recognize it. If the user didn't
// pass a device name, we first try to return the system default printer. If one
// isn't set, then pull all the printers and use the first one or fail if none
// exist.
std::pair<std::string, std::u16string> GetDeviceNameToUse(
const std::u16string& device_name) {
#if BUILDFLAG(IS_WIN)
// Blocking is needed here because Windows printer drivers are oftentimes
// not thread-safe and have to be accessed on the UI thread.
ScopedAllowBlockingForElectron allow_blocking;
#endif
if (!device_name.empty()) {
if (!IsDeviceNameValid(device_name))
return std::make_pair("Invalid deviceName provided", std::u16string());
return std::make_pair(std::string(), device_name);
}
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
std::string printer_name;
printing::mojom::ResultCode code =
print_backend->GetDefaultPrinterName(printer_name);
// We don't want to return if this fails since some devices won't have a
// default printer.
if (code != printing::mojom::ResultCode::kSuccess)
LOG(ERROR) << "Failed to get default printer name";
if (printer_name.empty()) {
printing::PrinterList printers;
if (print_backend->EnumeratePrinters(printers) !=
printing::mojom::ResultCode::kSuccess)
return std::make_pair("Failed to enumerate printers", std::u16string());
if (printers.empty())
return std::make_pair("No printers available on the network",
std::u16string());
printer_name = printers.front().printer_name;
}
return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name));
}
// Copied from
// chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54
scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() {
// USER_VISIBLE because the result is displayed in the print preview dialog.
#if !BUILDFLAG(IS_WIN)
static constexpr base::TaskTraits kTraits = {
base::MayBlock(), base::TaskPriority::USER_VISIBLE};
#endif
#if defined(USE_CUPS)
// CUPS is thread safe.
return base::ThreadPool::CreateTaskRunner(kTraits);
#elif BUILDFLAG(IS_WIN)
// Windows drivers are likely not thread-safe and need to be accessed on the
// UI thread.
return content::GetUIThreadTaskRunner({base::TaskPriority::USER_VISIBLE});
#else
// Be conservative on unsupported platforms.
return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits);
#endif
}
#endif
struct UserDataLink : public base::SupportsUserData::Data {
explicit UserDataLink(base::WeakPtr<WebContents> contents)
: web_contents(contents) {}
base::WeakPtr<WebContents> web_contents;
};
const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey;
const char kRootName[] = "<root>";
struct FileSystem {
FileSystem() = default;
FileSystem(const std::string& type,
const std::string& file_system_name,
const std::string& root_url,
const std::string& file_system_path)
: type(type),
file_system_name(file_system_name),
root_url(root_url),
file_system_path(file_system_path) {}
std::string type;
std::string file_system_name;
std::string root_url;
std::string file_system_path;
};
std::string RegisterFileSystem(content::WebContents* web_contents,
const base::FilePath& path) {
auto* isolated_context = storage::IsolatedContext::GetInstance();
std::string root_name(kRootName);
storage::IsolatedContext::ScopedFSHandle file_system =
isolated_context->RegisterFileSystemForPath(
storage::kFileSystemTypeLocal, std::string(), path, &root_name);
content::ChildProcessSecurityPolicy* policy =
content::ChildProcessSecurityPolicy::GetInstance();
content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
int renderer_id = render_view_host->GetProcess()->GetID();
policy->GrantReadFileSystem(renderer_id, file_system.id());
policy->GrantWriteFileSystem(renderer_id, file_system.id());
policy->GrantCreateFileForFileSystem(renderer_id, file_system.id());
policy->GrantDeleteFromFileSystem(renderer_id, file_system.id());
if (!policy->CanReadFile(renderer_id, path))
policy->GrantReadFile(renderer_id, path);
return file_system.id();
}
FileSystem CreateFileSystemStruct(content::WebContents* web_contents,
const std::string& file_system_id,
const std::string& file_system_path,
const std::string& type) {
const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL();
std::string file_system_name =
storage::GetIsolatedFileSystemName(origin, file_system_id);
std::string root_url = storage::GetIsolatedFileSystemRootURIString(
origin, file_system_id, kRootName);
return FileSystem(type, file_system_name, root_url, file_system_path);
}
base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) {
base::Value::Dict value;
value.Set("type", file_system.type);
value.Set("fileSystemName", file_system.file_system_name);
value.Set("rootURL", file_system.root_url);
value.Set("fileSystemPath", file_system.file_system_path);
return value;
}
void WriteToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::WriteFile(path, content.data(), content.size());
}
void AppendToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::AppendToFile(path, content);
}
PrefService* GetPrefService(content::WebContents* web_contents) {
auto* context = web_contents->GetBrowserContext();
return static_cast<electron::ElectronBrowserContext*>(context)->prefs();
}
std::map<std::string, std::string> GetAddedFileSystemPaths(
content::WebContents* web_contents) {
auto* pref_service = GetPrefService(web_contents);
const base::Value::Dict& file_system_paths =
pref_service->GetDict(prefs::kDevToolsFileSystemPaths);
std::map<std::string, std::string> result;
for (auto it : file_system_paths) {
std::string type =
it.second.is_string() ? it.second.GetString() : std::string();
result[it.first] = type;
}
return result;
}
bool IsDevToolsFileSystemAdded(content::WebContents* web_contents,
const std::string& file_system_path) {
return base::Contains(GetAddedFileSystemPaths(web_contents),
file_system_path);
}
void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) {
rwhv->SetBackgroundColor(color);
static_cast<content::RenderWidgetHostViewBase*>(rwhv)
->SetContentBackgroundColor(color);
}
content::RenderFrameHost* GetRenderFrameHost(
content::NavigationHandle* navigation_handle) {
int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId();
content::FrameTreeNode* frame_tree_node =
content::FrameTreeNode::GloballyFindByID(frame_tree_node_id);
content::RenderFrameHostManager* render_manager =
frame_tree_node->render_manager();
content::RenderFrameHost* frame_host = nullptr;
if (render_manager) {
frame_host = render_manager->speculative_frame_host();
if (!frame_host)
frame_host = render_manager->current_frame_host();
}
return frame_host;
}
} // namespace
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) {
switch (view_type) {
case extensions::mojom::ViewType::kExtensionBackgroundPage:
return WebContents::Type::kBackgroundPage;
case extensions::mojom::ViewType::kAppWindow:
case extensions::mojom::ViewType::kComponent:
case extensions::mojom::ViewType::kExtensionDialog:
case extensions::mojom::ViewType::kExtensionPopup:
case extensions::mojom::ViewType::kBackgroundContents:
case extensions::mojom::ViewType::kExtensionGuest:
case extensions::mojom::ViewType::kTabContents:
case extensions::mojom::ViewType::kOffscreenDocument:
case extensions::mojom::ViewType::kExtensionSidePanel:
case extensions::mojom::ViewType::kInvalid:
return WebContents::Type::kRemote;
}
}
#endif
WebContents::WebContents(v8::Isolate* isolate,
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
type_(Type::kRemote),
id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// WebContents created by extension host will have valid ViewType set.
extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents);
if (view_type != extensions::mojom::ViewType::kInvalid) {
InitWithExtensionView(isolate, web_contents, view_type);
}
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents);
script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents);
#endif
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
SetUserAgent(GetBrowserContext()->GetUserAgent());
web_contents->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type)
: content::WebContentsObserver(web_contents.get()),
type_(type),
id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
DCHECK(type != Type::kRemote)
<< "Can't take ownership of a remote WebContents";
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
InitWithSessionAndOptions(isolate, std::move(web_contents), session,
gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
const gin_helper::Dictionary& options)
: id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
// Read options.
options.Get("backgroundThrottling", &background_throttling_);
// Get type
options.Get("type", &type_);
bool b = false;
if (options.Get(options::kOffscreen, &b) && b)
type_ = Type::kOffScreen;
// Init embedder earlier
options.Get("embedder", &embedder_);
// Whether to enable DevTools.
options.Get("devTools", &enable_devtools_);
// BrowserViews are not attached to a window initially so they should start
// off as hidden. This is also important for compositor recycling. See:
// https://github.com/electron/electron/pull/21372
bool initially_shown = type_ != Type::kBrowserView;
options.Get(options::kShow, &initially_shown);
// Obtain the session.
std::string partition;
gin::Handle<api::Session> session;
if (options.Get("session", &session) && !session.IsEmpty()) {
} else if (options.Get("partition", &partition)) {
session = Session::FromPartition(isolate, partition);
} else {
// Use the default session if not specified.
session = Session::FromPartition(isolate, "");
}
session_.Reset(isolate, session.ToV8());
std::unique_ptr<content::WebContents> web_contents;
if (IsGuest()) {
scoped_refptr<content::SiteInstance> site_instance =
content::SiteInstance::CreateForURL(session->browser_context(),
GURL("chrome-guest://fake-host"));
content::WebContents::CreateParams params(session->browser_context(),
site_instance);
guest_delegate_ =
std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this);
params.guest_delegate = guest_delegate_.get();
if (embedder_ && embedder_->IsOffScreen()) {
auto* view = new OffScreenWebContentsView(
false,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
web_contents = content::WebContents::Create(params);
}
} else if (IsOffScreen()) {
// webPreferences does not have a transparent option, so if the window needs
// to be transparent, that will be set at electron_api_browser_window.cc#L57
// and we then need to pull it back out and check it here.
std::string background_color;
options.GetHidden(options::kBackgroundColor, &background_color);
bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT;
content::WebContents::CreateParams params(session->browser_context());
auto* view = new OffScreenWebContentsView(
transparent,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
content::WebContents::CreateParams params(session->browser_context());
params.initially_hidden = !initially_shown;
web_contents = content::WebContents::Create(params);
}
InitWithSessionAndOptions(isolate, std::move(web_contents), session, options);
}
void WebContents::InitZoomController(content::WebContents* web_contents,
const gin_helper::Dictionary& options) {
WebContentsZoomController::CreateForWebContents(web_contents);
zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
double zoom_factor;
if (options.Get(options::kZoomFactor, &zoom_factor))
zoom_controller_->SetDefaultZoomFactor(zoom_factor);
// Nothing to do with ZoomController, but this function gets called in all
// init cases!
content::RenderViewHost* host = web_contents->GetRenderViewHost();
if (host)
host->GetWidget()->AddInputEventObserver(this);
}
void WebContents::InitWithSessionAndOptions(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> owned_web_contents,
gin::Handle<api::Session> session,
const gin_helper::Dictionary& options) {
Observe(owned_web_contents.get());
InitWithWebContents(std::move(owned_web_contents), session->browser_context(),
IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
auto* prefs = web_contents()->GetMutableRendererPrefs();
// Collect preferred languages from OS and browser process. accept_languages
// effects HTTP header, navigator.languages, and CJK fallback font selection.
//
// Note that an application locale set to the browser process might be
// different with the one set to the preference list.
// (e.g. overridden with --lang)
std::string accept_languages =
g_browser_process->GetApplicationLocale() + ",";
for (auto const& language : electron::GetPreferredLanguages()) {
if (language == g_browser_process->GetApplicationLocale())
continue;
accept_languages += language + ",";
}
accept_languages.pop_back();
prefs->accept_languages = accept_languages;
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
// Update font settings.
static const gfx::FontRenderParams params(
gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr));
prefs->should_antialias_text = params.antialiasing;
prefs->use_subpixel_positioning = params.subpixel_positioning;
prefs->hinting = params.hinting;
prefs->use_autohinter = params.autohinter;
prefs->use_bitmaps = params.use_bitmaps;
prefs->subpixel_rendering = params.subpixel_rendering;
#endif
// Honor the system's cursor blink rate settings
if (auto interval = GetCursorBlinkInterval())
prefs->caret_blink_interval = *interval;
// Save the preferences in C++.
// If there's already a WebContentsPreferences object, we created it as part
// of the webContents.setWindowOpenHandler path, so don't overwrite it.
if (!WebContentsPreferences::From(web_contents())) {
new WebContentsPreferences(web_contents(), options);
}
// Trigger re-calculation of webkit prefs.
web_contents()->NotifyPreferencesChanged();
WebContentsPermissionHelper::CreateForWebContents(web_contents());
InitZoomController(web_contents(), options);
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents());
script_executor_ =
std::make_unique<extensions::ScriptExecutor>(web_contents());
#endif
AutofillDriverFactory::CreateForWebContents(web_contents());
SetUserAgent(GetBrowserContext()->GetUserAgent());
if (IsGuest()) {
NativeWindow* owner_window = nullptr;
if (embedder_) {
// New WebContents's owner_window is the embedder's owner_window.
auto* relay =
NativeWindowRelay::FromWebContents(embedder_->web_contents());
if (relay)
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
}
web_contents()->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
void WebContents::InitWithExtensionView(v8::Isolate* isolate,
content::WebContents* web_contents,
extensions::mojom::ViewType view_type) {
// Must reassign type prior to calling `Init`.
type_ = GetTypeFromViewType(view_type);
if (type_ == Type::kRemote)
return;
if (type_ == Type::kBackgroundPage)
// non-background-page WebContents are retained by other classes. We need
// to pin here to prevent background-page WebContents from being GC'd.
// The background page api::WebContents will live until the underlying
// content::WebContents is destroyed.
Pin(isolate);
// Allow toggling DevTools for background pages
Observe(web_contents);
InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents),
GetBrowserContext(), IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
}
#endif
void WebContents::InitWithWebContents(
std::unique_ptr<content::WebContents> web_contents,
ElectronBrowserContext* browser_context,
bool is_guest) {
browser_context_ = browser_context;
web_contents->SetDelegate(this);
#if BUILDFLAG(ENABLE_PRINTING)
PrintViewManagerElectron::CreateForWebContents(web_contents.get());
#endif
// Determine whether the WebContents is offscreen.
auto* web_preferences = WebContentsPreferences::From(web_contents.get());
offscreen_ = web_preferences && web_preferences->IsOffscreen();
// Create InspectableWebContents.
inspectable_web_contents_ = std::make_unique<InspectableWebContents>(
std::move(web_contents), browser_context->prefs(), is_guest);
inspectable_web_contents_->SetDelegate(this);
}
WebContents::~WebContents() {
if (owner_window_) {
owner_window_->RemoveBackgroundThrottlingSource(this);
}
if (web_contents()) {
content::RenderViewHost* host = web_contents()->GetRenderViewHost();
if (host)
host->GetWidget()->RemoveInputEventObserver(this);
}
if (!inspectable_web_contents_) {
WebContentsDestroyed();
return;
}
inspectable_web_contents_->GetView()->SetDelegate(nullptr);
// This event is only for internal use, which is emitted when WebContents is
// being destroyed.
Emit("will-destroy");
// For guest view based on OOPIF, the WebContents is released by the embedder
// frame, and we need to clear the reference to the memory.
bool not_owned_by_this = IsGuest() && attached_;
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// And background pages are owned by extensions::ExtensionHost.
if (type_ == Type::kBackgroundPage)
not_owned_by_this = true;
#endif
if (not_owned_by_this) {
inspectable_web_contents_->ReleaseWebContents();
WebContentsDestroyed();
}
// InspectableWebContents will be automatically destroyed.
}
void WebContents::DeleteThisIfAlive() {
// It is possible that the FirstWeakCallback has been called but the
// SecondWeakCallback has not, in this case the garbage collection of
// WebContents has already started and we should not |delete this|.
// Calling |GetWrapper| can detect this corner case.
auto* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
delete this;
}
void WebContents::Destroy() {
// The content::WebContents should be destroyed asynchronously when possible
// as user may choose to destroy WebContents during an event of it.
if (Browser::Get()->is_shutting_down() || IsGuest()) {
DeleteThisIfAlive();
} else {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&WebContents::DeleteThisIfAlive, GetWeakPtr()));
}
}
void WebContents::Close(absl::optional<gin_helper::Dictionary> options) {
bool dispatch_beforeunload = false;
if (options)
options->Get("waitForBeforeUnload", &dispatch_beforeunload);
if (dispatch_beforeunload &&
web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) {
NotifyUserActivation();
web_contents()->DispatchBeforeUnload(false /* auto_cancel */);
} else {
web_contents()->Close();
}
}
bool WebContents::DidAddMessageToConsole(
content::WebContents* source,
blink::mojom::ConsoleMessageLevel level,
const std::u16string& message,
int32_t line_no,
const std::u16string& source_id) {
return Emit("console-message", static_cast<int32_t>(level), message, line_no,
source_id);
}
void WebContents::OnCreateWindow(
const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const std::string& features,
const scoped_refptr<network::ResourceRequestBody>& body) {
Emit("-new-window", target_url, frame_name, disposition, features, referrer,
body);
}
void WebContents::WebContentsCreatedWithFullParams(
content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const content::mojom::CreateNewWindowParams& params,
content::WebContents* new_contents) {
ChildWebContentsTracker::CreateForWebContents(new_contents);
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents);
tracker->url = params.target_url;
tracker->frame_name = params.frame_name;
tracker->referrer = params.referrer.To<content::Referrer>();
tracker->raw_features = params.raw_features;
tracker->body = params.body;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary dict;
gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate),
&dict);
pending_child_web_preferences_.Reset();
// Associate the preferences passed in via `setWindowOpenHandler` with the
// content::WebContents that was just created for the child window. These
// preferences will be picked up by the RenderWidgetHost via its call to the
// delegate's OverrideWebkitPrefs.
new WebContentsPreferences(new_contents, dict);
}
bool WebContents::IsWebContentsCreationOverridden(
content::SiteInstance* source_site_instance,
content::mojom::WindowContainerType window_container_type,
const GURL& opener_url,
const content::mojom::CreateNewWindowParams& params) {
bool default_prevented = Emit(
"-will-add-new-contents", params.target_url, params.frame_name,
params.raw_features, params.disposition, *params.referrer, params.body);
// If the app prevented the default, redirect to CreateCustomWebContents,
// which always returns nullptr, which will result in the window open being
// prevented (window.open() will return null in the renderer).
return default_prevented;
}
void WebContents::SetNextChildWebPreferences(
const gin_helper::Dictionary preferences) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
// Store these prefs for when Chrome calls WebContentsCreatedWithFullParams
// with the new child contents.
pending_child_web_preferences_.Reset(isolate, preferences.GetHandle());
}
content::WebContents* WebContents::CreateCustomWebContents(
content::RenderFrameHost* opener,
content::SiteInstance* source_site_instance,
bool is_new_browsing_instance,
const GURL& opener_url,
const std::string& frame_name,
const GURL& target_url,
const content::StoragePartitionConfig& partition_config,
content::SessionStorageNamespace* session_storage_namespace) {
return nullptr;
}
void WebContents::AddNewContents(
content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) {
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get());
DCHECK(tracker);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto api_web_contents =
CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow);
// We call RenderFrameCreated here as at this point the empty "about:blank"
// render frame has already been created. If the window never navigates again
// RenderFrameCreated won't be called and certain prefs like
// "kBackgroundColor" will not be applied.
auto* frame = api_web_contents->MainFrame();
if (frame) {
api_web_contents->HandleNewRenderFrame(frame);
}
if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
window_features.bounds.x(), window_features.bounds.y(),
window_features.bounds.width(), window_features.bounds.height(),
tracker->url, tracker->frame_name, tracker->referrer,
tracker->raw_features, tracker->body)) {
api_web_contents->Destroy();
}
}
content::WebContents* WebContents::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
auto weak_this = GetWeakPtr();
if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {
Emit("-new-window", params.url, "", params.disposition, "", params.referrer,
params.post_data);
return nullptr;
}
if (!weak_this || !web_contents())
return nullptr;
content::NavigationController::LoadURLParams load_url_params(params.url);
load_url_params.referrer = params.referrer;
load_url_params.transition_type = params.transition;
load_url_params.extra_headers = params.extra_headers;
load_url_params.should_replace_current_entry =
params.should_replace_current_entry;
load_url_params.is_renderer_initiated = params.is_renderer_initiated;
load_url_params.started_from_context_menu = params.started_from_context_menu;
load_url_params.initiator_origin = params.initiator_origin;
load_url_params.source_site_instance = params.source_site_instance;
load_url_params.frame_tree_node_id = params.frame_tree_node_id;
load_url_params.redirect_chain = params.redirect_chain;
load_url_params.has_user_gesture = params.user_gesture;
load_url_params.blob_url_loader_factory = params.blob_url_loader_factory;
load_url_params.href_translate = params.href_translate;
load_url_params.reload_type = params.reload_type;
if (params.post_data) {
load_url_params.load_type =
content::NavigationController::LOAD_TYPE_HTTP_POST;
load_url_params.post_data = params.post_data;
}
source->GetController().LoadURLWithParams(load_url_params);
return source;
}
void WebContents::BeforeUnloadFired(content::WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) {
if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen ||
type_ == Type::kBrowserView)
*proceed_to_fire_unload = proceed;
else
*proceed_to_fire_unload = true;
// Note that Chromium does not emit this for navigations.
Emit("before-unload-fired", proceed);
}
void WebContents::SetContentsBounds(content::WebContents* source,
const gfx::Rect& rect) {
if (!Emit("content-bounds-updated", rect))
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnSetContentBounds(rect);
}
void WebContents::CloseContents(content::WebContents* source) {
Emit("close");
auto* autofill_driver_factory =
AutofillDriverFactory::FromWebContents(web_contents());
if (autofill_driver_factory) {
autofill_driver_factory->CloseAllPopups();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnCloseContents();
// This is handled by the embedder frame.
if (!IsGuest())
Destroy();
}
void WebContents::ActivateContents(content::WebContents* source) {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnActivateContents();
}
void WebContents::UpdateTargetURL(content::WebContents* source,
const GURL& url) {
Emit("update-target-url", url);
}
bool WebContents::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (type_ == Type::kWebView && embedder_) {
// Send the unhandled keyboard events back to the embedder.
return embedder_->HandleKeyboardEvent(source, event);
} else {
return PlatformHandleKeyboardEvent(source, event);
}
}
#if !BUILDFLAG(IS_MAC)
// NOTE: The macOS version of this function is found in
// electron_api_web_contents_mac.mm, as it requires calling into objective-C
// code.
bool WebContents::PlatformHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
// Escape exits tabbed fullscreen mode.
if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) {
ExitFullscreenModeForTab(source);
return true;
}
// Check if the webContents has preferences and to ignore shortcuts
auto* web_preferences = WebContentsPreferences::From(source);
if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts())
return false;
// Let the NativeWindow handle other parts.
if (owner_window()) {
owner_window()->HandleKeyboardEvent(source, event);
return true;
}
return false;
}
#endif
content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (exclusive_access_manager_.HandleUserKeyEvent(event))
return content::KeyboardEventProcessingResult::HANDLED;
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown ||
event.GetType() == blink::WebInputEvent::Type::kKeyUp) {
// For backwards compatibility, pretend that `kRawKeyDown` events are
// actually `kKeyDown`.
content::NativeWebKeyboardEvent tweaked_event(event);
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown)
tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown);
bool prevent_default = Emit("before-input-event", tweaked_event);
if (prevent_default) {
return content::KeyboardEventProcessingResult::HANDLED;
}
}
return content::KeyboardEventProcessingResult::NOT_HANDLED;
}
void WebContents::ContentsZoomChange(bool zoom_in) {
Emit("zoom-changed", zoom_in ? "in" : "out");
}
Profile* WebContents::GetProfile() {
return nullptr;
}
bool WebContents::IsFullscreen() const {
if (!owner_window())
return false;
return owner_window()->IsFullscreen() || is_html_fullscreen();
}
void WebContents::EnterFullscreen(const GURL& url,
ExclusiveAccessBubbleType bubble_type,
const int64_t display_id) {}
void WebContents::ExitFullscreen() {}
void WebContents::UpdateExclusiveAccessExitBubbleContent(
const GURL& url,
ExclusiveAccessBubbleType bubble_type,
ExclusiveAccessBubbleHideCallback bubble_first_hide_callback,
bool notify_download,
bool force_update) {}
void WebContents::OnExclusiveAccessUserInput() {}
content::WebContents* WebContents::GetActiveWebContents() {
return web_contents();
}
bool WebContents::CanUserExitFullscreen() const {
return true;
}
bool WebContents::IsExclusiveAccessBubbleDisplayed() const {
return false;
}
void WebContents::EnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options) {
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(source);
auto callback =
base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab,
base::Unretained(this), requesting_frame, options);
permission_helper->RequestFullscreenPermission(requesting_frame, callback);
}
void WebContents::OnEnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options,
bool allowed) {
if (!allowed || !owner_window())
return;
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
if (IsFullscreenForTabOrPending(source)) {
DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame());
return;
}
owner_window()->set_fullscreen_transition_type(
NativeWindow::FullScreenTransitionType::kHTML);
exclusive_access_manager_.fullscreen_controller()->EnterFullscreenModeForTab(
requesting_frame, options.display_id);
SetHtmlApiFullscreen(true);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
if (!owner_window())
return;
// This needs to be called before we exit fullscreen on the native window,
// or the controller will incorrectly think we weren't fullscreen and bail.
exclusive_access_manager_.fullscreen_controller()->ExitFullscreenModeForTab(
source);
SetHtmlApiFullscreen(false);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too. Chrome does this indirectly from
// `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::RendererUnresponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host,
base::RepeatingClosure hang_monitor_restarter) {
Emit("unresponsive");
}
void WebContents::RendererResponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host) {
Emit("responsive");
}
bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) {
Emit("context-menu", std::make_pair(params, &render_frame_host));
return true;
}
void WebContents::FindReply(content::WebContents* web_contents,
int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update) {
if (!final_update)
return;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto result = gin_helper::Dictionary::CreateEmpty(isolate);
result.Set("requestId", request_id);
result.Set("matches", number_of_matches);
result.Set("selectionArea", selection_rect);
result.Set("activeMatchOrdinal", active_match_ordinal);
result.Set("finalUpdate", final_update); // Deprecate after 2.0
Emit("found-in-page", result.GetHandle());
}
void WebContents::RequestExclusivePointerAccess(
content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target,
bool allowed) {
if (allowed) {
exclusive_access_manager_.mouse_lock_controller()->RequestToLockMouse(
web_contents, user_gesture, last_unlocked_by_target);
} else {
web_contents->GotResponseToLockMouseRequest(
blink::mojom::PointerLockResult::kPermissionDenied);
}
}
void WebContents::RequestToLockMouse(content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestPointerLockPermission(
user_gesture, last_unlocked_by_target,
base::BindOnce(&WebContents::RequestExclusivePointerAccess,
base::Unretained(this)));
}
void WebContents::LostMouseLock() {
exclusive_access_manager_.mouse_lock_controller()->LostMouseLock();
}
void WebContents::RequestKeyboardLock(content::WebContents* web_contents,
bool esc_key_locked) {
exclusive_access_manager_.keyboard_lock_controller()->RequestKeyboardLock(
web_contents, esc_key_locked);
}
void WebContents::CancelKeyboardLockRequest(
content::WebContents* web_contents) {
exclusive_access_manager_.keyboard_lock_controller()
->CancelKeyboardLockRequest(web_contents);
}
bool WebContents::CheckMediaAccessPermission(
content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::mojom::MediaStreamType type) {
auto* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
return permission_helper->CheckMediaAccessPermission(security_origin, type);
}
void WebContents::RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestMediaAccessPermission(request, std::move(callback));
}
content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager(
content::WebContents* source) {
if (!dialog_manager_)
dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>();
return dialog_manager_.get();
}
void WebContents::OnAudioStateChanged(bool audible) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
gin::Dictionary dict(isolate, event_object);
dict.Set("audible", audible);
EmitWithoutEvent("audio-state-changed", event);
}
void WebContents::BeforeUnloadFired(bool proceed) {
// Do nothing, we override this method just to avoid compilation error since
// there are two virtual functions named BeforeUnloadFired.
}
void WebContents::HandleNewRenderFrame(
content::RenderFrameHost* render_frame_host) {
auto* rwhv = render_frame_host->GetView();
if (!rwhv)
return;
// Set the background color of RenderWidgetHostView.
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences) {
auto maybe_color = web_preferences->GetBackgroundColor();
bool guest = IsGuest() || type_ == Type::kBrowserView;
// If webPreferences has no color stored we need to explicitly set guest
// webContents background color to transparent.
auto bg_color =
maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE);
web_contents()->SetPageBaseBackgroundColor(bg_color);
SetBackgroundColor(rwhv, bg_color);
}
if (!background_throttling_)
render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false);
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (rwh_impl)
rwh_impl->disable_hidden_ = !background_throttling_;
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->MaybeSetupMojoConnection();
}
void WebContents::OnBackgroundColorChanged() {
absl::optional<SkColor> color = web_contents()->GetBackgroundColor();
if (color.has_value()) {
auto* const view = web_contents()->GetRenderWidgetHostView();
static_cast<content::RenderWidgetHostViewBase*>(view)
->SetContentBackgroundColor(color.value());
}
}
void WebContents::RenderFrameCreated(
content::RenderFrameHost* render_frame_host) {
HandleNewRenderFrame(render_frame_host);
// RenderFrameCreated is called for speculative frames which may not be
// used in certain cross-origin navigations. Invoking
// RenderFrameHost::GetLifecycleState currently crashes when called for
// speculative frames so we need to filter it out for now. Check
// https://crbug.com/1183639 for details on when this can be removed.
auto* rfh_impl =
static_cast<content::RenderFrameHostImpl*>(render_frame_host);
if (rfh_impl->lifecycle_state() ==
content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) {
return;
}
content::RenderFrameHost::LifecycleState lifecycle_state =
render_frame_host->GetLifecycleState();
if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.SetGetter("frame", render_frame_host);
Emit("frame-created", details);
}
}
void WebContents::RenderFrameDeleted(
content::RenderFrameHost* render_frame_host) {
// A RenderFrameHost can be deleted when:
// - A WebContents is removed and its containing frames are disposed.
// - An <iframe> is removed from the DOM.
// - Cross-origin navigation creates a new RFH in a separate process which
// is swapped by content::RenderFrameHostManager.
//
// WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID
// to find an existing instance of WebFrameMain. During a cross-origin
// navigation, the deleted RFH will be the old host which was swapped out. In
// this special case, we need to also ensure that WebFrameMain's internal RFH
// matches before marking it as disposed.
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame && web_frame->render_frame_host() == render_frame_host)
web_frame->MarkRenderFrameDisposed();
}
void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) {
if (new_host->IsInPrimaryMainFrame()) {
if (old_host)
old_host->GetRenderWidgetHost()->RemoveInputEventObserver(this);
if (new_host)
new_host->GetRenderWidgetHost()->AddInputEventObserver(this);
}
// During cross-origin navigation, a FrameTreeNode will swap out its RFH.
// If an instance of WebFrameMain exists, it will need to have its RFH
// swapped as well.
//
// |old_host| can be a nullptr so we use |new_host| for looking up the
// WebFrameMain instance.
auto* web_frame = WebFrameMain::FromRenderFrameHost(new_host);
if (web_frame) {
web_frame->UpdateRenderFrameHost(new_host);
}
}
void WebContents::FrameDeleted(int frame_tree_node_id) {
auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id);
if (web_frame)
web_frame->Destroyed();
}
void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
// This event is necessary for tracking any states with respect to
// intermediate render view hosts aka speculative render view hosts. Currently
// used by object-registry.js to ref count remote objects.
Emit("render-view-deleted", render_view_host->GetProcess()->GetID());
if (web_contents()->GetRenderViewHost() == render_view_host) {
// When the RVH that has been deleted is the current RVH it means that the
// the web contents are being closed. This is communicated by this event.
// Currently tracked by guest-window-manager.ts to destroy the
// BrowserWindow.
Emit("current-render-view-deleted",
render_view_host->GetProcess()->GetID());
}
}
void WebContents::PrimaryMainFrameRenderProcessGone(
base::TerminationStatus status) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("reason", status);
details.Set("exitCode", web_contents()->GetCrashedErrorCode());
Emit("render-process-gone", details);
}
void WebContents::PluginCrashed(const base::FilePath& plugin_path,
base::ProcessId plugin_pid) {
#if BUILDFLAG(ENABLE_PLUGINS)
content::WebPluginInfo info;
auto* plugin_service = content::PluginService::GetInstance();
plugin_service->GetPluginInfoByPath(plugin_path, &info);
Emit("plugin-crashed", info.name, info.version);
#endif // BUILDFLAG(ENABLE_PLUGINS)
}
void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id) {
Emit("media-started-playing");
}
void WebContents::MediaStoppedPlaying(
const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id,
content::WebContentsObserver::MediaStoppedReason reason) {
Emit("media-paused");
}
void WebContents::DidChangeThemeColor() {
auto theme_color = web_contents()->GetThemeColor();
if (theme_color) {
Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value()));
} else {
Emit("did-change-theme-color", nullptr);
}
}
void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) {
set_fullscreen_frame(rfh);
}
void WebContents::OnWebContentsFocused(
content::RenderWidgetHost* render_widget_host) {
Emit("focus");
}
void WebContents::OnWebContentsLostFocus(
content::RenderWidgetHost* render_widget_host) {
Emit("blur");
}
void WebContents::DOMContentLoaded(
content::RenderFrameHost* render_frame_host) {
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->DOMContentLoaded();
if (!render_frame_host->GetParent())
Emit("dom-ready");
}
void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url) {
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
auto weak_this = GetWeakPtr();
Emit("did-frame-finish-load", is_main_frame, frame_process_id,
frame_routing_id);
// β οΈWARNING!β οΈ
// Emit() triggers JS which can call destroy() on |this|. It's not safe to
// assume that |this| points to valid memory at this point.
if (is_main_frame && weak_this && web_contents())
Emit("did-finish-load");
}
void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
const GURL& url,
int error_code) {
// See DocumentLoader::StartLoadingResponse() - when we navigate to a media
// resource the original request for the media resource, which resulted in a
// committed navigation, is simply discarded. The media element created
// inside the MediaDocument then makes *another new* request for the same
// media resource.
bool is_media_document =
media::IsSupportedMediaMimeType(web_contents()->GetContentsMimeType());
if (error_code == net::ERR_ABORTED && is_media_document)
return;
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id,
frame_routing_id);
}
void WebContents::DidStartLoading() {
Emit("did-start-loading");
}
void WebContents::DidStopLoading() {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences && web_preferences->ShouldUsePreferredSizeMode())
web_contents()->GetRenderViewHost()->EnablePreferredSizeMode();
Emit("did-stop-loading");
}
bool WebContents::EmitNavigationEvent(
const std::string& event_name,
content::NavigationHandle* navigation_handle) {
bool is_main_frame = navigation_handle->IsInMainFrame();
int frame_process_id = -1, frame_routing_id = -1;
content::RenderFrameHost* frame_host = GetRenderFrameHost(navigation_handle);
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
bool is_same_document = navigation_handle->IsSameDocument();
auto url = navigation_handle->GetURL();
content::RenderFrameHost* initiator_frame_host =
navigation_handle->GetInitiatorFrameToken().has_value()
? content::RenderFrameHost::FromFrameToken(
navigation_handle->GetInitiatorProcessId(),
navigation_handle->GetInitiatorFrameToken().value())
: nullptr;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
gin_helper::Dictionary dict(isolate, event_object);
dict.Set("url", url);
dict.Set("isSameDocument", is_same_document);
dict.Set("isMainFrame", is_main_frame);
dict.Set("frame", frame_host);
dict.SetGetter("initiator", initiator_frame_host);
EmitWithoutEvent(event_name, event, url, is_same_document, is_main_frame,
frame_process_id, frame_routing_id);
return event->GetDefaultPrevented();
}
void WebContents::Message(bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Message", "channel", channel);
// webContents.emit('-ipc-message', new Event(), internal, channel,
// arguments);
EmitWithSender("-ipc-message", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), internal,
channel, std::move(arguments));
}
void WebContents::Invoke(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::InvokeCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel);
// webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments);
EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::OnFirstNonEmptyLayout(
content::RenderFrameHost* render_frame_host) {
if (render_frame_host == web_contents()->GetPrimaryMainFrame()) {
Emit("ready-to-show");
}
}
// This object wraps the InvokeCallback so that if it gets GC'd by V8, we can
// still call the callback and send an error. Not doing so causes a Mojo DCHECK,
// since Mojo requires callbacks to be called before they are destroyed.
class ReplyChannel : public gin::Wrappable<ReplyChannel> {
public:
using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback;
static gin::Handle<ReplyChannel> Create(v8::Isolate* isolate,
InvokeCallback callback) {
return gin::CreateHandle(isolate, new ReplyChannel(std::move(callback)));
}
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override {
return gin::Wrappable<ReplyChannel>::GetObjectTemplateBuilder(isolate)
.SetMethod("sendReply", &ReplyChannel::SendReply);
}
const char* GetTypeName() override { return "ReplyChannel"; }
void SendError(const std::string& msg) {
v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
// If there's no current context, it means we're shutting down, so we
// don't need to send an event.
if (!isolate->GetCurrentContext().IsEmpty()) {
v8::HandleScope scope(isolate);
auto message = gin::DataObjectBuilder(isolate).Set("error", msg).Build();
SendReply(isolate, message);
}
}
private:
explicit ReplyChannel(InvokeCallback callback)
: callback_(std::move(callback)) {}
~ReplyChannel() override {
if (callback_)
SendError("reply was never sent");
}
bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> arg) {
if (!callback_)
return false;
blink::CloneableMessage message;
if (!gin::ConvertFromV8(isolate, arg, &message)) {
return false;
}
std::move(callback_).Run(std::move(message));
return true;
}
InvokeCallback callback_;
};
gin::WrapperInfo ReplyChannel::kWrapperInfo = {gin::kEmbedderNativeGin};
gin::Handle<gin_helper::internal::Event> WebContents::MakeEventWithSender(
v8::Isolate* isolate,
content::RenderFrameHost* frame,
electron::mojom::ElectronApiIPC::InvokeCallback callback) {
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper)) {
if (callback) {
// We must always invoke the callback if present.
ReplyChannel::Create(isolate, std::move(callback))
->SendError("WebContents was destroyed");
}
return gin::Handle<gin_helper::internal::Event>();
}
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
gin_helper::Dictionary dict(isolate, event.ToV8().As<v8::Object>());
if (callback)
dict.Set("_replyChannel",
ReplyChannel::Create(isolate, std::move(callback)));
if (frame) {
dict.Set("frameId", frame->GetRoutingID());
dict.Set("processId", frame->GetProcess()->GetID());
}
return event;
}
void WebContents::ReceivePostMessage(
const std::string& channel,
blink::TransferableMessage message,
content::RenderFrameHost* render_frame_host) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto wrapped_ports =
MessagePort::EntanglePorts(isolate, std::move(message.ports));
v8::Local<v8::Value> message_value =
electron::DeserializeV8Value(isolate, message);
EmitWithSender("-ipc-ports", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), false,
channel, message_value, std::move(wrapped_ports));
}
void WebContents::MessageSync(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::MessageSyncCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel);
// webContents.emit('-ipc-message-sync', new Event(sender, message), internal,
// channel, arguments);
EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::MessageHost(const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel);
// webContents.emit('ipc-message-host', new Event(), channel, args);
EmitWithSender("ipc-message-host", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), channel,
std::move(arguments));
}
void WebContents::UpdateDraggableRegions(
std::vector<mojom::DraggableRegionPtr> regions) {
if (owner_window() && owner_window()->has_frame())
return;
draggable_region_ = DraggableRegionsToSkRegion(regions);
}
void WebContents::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-start-navigation", navigation_handle);
}
void WebContents::DidRedirectNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-redirect-navigation", navigation_handle);
}
void WebContents::ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) {
// Don't focus content in an inactive window.
if (!owner_window())
return;
#if BUILDFLAG(IS_MAC)
if (!owner_window()->IsActive())
return;
#else
if (!owner_window()->widget()->IsActive())
return;
#endif
// Don't focus content after subframe navigations.
if (!navigation_handle->IsInMainFrame())
return;
// Only focus for top-level contents.
if (type_ != Type::kBrowserWindow)
return;
web_contents()->SetInitialFocus();
}
void WebContents::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (owner_window_) {
owner_window_->NotifyLayoutWindowControlsOverlay();
}
if (!navigation_handle->HasCommitted())
return;
bool is_main_frame = navigation_handle->IsInMainFrame();
content::RenderFrameHost* frame_host =
navigation_handle->GetRenderFrameHost();
int frame_process_id = -1, frame_routing_id = -1;
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
if (!navigation_handle->IsErrorPage()) {
// FIXME: All the Emit() calls below could potentially result in |this|
// being destroyed (by JS listening for the event and calling
// webContents.destroy()).
auto url = navigation_handle->GetURL();
bool is_same_document = navigation_handle->IsSameDocument();
if (is_same_document) {
Emit("did-navigate-in-page", url, is_main_frame, frame_process_id,
frame_routing_id);
} else {
const net::HttpResponseHeaders* http_response =
navigation_handle->GetResponseHeaders();
std::string http_status_text;
int http_response_code = -1;
if (http_response) {
http_status_text = http_response->GetStatusText();
http_response_code = http_response->response_code();
}
Emit("did-frame-navigate", url, http_response_code, http_status_text,
is_main_frame, frame_process_id, frame_routing_id);
if (is_main_frame) {
Emit("did-navigate", url, http_response_code, http_status_text);
}
}
if (IsGuest())
Emit("load-commit", url, is_main_frame);
} else {
auto url = navigation_handle->GetURL();
int code = navigation_handle->GetNetErrorCode();
auto description = net::ErrorToShortString(code);
Emit("did-fail-provisional-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
// Do not emit "did-fail-load" for canceled requests.
if (code != net::ERR_ABORTED) {
EmitWarning(
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()),
"Failed to load URL: " + url.possibly_invalid_spec() +
" with error: " + description,
"electron");
Emit("did-fail-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
}
}
content::NavigationEntry* entry = navigation_handle->GetNavigationEntry();
// This check is needed due to an issue in Chromium
// Check the Chromium issue to keep updated:
// https://bugs.chromium.org/p/chromium/issues/detail?id=1178663
// If a history entry has been made and the forward/back call has been made,
// proceed with setting the new title
if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK))
WebContents::TitleWasSet(entry);
}
void WebContents::TitleWasSet(content::NavigationEntry* entry) {
std::u16string final_title;
bool explicit_set = true;
if (entry) {
auto title = entry->GetTitle();
auto url = entry->GetURL();
if (url.SchemeIsFile() && title.empty()) {
final_title = base::UTF8ToUTF16(url.ExtractFileName());
explicit_set = false;
} else {
final_title = title;
}
} else {
final_title = web_contents()->GetTitle();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnPageTitleUpdated(final_title, explicit_set);
Emit("page-title-updated", final_title, explicit_set);
}
void WebContents::DidUpdateFaviconURL(
content::RenderFrameHost* render_frame_host,
const std::vector<blink::mojom::FaviconURLPtr>& urls) {
std::set<GURL> unique_urls;
for (const auto& iter : urls) {
if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon)
continue;
const GURL& url = iter->icon_url;
if (url.is_valid())
unique_urls.insert(url);
}
Emit("page-favicon-updated", unique_urls);
}
void WebContents::DevToolsReloadPage() {
Emit("devtools-reload-page");
}
void WebContents::DevToolsFocused() {
Emit("devtools-focused");
}
void WebContents::DevToolsOpened() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
DCHECK(inspectable_web_contents_);
DCHECK(inspectable_web_contents_->GetDevToolsWebContents());
auto handle = FromOrCreate(
isolate, inspectable_web_contents_->GetDevToolsWebContents());
devtools_web_contents_.Reset(isolate, handle.ToV8());
// Set inspected tabID.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "setInspectedTabId", base::Value(ID()));
// Inherit owner window in devtools when it doesn't have one.
auto* devtools = inspectable_web_contents_->GetDevToolsWebContents();
bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey());
if (owner_window() && !has_window)
handle->SetOwnerWindow(devtools, owner_window());
Emit("devtools-opened");
}
void WebContents::DevToolsClosed() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
devtools_web_contents_.Reset();
Emit("devtools-closed");
}
void WebContents::DevToolsResized() {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnDevToolsResized();
}
void WebContents::SetOwnerWindow(NativeWindow* owner_window) {
SetOwnerWindow(GetWebContents(), owner_window);
}
void WebContents::SetOwnerWindow(content::WebContents* web_contents,
NativeWindow* owner_window) {
if (owner_window_) {
owner_window_->RemoveBackgroundThrottlingSource(this);
}
if (owner_window) {
owner_window_ = owner_window->GetWeakPtr();
NativeWindowRelay::CreateForWebContents(web_contents,
owner_window->GetWeakPtr());
owner_window_->AddBackgroundThrottlingSource(this);
} else {
owner_window_ = nullptr;
web_contents->RemoveUserData(NativeWindowRelay::UserDataKey());
}
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetNativeWindow(owner_window);
}
content::WebContents* WebContents::GetWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetWebContents();
}
content::WebContents* WebContents::GetDevToolsWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetDevToolsWebContents();
}
void WebContents::WebContentsDestroyed() {
// Clear the pointer stored in wrapper.
if (GetAllWebContents().Lookup(id_))
GetAllWebContents().Remove(id_);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
wrapper->SetAlignedPointerInInternalField(0, nullptr);
// Tell WebViewGuestDelegate that the WebContents has been destroyed.
if (guest_delegate_)
guest_delegate_->WillDestroy();
Observe(nullptr);
Emit("destroyed");
}
void WebContents::NavigationEntryCommitted(
const content::LoadCommittedDetails& details) {
Emit("navigation-entry-committed", details.entry->GetURL(),
details.is_same_document, details.did_replace_entry);
}
bool WebContents::GetBackgroundThrottling() const {
return background_throttling_;
}
void WebContents::SetBackgroundThrottling(bool allowed) {
background_throttling_ = allowed;
if (owner_window_) {
owner_window_->UpdateBackgroundThrottlingState();
}
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (!rfh)
return;
auto* rwhv = rfh->GetView();
if (!rwhv)
return;
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (!rwh_impl)
return;
rwh_impl->disable_hidden_ = !background_throttling_;
web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed);
if (rwh_impl->is_hidden()) {
rwh_impl->WasShown({});
}
}
int WebContents::GetProcessID() const {
return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
}
base::ProcessId WebContents::GetOSProcessID() const {
base::ProcessHandle process_handle = web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->GetProcess()
.Handle();
return base::GetProcId(process_handle);
}
WebContents::Type WebContents::GetType() const {
return type_;
}
bool WebContents::Equal(const WebContents* web_contents) const {
return ID() == web_contents->ID();
}
GURL WebContents::GetURL() const {
return web_contents()->GetLastCommittedURL();
}
void WebContents::LoadURL(const GURL& url,
const gin_helper::Dictionary& options) {
if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL),
net::ErrorToShortString(net::ERR_INVALID_URL),
url.possibly_invalid_spec(), true);
return;
}
content::NavigationController::LoadURLParams params(url);
if (!options.Get("httpReferrer", ¶ms.referrer)) {
GURL http_referrer;
if (options.Get("httpReferrer", &http_referrer))
params.referrer =
content::Referrer(http_referrer.GetAsReferrer(),
network::mojom::ReferrerPolicy::kDefault);
}
std::string user_agent;
if (options.Get("userAgent", &user_agent))
SetUserAgent(user_agent);
std::string extra_headers;
if (options.Get("extraHeaders", &extra_headers))
params.extra_headers = extra_headers;
scoped_refptr<network::ResourceRequestBody> body;
if (options.Get("postData", &body)) {
params.post_data = body;
params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
}
GURL base_url_for_data_url;
if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
params.base_url_for_data_url = base_url_for_data_url;
params.load_type = content::NavigationController::LOAD_TYPE_DATA;
}
bool reload_ignoring_cache = false;
if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) &&
reload_ignoring_cache) {
params.reload_type = content::ReloadType::BYPASSING_CACHE;
}
// Calling LoadURLWithParams() can trigger JS which destroys |this|.
auto weak_this = GetWeakPtr();
params.transition_type = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
// Discard non-committed entries to ensure that we don't re-use a pending
// entry
web_contents()->GetController().DiscardNonCommittedEntries();
web_contents()->GetController().LoadURLWithParams(params);
// β οΈWARNING!β οΈ
// LoadURLWithParams() triggers JS events which can call destroy() on |this|.
// It's not safe to assume that |this| points to valid memory at this point.
if (!weak_this || !web_contents())
return;
// Required to make beforeunload handler work.
NotifyUserActivation();
}
// TODO(MarshallOfSound): Figure out what we need to do with post data here, I
// believe the default behavior when we pass "true" is to phone out to the
// delegate and then the controller expects this method to be called again with
// "false" if the user approves the reload. For now this would result in
// ".reload()" calls on POST data domains failing silently. Passing false would
// result in them succeeding, but reposting which although more correct could be
// considering a breaking change.
void WebContents::Reload() {
web_contents()->GetController().Reload(content::ReloadType::NORMAL,
/* check_for_repost */ true);
}
void WebContents::ReloadIgnoringCache() {
web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE,
/* check_for_repost */ true);
}
void WebContents::DownloadURL(const GURL& url, gin::Arguments* args) {
std::map<std::string, std::string> headers;
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
if (options.Has("headers") && !options.Get("headers", &headers)) {
args->ThrowTypeError("Invalid value for headers - must be an object");
return;
}
}
std::unique_ptr<download::DownloadUrlParameters> download_params(
content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
web_contents(), url, MISSING_TRAFFIC_ANNOTATION));
for (const auto& [name, value] : headers) {
download_params->add_request_header(name, value);
}
auto* download_manager =
web_contents()->GetBrowserContext()->GetDownloadManager();
download_manager->DownloadUrl(std::move(download_params));
}
std::u16string WebContents::GetTitle() const {
return web_contents()->GetTitle();
}
bool WebContents::IsLoading() const {
return web_contents()->IsLoading();
}
bool WebContents::IsLoadingMainFrame() const {
return web_contents()->ShouldShowLoadingUI();
}
bool WebContents::IsWaitingForResponse() const {
return web_contents()->IsWaitingForResponse();
}
void WebContents::Stop() {
web_contents()->Stop();
}
bool WebContents::CanGoBack() const {
return web_contents()->GetController().CanGoBack();
}
void WebContents::GoBack() {
if (CanGoBack())
web_contents()->GetController().GoBack();
}
bool WebContents::CanGoForward() const {
return web_contents()->GetController().CanGoForward();
}
void WebContents::GoForward() {
if (CanGoForward())
web_contents()->GetController().GoForward();
}
bool WebContents::CanGoToOffset(int offset) const {
return web_contents()->GetController().CanGoToOffset(offset);
}
void WebContents::GoToOffset(int offset) {
if (CanGoToOffset(offset))
web_contents()->GetController().GoToOffset(offset);
}
bool WebContents::CanGoToIndex(int index) const {
return index >= 0 && index < GetHistoryLength();
}
void WebContents::GoToIndex(int index) {
if (CanGoToIndex(index))
web_contents()->GetController().GoToIndex(index);
}
int WebContents::GetActiveIndex() const {
return web_contents()->GetController().GetCurrentEntryIndex();
}
void WebContents::ClearHistory() {
// In some rare cases (normally while there is no real history) we are in a
// state where we can't prune navigation entries
if (web_contents()->GetController().CanPruneAllButLastCommitted()) {
web_contents()->GetController().PruneAllButLastCommitted();
}
}
int WebContents::GetHistoryLength() const {
return web_contents()->GetController().GetEntryCount();
}
const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy;
}
void WebContents::SetWebRTCIPHandlingPolicy(
const std::string& webrtc_ip_handling_policy) {
if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
return;
web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
webrtc_ip_handling_policy;
web_contents()->SyncRendererPrefs();
}
v8::Local<v8::Value> WebContents::GetWebRTCUDPPortRange(
v8::Isolate* isolate) const {
auto* prefs = web_contents()->GetMutableRendererPrefs();
auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
dict.Set("min", static_cast<uint32_t>(prefs->webrtc_udp_min_port));
dict.Set("max", static_cast<uint32_t>(prefs->webrtc_udp_max_port));
return dict.GetHandle();
}
void WebContents::SetWebRTCUDPPortRange(gin::Arguments* args) {
uint32_t min = 0, max = 0;
gin_helper::Dictionary range;
if (!args->GetNext(&range) || !range.Get("min", &min) ||
!range.Get("max", &max)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'min' and 'max' are both required");
return;
}
if ((0 == min && 0 != max) || max > UINT16_MAX) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError(
"'min' and 'max' must be in the (0, 65535] range or [0, 0]");
return;
}
if (min > max) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'max' must be greater than or equal to 'min'");
return;
}
auto* prefs = web_contents()->GetMutableRendererPrefs();
if (prefs->webrtc_udp_min_port == static_cast<uint16_t>(min) &&
prefs->webrtc_udp_max_port == static_cast<uint16_t>(max)) {
return;
}
prefs->webrtc_udp_min_port = min;
prefs->webrtc_udp_max_port = max;
web_contents()->SyncRendererPrefs();
}
std::string WebContents::GetMediaSourceID(
content::WebContents* request_web_contents) {
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host)
return std::string();
content::DesktopMediaID media_id(
content::DesktopMediaID::TYPE_WEB_CONTENTS,
content::DesktopMediaID::kNullId,
content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(),
frame_host->GetRoutingID()));
auto* request_frame_host = request_web_contents->GetPrimaryMainFrame();
if (!request_frame_host)
return std::string();
std::string id =
content::DesktopStreamsRegistry::GetInstance()->RegisterStream(
request_frame_host->GetProcess()->GetID(),
request_frame_host->GetRoutingID(),
url::Origin::Create(request_frame_host->GetLastCommittedURL()
.DeprecatedGetOriginAsURL()),
media_id, content::kRegistryStreamTypeTab);
return id;
}
bool WebContents::IsCrashed() const {
return web_contents()->IsCrashed();
}
void WebContents::ForcefullyCrashRenderer() {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
if (!rwh)
return;
content::RenderProcessHost* rph = rwh->GetProcess();
if (rph) {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// A generic |CrashDumpHungChildProcess()| is not implemented for Linux.
// Instead we send an explicit IPC to crash on the renderer's IO thread.
rph->ForceCrash();
#else
// Try to generate a crash report for the hung process.
#if !IS_MAS_BUILD()
CrashDumpHungChildProcess(rph->GetProcess().Handle());
#endif
rph->Shutdown(content::RESULT_CODE_HUNG);
#endif
}
}
void WebContents::SetUserAgent(const std::string& user_agent) {
blink::UserAgentOverride ua_override;
ua_override.ua_string_override = user_agent;
if (!user_agent.empty())
ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata();
web_contents()->SetUserAgentOverride(ua_override, false);
}
std::string WebContents::GetUserAgent() {
return web_contents()->GetUserAgentOverride().ua_string_override;
}
v8::Local<v8::Promise> WebContents::SavePage(
const base::FilePath& full_file_path,
const content::SavePageType& save_type) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!full_file_path.IsAbsolute()) {
promise.RejectWithErrorMessage("Path must be absolute");
return handle;
}
auto* handler = new SavePageHandler(web_contents(), std::move(promise));
handler->Handle(full_file_path, save_type);
return handle;
}
void WebContents::OpenDevTools(gin::Arguments* args) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
std::string state;
if (type_ == Type::kWebView || type_ == Type::kBackgroundPage ||
!owner_window()) {
state = "detach";
}
bool activate = true;
std::string title;
if (args && args->Length() == 1) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("mode", &state);
options.Get("activate", &activate);
options.Get("title", &title);
}
}
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->SetDockState(state);
inspectable_web_contents_->SetDevToolsTitle(base::UTF8ToUTF16(title));
inspectable_web_contents_->ShowDevTools(activate);
}
void WebContents::CloseDevTools() {
if (type_ == Type::kRemote)
return;
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->CloseDevTools();
}
bool WebContents::IsDevToolsOpened() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->IsDevToolsViewShowing();
}
std::u16string WebContents::GetDevToolsTitle() {
if (type_ == Type::kRemote)
return std::u16string();
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->GetDevToolsTitle();
}
void WebContents::SetDevToolsTitle(const std::u16string& title) {
inspectable_web_contents_->SetDevToolsTitle(title);
}
bool WebContents::IsDevToolsFocused() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->GetView()->IsDevToolsViewFocused();
}
void WebContents::EnableDeviceEmulation(
const blink::DeviceEmulationParams& params) {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->EnableDeviceEmulation(params);
}
}
}
void WebContents::DisableDeviceEmulation() {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->DisableDeviceEmulation();
}
}
}
void WebContents::ToggleDevTools() {
if (IsDevToolsOpened())
CloseDevTools();
else
OpenDevTools(nullptr);
}
void WebContents::InspectElement(int x, int y) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
DCHECK(inspectable_web_contents_);
if (!inspectable_web_contents_->GetDevToolsWebContents())
OpenDevTools(nullptr);
inspectable_web_contents_->InspectElement(x, y);
}
void WebContents::InspectSharedWorkerById(const std::string& workerId) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
if (agent_host->GetId() == workerId) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
}
std::vector<scoped_refptr<content::DevToolsAgentHost>>
WebContents::GetAllSharedWorkers() {
std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers;
if (type_ == Type::kRemote)
return shared_workers;
if (!enable_devtools_)
return shared_workers;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
shared_workers.push_back(agent_host);
}
}
return shared_workers;
}
void WebContents::InspectSharedWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::InspectServiceWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeServiceWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::SetIgnoreMenuShortcuts(bool ignore) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
DCHECK(web_preferences);
web_preferences->SetIgnoreMenuShortcuts(ignore);
}
void WebContents::SetAudioMuted(bool muted) {
web_contents()->SetAudioMuted(muted);
}
bool WebContents::IsAudioMuted() {
return web_contents()->IsAudioMuted();
}
bool WebContents::IsCurrentlyAudible() {
return web_contents()->IsCurrentlyAudible();
}
#if BUILDFLAG(ENABLE_PRINTING)
void WebContents::OnGetDeviceNameToUse(
base::Value::Dict print_settings,
printing::CompletionCallback print_callback,
bool silent,
// <error, device_name>
std::pair<std::string, std::u16string> info) {
// The content::WebContents might be already deleted at this point, and the
// PrintViewManagerElectron class does not do null check.
if (!web_contents()) {
if (print_callback)
std::move(print_callback).Run(false, "failed");
return;
}
if (!info.first.empty()) {
if (print_callback)
std::move(print_callback).Run(false, info.first);
return;
}
// If the user has passed a deviceName use it, otherwise use default printer.
print_settings.Set(printing::kSettingDeviceName, info.second);
auto* print_view_manager =
PrintViewManagerElectron::FromWebContents(web_contents());
if (!print_view_manager)
return;
auto* focused_frame = web_contents()->GetFocusedFrame();
auto* rfh = focused_frame && focused_frame->HasSelection()
? focused_frame
: web_contents()->GetPrimaryMainFrame();
print_view_manager->PrintNow(rfh, silent, std::move(print_settings),
std::move(print_callback));
}
void WebContents::Print(gin::Arguments* args) {
auto options = gin_helper::Dictionary::CreateEmpty(args->isolate());
base::Value::Dict settings;
if (args->Length() >= 1 && !args->GetNext(&options)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid print settings specified.");
return;
}
printing::CompletionCallback callback;
if (args->Length() == 2 && !args->GetNext(&callback)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid optional callback provided.");
return;
}
// Set optional silent printing
bool silent = false;
options.Get("silent", &silent);
bool print_background = false;
options.Get("printBackground", &print_background);
settings.Set(printing::kSettingShouldPrintBackgrounds, print_background);
// Set custom margin settings
auto margins = gin_helper::Dictionary::CreateEmpty(args->isolate());
if (options.Get("margins", &margins)) {
printing::mojom::MarginType margin_type =
printing::mojom::MarginType::kDefaultMargins;
margins.Get("marginType", &margin_type);
settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type));
if (margin_type == printing::mojom::MarginType::kCustomMargins) {
base::Value::Dict custom_margins;
int top = 0;
margins.Get("top", &top);
custom_margins.Set(printing::kSettingMarginTop, top);
int bottom = 0;
margins.Get("bottom", &bottom);
custom_margins.Set(printing::kSettingMarginBottom, bottom);
int left = 0;
margins.Get("left", &left);
custom_margins.Set(printing::kSettingMarginLeft, left);
int right = 0;
margins.Get("right", &right);
custom_margins.Set(printing::kSettingMarginRight, right);
settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins));
}
} else {
settings.Set(
printing::kSettingMarginsType,
static_cast<int>(printing::mojom::MarginType::kDefaultMargins));
}
// Set whether to print color or greyscale
bool print_color = true;
options.Get("color", &print_color);
auto const color_model = print_color ? printing::mojom::ColorModel::kColor
: printing::mojom::ColorModel::kGray;
settings.Set(printing::kSettingColor, static_cast<int>(color_model));
// Is the orientation landscape or portrait.
bool landscape = false;
options.Get("landscape", &landscape);
settings.Set(printing::kSettingLandscape, landscape);
// We set the default to the system's default printer and only update
// if at the Chromium level if the user overrides.
// Printer device name as opened by the OS.
std::u16string device_name;
options.Get("deviceName", &device_name);
int scale_factor = 100;
options.Get("scaleFactor", &scale_factor);
settings.Set(printing::kSettingScaleFactor, scale_factor);
int pages_per_sheet = 1;
options.Get("pagesPerSheet", &pages_per_sheet);
settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet);
// True if the user wants to print with collate.
bool collate = true;
options.Get("collate", &collate);
settings.Set(printing::kSettingCollate, collate);
// The number of individual copies to print
int copies = 1;
options.Get("copies", &copies);
settings.Set(printing::kSettingCopies, copies);
// Strings to be printed as headers and footers if requested by the user.
std::string header;
options.Get("header", &header);
std::string footer;
options.Get("footer", &footer);
if (!(header.empty() && footer.empty())) {
settings.Set(printing::kSettingHeaderFooterEnabled, true);
settings.Set(printing::kSettingHeaderFooterTitle, header);
settings.Set(printing::kSettingHeaderFooterURL, footer);
} else {
settings.Set(printing::kSettingHeaderFooterEnabled, false);
}
// We don't want to allow the user to enable these settings
// but we need to set them or a CHECK is hit.
settings.Set(printing::kSettingPrinterType,
static_cast<int>(printing::mojom::PrinterType::kLocal));
settings.Set(printing::kSettingShouldPrintSelectionOnly, false);
settings.Set(printing::kSettingRasterizePdf, false);
// Set custom page ranges to print
std::vector<gin_helper::Dictionary> page_ranges;
if (options.Get("pageRanges", &page_ranges)) {
base::Value::List page_range_list;
for (auto& range : page_ranges) {
int from, to;
if (range.Get("from", &from) && range.Get("to", &to)) {
base::Value::Dict range_dict;
// Chromium uses 1-based page ranges, so increment each by 1.
range_dict.Set(printing::kSettingPageRangeFrom, from + 1);
range_dict.Set(printing::kSettingPageRangeTo, to + 1);
page_range_list.Append(std::move(range_dict));
} else {
continue;
}
}
if (!page_range_list.empty())
settings.Set(printing::kSettingPageRange, std::move(page_range_list));
}
// Duplex type user wants to use.
printing::mojom::DuplexMode duplex_mode =
printing::mojom::DuplexMode::kSimplex;
options.Get("duplexMode", &duplex_mode);
settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode));
// We've already done necessary parameter sanitization at the
// JS level, so we can simply pass this through.
base::Value media_size(base::Value::Type::DICT);
if (options.Get("mediaSize", &media_size))
settings.Set(printing::kSettingMediaSize, std::move(media_size));
// Set custom dots per inch (dpi)
gin_helper::Dictionary dpi_settings;
int dpi = 72;
if (options.Get("dpi", &dpi_settings)) {
int horizontal = 72;
dpi_settings.Get("horizontal", &horizontal);
settings.Set(printing::kSettingDpiHorizontal, horizontal);
int vertical = 72;
dpi_settings.Get("vertical", &vertical);
settings.Set(printing::kSettingDpiVertical, vertical);
} else {
settings.Set(printing::kSettingDpiHorizontal, dpi);
settings.Set(printing::kSettingDpiVertical, dpi);
}
print_task_runner_->PostTaskAndReplyWithResult(
FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name),
base::BindOnce(&WebContents::OnGetDeviceNameToUse,
weak_factory_.GetWeakPtr(), std::move(settings),
std::move(callback), silent));
}
// Partially duplicated and modified from
// headless/lib/browser/protocol/page_handler.cc;l=41
v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
// This allows us to track headless printing calls.
auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID);
auto landscape = settings.GetDict().FindBool("landscape");
auto display_header_footer =
settings.GetDict().FindBool("displayHeaderFooter");
auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds");
auto scale = settings.GetDict().FindDouble("scale");
auto paper_width = settings.GetDict().FindDouble("paperWidth");
auto paper_height = settings.GetDict().FindDouble("paperHeight");
auto margin_top = settings.GetDict().FindDouble("marginTop");
auto margin_bottom = settings.GetDict().FindDouble("marginBottom");
auto margin_left = settings.GetDict().FindDouble("marginLeft");
auto margin_right = settings.GetDict().FindDouble("marginRight");
auto page_ranges = *settings.GetDict().FindString("pageRanges");
auto header_template = *settings.GetDict().FindString("headerTemplate");
auto footer_template = *settings.GetDict().FindString("footerTemplate");
auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize");
auto generate_tagged_pdf =
settings.GetDict().FindBool("shouldGenerateTaggedPDF");
absl::variant<printing::mojom::PrintPagesParamsPtr, std::string>
print_pages_params = print_to_pdf::GetPrintPagesParams(
web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(),
landscape, display_header_footer, print_background, scale,
paper_width, paper_height, margin_top, margin_bottom, margin_left,
margin_right, absl::make_optional(header_template),
absl::make_optional(footer_template), prefer_css_page_size,
generate_tagged_pdf);
if (absl::holds_alternative<std::string>(print_pages_params)) {
auto error = absl::get<std::string>(print_pages_params);
promise.RejectWithErrorMessage("Invalid print parameters: " + error);
return handle;
}
auto* manager = PrintViewManagerElectron::FromWebContents(web_contents());
if (!manager) {
promise.RejectWithErrorMessage("Failed to find print manager");
return handle;
}
auto params = std::move(
absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params));
params->params->document_cookie = unique_id.value_or(0);
manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges,
std::move(params),
base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(),
std::move(promise)));
return handle;
}
void WebContents::OnPDFCreated(
gin_helper::Promise<v8::Local<v8::Value>> promise,
print_to_pdf::PdfPrintResult print_result,
scoped_refptr<base::RefCountedMemory> data) {
if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) {
promise.RejectWithErrorMessage(
"Failed to generate PDF: " +
print_to_pdf::PdfPrintResultToString(print_result));
return;
}
v8::Isolate* isolate = promise.isolate();
gin_helper::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate, promise.GetContext()));
v8::Local<v8::Value> buffer =
node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()),
data->size())
.ToLocalChecked();
promise.Resolve(buffer);
}
#endif
void WebContents::AddWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsAddFileSystem(std::string(), path);
}
void WebContents::RemoveWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsRemoveFileSystem(path);
}
void WebContents::Undo() {
web_contents()->Undo();
}
void WebContents::Redo() {
web_contents()->Redo();
}
void WebContents::Cut() {
web_contents()->Cut();
}
void WebContents::Copy() {
web_contents()->Copy();
}
void WebContents::CenterSelection() {
web_contents()->CenterSelection();
}
void WebContents::Paste() {
web_contents()->Paste();
}
void WebContents::PasteAndMatchStyle() {
web_contents()->PasteAndMatchStyle();
}
void WebContents::Delete() {
web_contents()->Delete();
}
void WebContents::SelectAll() {
web_contents()->SelectAll();
}
void WebContents::Unselect() {
web_contents()->CollapseSelection();
}
void WebContents::ScrollToTopOfDocument() {
web_contents()->ScrollToTopOfDocument();
}
void WebContents::ScrollToBottomOfDocument() {
web_contents()->ScrollToBottomOfDocument();
}
void WebContents::AdjustSelectionByCharacterOffset(gin::Arguments* args) {
int start_adjust = 0;
int end_adjust = 0;
gin_helper::Dictionary dict;
if (args->GetNext(&dict)) {
dict.Get("start", &start_adjust);
dict.Get("matchCase", &end_adjust);
}
// The selection menu is a Chrome-specific piece of UI.
// TODO(codebytere): maybe surface as an event in the future?
web_contents()->AdjustSelectionByCharacterOffset(
start_adjust, end_adjust, false /* show_selection_menu */);
}
void WebContents::Replace(const std::u16string& word) {
web_contents()->Replace(word);
}
void WebContents::ReplaceMisspelling(const std::u16string& word) {
web_contents()->ReplaceMisspelling(word);
}
uint32_t WebContents::FindInPage(gin::Arguments* args) {
std::u16string search_text;
if (!args->GetNext(&search_text) || search_text.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must provide a non-empty search content");
return 0;
}
uint32_t request_id = ++find_in_page_request_id_;
gin_helper::Dictionary dict;
auto options = blink::mojom::FindOptions::New();
if (args->GetNext(&dict)) {
dict.Get("forward", &options->forward);
dict.Get("matchCase", &options->match_case);
dict.Get("findNext", &options->new_session);
}
web_contents()->Find(request_id, search_text, std::move(options));
return request_id;
}
void WebContents::StopFindInPage(content::StopFindAction action) {
web_contents()->StopFinding(action);
}
void WebContents::ShowDefinitionForSelection() {
#if BUILDFLAG(IS_MAC)
auto* const view = web_contents()->GetRenderWidgetHostView();
if (view)
view->ShowDefinitionForSelection();
#endif
}
void WebContents::CopyImageAt(int x, int y) {
auto* const host = web_contents()->GetPrimaryMainFrame();
if (host)
host->CopyImageAt(x, y);
}
void WebContents::Focus() {
// Focusing on WebContents does not automatically focus the window on macOS
// and Linux, do it manually to match the behavior on Windows.
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
if (owner_window())
owner_window()->Focus(true);
#endif
web_contents()->Focus();
}
#if !BUILDFLAG(IS_MAC)
bool WebContents::IsFocused() const {
auto* view = web_contents()->GetRenderWidgetHostView();
if (!view)
return false;
if (GetType() != Type::kBackgroundPage) {
auto* window = web_contents()->GetNativeView()->GetToplevelWindow();
if (window && !window->IsVisible())
return false;
}
return view->HasFocus();
}
#endif
void WebContents::SendInputEvent(v8::Isolate* isolate,
v8::Local<v8::Value> input_event) {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
blink::WebInputEvent::Type type =
gin::GetWebInputEventType(isolate, input_event);
if (blink::WebInputEvent::IsMouseEventType(type)) {
blink::WebMouseEvent mouse_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) {
if (IsOffScreen()) {
GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event);
} else {
rwh->ForwardMouseEvent(mouse_event);
}
return;
}
} else if (blink::WebInputEvent::IsKeyboardEventType(type)) {
content::NativeWebKeyboardEvent keyboard_event(
blink::WebKeyboardEvent::Type::kRawKeyDown,
blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow());
if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) {
// For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`.
if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown)
keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown);
rwh->ForwardKeyboardEvent(keyboard_event);
return;
}
} else if (type == blink::WebInputEvent::Type::kMouseWheel) {
blink::WebMouseWheelEvent mouse_wheel_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
if (IsOffScreen()) {
GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent(
mouse_wheel_event);
} else {
// Chromium expects phase info in wheel events (and applies a
// DCHECK to verify it). See: https://crbug.com/756524.
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
// Send a synthetic wheel event with phaseEnded to finish scrolling.
mouse_wheel_event.has_synthetic_phase = true;
mouse_wheel_event.delta_x = 0;
mouse_wheel_event.delta_y = 0;
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kEventNonBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
}
return;
}
}
isolate->ThrowException(
v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object")));
}
void WebContents::BeginFrameSubscription(gin::Arguments* args) {
bool only_dirty = false;
FrameSubscriber::FrameCaptureCallback callback;
if (args->Length() > 1) {
if (!args->GetNext(&only_dirty)) {
args->ThrowError();
return;
}
}
if (!args->GetNext(&callback)) {
args->ThrowError();
return;
}
frame_subscriber_ =
std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty);
}
void WebContents::EndFrameSubscription() {
frame_subscriber_.reset();
}
void WebContents::StartDrag(const gin_helper::Dictionary& item,
gin::Arguments* args) {
base::FilePath file;
std::vector<base::FilePath> files;
if (!item.Get("files", &files) && item.Get("file", &file)) {
files.push_back(file);
}
v8::Local<v8::Value> icon_value;
if (!item.Get("icon", &icon_value)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'icon' parameter is required");
return;
}
NativeImage* icon = nullptr;
if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) ||
icon->image().IsEmpty()) {
return;
}
// Start dragging.
if (!files.empty()) {
base::CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop allow;
DragFileItems(files, icon->image(), web_contents()->GetNativeView());
} else {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must specify either 'file' or 'files' option");
}
}
v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) {
gin_helper::Promise<gfx::Image> promise(args->isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
gfx::Rect rect;
args->GetNext(&rect);
bool stay_hidden = false;
bool stay_awake = false;
if (args && args->Length() == 2) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("stayHidden", &stay_hidden);
options.Get("stayAwake", &stay_awake);
}
}
auto* const view = web_contents()->GetRenderWidgetHostView();
if (!view) {
promise.Resolve(gfx::Image());
return handle;
}
#if !BUILDFLAG(IS_MAC)
// If the view's renderer is suspended this may fail on Windows/Linux -
// bail if so. See CopyFromSurface in
// content/public/browser/render_widget_host_view.h.
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (rfh &&
rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) {
promise.Resolve(gfx::Image());
return handle;
}
#endif // BUILDFLAG(IS_MAC)
auto capture_handle = web_contents()->IncrementCapturerCount(
rect.size(), stay_hidden, stay_awake);
// Capture full page if user doesn't specify a |rect|.
const gfx::Size view_size =
rect.IsEmpty() ? view->GetViewBounds().size() : rect.size();
// By default, the requested bitmap size is the view size in screen
// coordinates. However, if there's more pixel detail available on the
// current system, increase the requested bitmap size to capture it all.
gfx::Size bitmap_size = view_size;
const gfx::NativeView native_view = view->GetNativeView();
const float scale = display::Screen::GetScreen()
->GetDisplayNearestView(native_view)
.device_scale_factor();
if (scale > 1.0f)
bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size,
base::BindOnce(&OnCapturePageDone, std::move(promise),
std::move(capture_handle)));
return handle;
}
bool WebContents::IsBeingCaptured() {
return web_contents()->IsBeingCaptured();
}
void WebContents::OnCursorChanged(const ui::Cursor& cursor) {
if (cursor.type() == ui::mojom::CursorType::kCustom) {
Emit("cursor-changed", CursorTypeToString(cursor.type()),
gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()),
cursor.image_scale_factor(),
gfx::Size(cursor.custom_bitmap().width(),
cursor.custom_bitmap().height()),
cursor.custom_hotspot());
} else {
Emit("cursor-changed", CursorTypeToString(cursor.type()));
}
}
bool WebContents::IsGuest() const {
return type_ == Type::kWebView;
}
void WebContents::AttachToIframe(content::WebContents* embedder_web_contents,
int embedder_frame_id) {
attached_ = true;
if (guest_delegate_)
guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id);
}
bool WebContents::IsOffScreen() const {
return type_ == Type::kOffScreen;
}
void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap));
}
void WebContents::StartPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(true);
}
void WebContents::StopPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(false);
}
bool WebContents::IsPainting() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv && osr_wcv->IsPainting();
}
void WebContents::SetFrameRate(int frame_rate) {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetFrameRate(frame_rate);
}
int WebContents::GetFrameRate() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv ? osr_wcv->GetFrameRate() : 0;
}
void WebContents::Invalidate() {
if (IsOffScreen()) {
auto* osr_rwhv = GetOffScreenRenderWidgetHostView();
if (osr_rwhv)
osr_rwhv->Invalidate();
} else {
auto* const window = owner_window();
if (window)
window->Invalidate();
}
}
gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) {
if (IsOffScreen() && wc == web_contents()) {
auto* relay = NativeWindowRelay::FromWebContents(web_contents());
if (relay) {
auto* owner_window = relay->GetNativeWindow();
return owner_window ? owner_window->GetSize() : gfx::Size();
}
}
return gfx::Size();
}
void WebContents::SetZoomLevel(double level) {
zoom_controller_->SetZoomLevel(level);
}
double WebContents::GetZoomLevel() const {
return zoom_controller_->GetZoomLevel();
}
void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower,
double factor) {
if (factor < std::numeric_limits<double>::epsilon()) {
thrower.ThrowError("'zoomFactor' must be a double greater than 0.0");
return;
}
auto level = blink::PageZoomFactorToZoomLevel(factor);
SetZoomLevel(level);
}
double WebContents::GetZoomFactor() const {
auto level = GetZoomLevel();
return blink::PageZoomLevelToZoomFactor(level);
}
void WebContents::SetTemporaryZoomLevel(double level) {
zoom_controller_->SetTemporaryZoomLevel(level);
}
void WebContents::DoGetZoomLevel(
electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback
callback) {
std::move(callback).Run(GetZoomLevel());
}
std::vector<base::FilePath> WebContents::GetPreloadPaths() const {
auto result = SessionPreferences::GetValidPreloads(GetBrowserContext());
if (auto* web_preferences = WebContentsPreferences::From(web_contents())) {
base::FilePath preload;
if (web_preferences->GetPreloadPath(&preload)) {
result.emplace_back(preload);
}
}
return result;
}
v8::Local<v8::Value> WebContents::GetLastWebPreferences(
v8::Isolate* isolate) const {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (!web_preferences)
return v8::Null(isolate);
return gin::ConvertToV8(isolate, *web_preferences->last_preference());
}
v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow(
v8::Isolate* isolate) const {
if (owner_window())
return BrowserWindow::From(isolate, owner_window());
else
return v8::Null(isolate);
}
v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
return v8::Local<v8::Value>::New(isolate, session_);
}
content::WebContents* WebContents::HostWebContents() const {
if (!embedder_)
return nullptr;
return embedder_->web_contents();
}
void WebContents::SetEmbedder(const WebContents* embedder) {
if (embedder) {
NativeWindow* owner_window = nullptr;
auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
if (relay) {
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
content::RenderWidgetHostView* rwhv =
web_contents()->GetRenderWidgetHostView();
if (rwhv) {
rwhv->Hide();
rwhv->Show();
}
}
}
void WebContents::SetDevToolsWebContents(const WebContents* devtools) {
if (inspectable_web_contents_)
inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents());
}
v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const {
gfx::NativeView ptr = web_contents()->GetNativeView();
auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr),
sizeof(gfx::NativeView));
if (buffer.IsEmpty())
return v8::Null(isolate);
else
return buffer.ToLocalChecked();
}
v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
if (devtools_web_contents_.IsEmpty())
return v8::Null(isolate);
else
return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
}
v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
if (debugger_.IsEmpty()) {
auto handle = electron::api::Debugger::Create(isolate, web_contents());
debugger_.Reset(isolate, handle.ToV8());
}
return v8::Local<v8::Value>::New(isolate, debugger_);
}
content::RenderFrameHost* WebContents::MainFrame() {
return web_contents()->GetPrimaryMainFrame();
}
content::RenderFrameHost* WebContents::Opener() {
return web_contents()->GetOpener();
}
void WebContents::NotifyUserActivation() {
content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame();
if (frame)
frame->NotifyUserActivation(
blink::mojom::UserActivationNotificationType::kInteraction);
}
void WebContents::SetImageAnimationPolicy(const std::string& new_policy) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
web_preferences->SetImageAnimationPolicy(new_policy);
web_contents()->OnWebPreferencesChanged();
}
void WebContents::OnInputEvent(const blink::WebInputEvent& event) {
Emit("input-event", event);
}
v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage("Failed to create memory dump");
return handle;
}
auto pid = frame_host->GetProcess()->GetProcess().Pid();
v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext());
memory_instrumentation::MemoryInstrumentation::GetInstance()
->RequestGlobalDumpForPid(
pid, std::vector<std::string>(),
base::BindOnce(&ElectronBindings::DidReceiveMemoryDump,
std::move(context), std::move(promise), pid));
return handle;
}
v8::Local<v8::Promise> WebContents::TakeHeapSnapshot(
v8::Isolate* isolate,
const base::FilePath& file_path) {
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
ScopedAllowBlockingForElectron allow_blocking;
uint32_t flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE;
// The snapshot file is passed to an untrusted process.
flags = base::File::AddFlagsForPassingToUntrustedProcess(flags);
base::File file(file_path, flags);
if (!file.IsValid()) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with invalid file path " +
#if BUILDFLAG(IS_WIN)
base::WideToUTF8(file_path.value()));
#else
file_path.value());
#endif
return handle;
}
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with invalid webContents main frame");
return handle;
}
if (!frame_host->IsRenderFrameLive()) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with nonexistent render frame");
return handle;
}
// This dance with `base::Owned` is to ensure that the interface stays alive
// until the callback is called. Otherwise it would be closed at the end of
// this function.
auto electron_renderer =
std::make_unique<mojo::Remote<mojom::ElectronRenderer>>();
frame_host->GetRemoteInterfaces()->GetInterface(
electron_renderer->BindNewPipeAndPassReceiver());
auto* raw_ptr = electron_renderer.get();
(*raw_ptr)->TakeHeapSnapshot(
mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())),
base::BindOnce(
[](mojo::Remote<mojom::ElectronRenderer>* ep,
gin_helper::Promise<void> promise, bool success) {
if (success) {
promise.Resolve();
} else {
promise.RejectWithErrorMessage("Failed to take heap snapshot");
}
},
base::Owned(std::move(electron_renderer)), std::move(promise)));
return handle;
}
void WebContents::UpdatePreferredSize(content::WebContents* web_contents,
const gfx::Size& pref_size) {
Emit("preferred-size-changed", pref_size);
}
bool WebContents::CanOverscrollContent() {
return false;
}
std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper(
content::RenderFrameHost* frame,
content::EyeDropperListener* listener) {
return ShowEyeDropper(frame, listener);
}
void WebContents::RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) {
FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener),
params);
}
void WebContents::EnumerateDirectory(
content::WebContents* web_contents,
scoped_refptr<content::FileSelectListener> listener,
const base::FilePath& path) {
FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path);
}
bool WebContents::IsFullscreenForTabOrPending(
const content::WebContents* source) {
if (!owner_window())
return is_html_fullscreen();
bool in_transition = owner_window()->fullscreen_transition_state() !=
NativeWindow::FullScreenTransitionState::kNone;
bool is_html_transition = owner_window()->fullscreen_transition_type() ==
NativeWindow::FullScreenTransitionType::kHTML;
return is_html_fullscreen() || (in_transition && is_html_transition);
}
content::FullscreenState WebContents::GetFullscreenState(
const content::WebContents* source) const {
// `const_cast` here because EAM does not have const getters
return const_cast<ExclusiveAccessManager*>(&exclusive_access_manager_)
->fullscreen_controller()
->GetFullscreenState(source);
}
bool WebContents::TakeFocus(content::WebContents* source, bool reverse) {
if (source && source->GetOutermostWebContents() == source) {
// If this is the outermost web contents and the user has tabbed or
// shift + tabbed through all the elements, reset the focus back to
// the first or last element so that it doesn't stay in the body.
source->FocusThroughTabTraversal(reverse);
return true;
}
return false;
}
content::PictureInPictureResult WebContents::EnterPictureInPicture(
content::WebContents* web_contents) {
return PictureInPictureWindowManager::GetInstance()
->EnterVideoPictureInPicture(web_contents);
}
void WebContents::ExitPictureInPicture() {
PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture();
}
void WebContents::DevToolsSaveToFile(const std::string& url,
const std::string& content,
bool save_as) {
base::FilePath path;
auto it = saved_files_.find(url);
if (it != saved_files_.end() && !save_as) {
path = it->second;
} else {
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.title = url;
settings.default_path = base::FilePath::FromUTF8Unsafe(url);
if (!file_dialog::ShowSaveDialogSync(settings, &path)) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "canceledSaveURL", base::Value(url));
return;
}
}
saved_files_[url] = path;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "savedURL", base::Value(url),
base::Value(path.AsUTF8Unsafe()));
file_task_runner_->PostTask(FROM_HERE,
base::BindOnce(&WriteToFile, path, content));
}
void WebContents::DevToolsAppendToFile(const std::string& url,
const std::string& content) {
auto it = saved_files_.find(url);
if (it == saved_files_.end())
return;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL",
base::Value(url));
file_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&AppendToFile, it->second, content));
}
void WebContents::DevToolsRequestFileSystems() {
auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents());
if (file_system_paths.empty()) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List()));
return;
}
std::vector<FileSystem> file_systems;
for (const auto& file_system_path : file_system_paths) {
base::FilePath path =
base::FilePath::FromUTF8Unsafe(file_system_path.first);
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
FileSystem file_system =
CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id,
file_system_path.first, file_system_path.second);
file_systems.push_back(file_system);
}
base::Value::List file_system_value;
for (const auto& file_system : file_systems)
file_system_value.Append(CreateFileSystemValue(file_system));
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded",
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsAddFileSystem(
const std::string& type,
const base::FilePath& file_system_path) {
base::FilePath path = file_system_path;
if (path.empty()) {
std::vector<base::FilePath> paths;
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY;
if (!file_dialog::ShowOpenDialogSync(settings, &paths))
return;
path = paths[0];
}
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe()))
return;
FileSystem file_system = CreateFileSystemStruct(
GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type);
base::Value::Dict file_system_value = CreateFileSystemValue(file_system);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Set(path.AsUTF8Unsafe(), type);
std::string error = ""; // No error
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemAdded", base::Value(error),
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsRemoveFileSystem(
const base::FilePath& file_system_path) {
if (!inspectable_web_contents_)
return;
std::string path = file_system_path.AsUTF8Unsafe();
storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath(
file_system_path);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Remove(path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemRemoved", base::Value(path));
}
void WebContents::DevToolsIndexPath(
int request_id,
const std::string& file_system_path,
const std::string& excluded_folders_message) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsIndexingDone(request_id, file_system_path);
return;
}
if (devtools_indexing_jobs_.count(request_id) != 0)
return;
std::vector<std::string> excluded_folders;
absl::optional<base::Value> parsed_excluded_folders =
base::JSONReader::Read(excluded_folders_message);
if (parsed_excluded_folders && parsed_excluded_folders->is_list()) {
for (const base::Value& folder_path : parsed_excluded_folders->GetList()) {
if (folder_path.is_string())
excluded_folders.push_back(folder_path.GetString());
}
}
devtools_indexing_jobs_[request_id] =
scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>(
devtools_file_system_indexer_->IndexPath(
file_system_path, excluded_folders,
base::BindRepeating(
&WebContents::OnDevToolsIndexingWorkCalculated,
weak_factory_.GetWeakPtr(), request_id, file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingWorked,
weak_factory_.GetWeakPtr(), request_id,
file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingDone,
weak_factory_.GetWeakPtr(), request_id,
file_system_path)));
}
void WebContents::DevToolsStopIndexing(int request_id) {
auto it = devtools_indexing_jobs_.find(request_id);
if (it == devtools_indexing_jobs_.end())
return;
it->second->Stop();
devtools_indexing_jobs_.erase(it);
}
void WebContents::DevToolsOpenInNewTab(const std::string& url) {
Emit("devtools-open-url", url);
}
void WebContents::DevToolsSearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsSearchCompleted(request_id, file_system_path,
std::vector<std::string>());
return;
}
devtools_file_system_indexer_->SearchInPath(
file_system_path, query,
base::BindRepeating(&WebContents::OnDevToolsSearchCompleted,
weak_factory_.GetWeakPtr(), request_id,
file_system_path));
}
void WebContents::DevToolsSetEyeDropperActive(bool active) {
auto* web_contents = GetWebContents();
if (!web_contents)
return;
if (active) {
eye_dropper_ = std::make_unique<DevToolsEyeDropper>(
web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper,
base::Unretained(this)));
} else {
eye_dropper_.reset();
}
}
void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) {
base::Value::Dict color;
color.Set("r", r);
color.Set("g", g);
color.Set("b", b);
color.Set("a", a);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color)));
}
#if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
ui::ImageModel WebContents::GetDevToolsWindowIcon() {
return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{};
}
#endif
#if BUILDFLAG(IS_LINUX)
void WebContents::GetDevToolsWindowWMClass(std::string* name,
std::string* class_name) {
*class_name = Browser::Get()->GetName();
*name = base::ToLowerASCII(*class_name);
}
#endif
void WebContents::OnDevToolsIndexingWorkCalculated(
int request_id,
const std::string& file_system_path,
int total_work) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id),
base::Value(file_system_path), base::Value(total_work));
}
void WebContents::OnDevToolsIndexingWorked(int request_id,
const std::string& file_system_path,
int worked) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingWorked", base::Value(request_id),
base::Value(file_system_path), base::Value(worked));
}
void WebContents::OnDevToolsIndexingDone(int request_id,
const std::string& file_system_path) {
devtools_indexing_jobs_.erase(request_id);
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone",
base::Value(request_id),
base::Value(file_system_path));
}
void WebContents::OnDevToolsSearchCompleted(
int request_id,
const std::string& file_system_path,
const std::vector<std::string>& file_paths) {
base::Value::List file_paths_value;
for (const auto& file_path : file_paths)
file_paths_value.Append(file_path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "searchCompleted", base::Value(request_id),
base::Value(file_system_path), base::Value(std::move(file_paths_value)));
}
void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) {
// Window is already in fullscreen mode, save the state.
if (enter_fullscreen && owner_window()->IsFullscreen()) {
native_fullscreen_ = true;
UpdateHtmlApiFullscreen(true);
return;
}
// Exit html fullscreen state but not window's fullscreen mode.
if (!enter_fullscreen && native_fullscreen_) {
UpdateHtmlApiFullscreen(false);
return;
}
// Set fullscreen on window if allowed.
auto* web_preferences = WebContentsPreferences::From(GetWebContents());
bool html_fullscreenable =
web_preferences
? !web_preferences->ShouldDisableHtmlFullscreenWindowResize()
: true;
if (html_fullscreenable)
owner_window_->SetFullScreen(enter_fullscreen);
UpdateHtmlApiFullscreen(enter_fullscreen);
native_fullscreen_ = false;
}
void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) {
if (fullscreen == is_html_fullscreen())
return;
html_fullscreen_ = fullscreen;
// Notify renderer of the html fullscreen change.
web_contents()
->GetRenderViewHost()
->GetWidget()
->SynchronizeVisualProperties();
// The embedder WebContents is separated from the frame tree of webview, so
// we must manually sync their fullscreen states.
if (embedder_)
embedder_->SetHtmlApiFullscreen(fullscreen);
if (fullscreen) {
Emit("enter-html-full-screen");
owner_window_->NotifyWindowEnterHtmlFullScreen();
} else {
Emit("leave-html-full-screen");
owner_window_->NotifyWindowLeaveHtmlFullScreen();
}
// Make sure all child webviews quit html fullscreen.
if (!fullscreen && !IsGuest()) {
auto* manager = WebViewManager::GetWebViewManager(web_contents());
manager->ForEachGuest(
web_contents(), base::BindRepeating([](content::WebContents* guest) {
WebContents* api_web_contents = WebContents::From(guest);
api_web_contents->SetHtmlApiFullscreen(false);
return false;
}));
}
}
// static
void WebContents::FillObjectTemplate(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin::InvokerOptions options;
options.holder_is_first_argument = true;
options.holder_type = GetClassName();
templ->Set(
gin::StringToSymbol(isolate, "isDestroyed"),
gin::CreateFunctionTemplate(
isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed),
options));
// We use gin_helper::ObjectTemplateBuilder instead of
// gin::ObjectTemplateBuilder here to handle the fact that WebContents is
// destroyable.
gin_helper::ObjectTemplateBuilder(isolate, templ)
.SetMethod("destroy", &WebContents::Destroy)
.SetMethod("close", &WebContents::Close)
.SetMethod("getBackgroundThrottling",
&WebContents::GetBackgroundThrottling)
.SetMethod("setBackgroundThrottling",
&WebContents::SetBackgroundThrottling)
.SetMethod("getProcessId", &WebContents::GetProcessID)
.SetMethod("getOSProcessId", &WebContents::GetOSProcessID)
.SetMethod("equal", &WebContents::Equal)
.SetMethod("_loadURL", &WebContents::LoadURL)
.SetMethod("reload", &WebContents::Reload)
.SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache)
.SetMethod("downloadURL", &WebContents::DownloadURL)
.SetMethod("getURL", &WebContents::GetURL)
.SetMethod("getTitle", &WebContents::GetTitle)
.SetMethod("isLoading", &WebContents::IsLoading)
.SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
.SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
.SetMethod("stop", &WebContents::Stop)
.SetMethod("canGoBack", &WebContents::CanGoBack)
.SetMethod("goBack", &WebContents::GoBack)
.SetMethod("canGoForward", &WebContents::CanGoForward)
.SetMethod("goForward", &WebContents::GoForward)
.SetMethod("canGoToOffset", &WebContents::CanGoToOffset)
.SetMethod("goToOffset", &WebContents::GoToOffset)
.SetMethod("canGoToIndex", &WebContents::CanGoToIndex)
.SetMethod("goToIndex", &WebContents::GoToIndex)
.SetMethod("getActiveIndex", &WebContents::GetActiveIndex)
.SetMethod("clearHistory", &WebContents::ClearHistory)
.SetMethod("length", &WebContents::GetHistoryLength)
.SetMethod("isCrashed", &WebContents::IsCrashed)
.SetMethod("forcefullyCrashRenderer",
&WebContents::ForcefullyCrashRenderer)
.SetMethod("setUserAgent", &WebContents::SetUserAgent)
.SetMethod("getUserAgent", &WebContents::GetUserAgent)
.SetMethod("savePage", &WebContents::SavePage)
.SetMethod("openDevTools", &WebContents::OpenDevTools)
.SetMethod("closeDevTools", &WebContents::CloseDevTools)
.SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
.SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
.SetMethod("getDevToolsTitle", &WebContents::GetDevToolsTitle)
.SetMethod("setDevToolsTitle", &WebContents::SetDevToolsTitle)
.SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation)
.SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation)
.SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
.SetMethod("inspectElement", &WebContents::InspectElement)
.SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts)
.SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
.SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
.SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible)
.SetMethod("undo", &WebContents::Undo)
.SetMethod("redo", &WebContents::Redo)
.SetMethod("cut", &WebContents::Cut)
.SetMethod("copy", &WebContents::Copy)
.SetMethod("centerSelection", &WebContents::CenterSelection)
.SetMethod("paste", &WebContents::Paste)
.SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
.SetMethod("delete", &WebContents::Delete)
.SetMethod("selectAll", &WebContents::SelectAll)
.SetMethod("unselect", &WebContents::Unselect)
.SetMethod("scrollToTop", &WebContents::ScrollToTopOfDocument)
.SetMethod("scrollToBottom", &WebContents::ScrollToBottomOfDocument)
.SetMethod("adjustSelection",
&WebContents::AdjustSelectionByCharacterOffset)
.SetMethod("replace", &WebContents::Replace)
.SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
.SetMethod("findInPage", &WebContents::FindInPage)
.SetMethod("stopFindInPage", &WebContents::StopFindInPage)
.SetMethod("focus", &WebContents::Focus)
.SetMethod("isFocused", &WebContents::IsFocused)
.SetMethod("sendInputEvent", &WebContents::SendInputEvent)
.SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription)
.SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
.SetMethod("startDrag", &WebContents::StartDrag)
.SetMethod("attachToIframe", &WebContents::AttachToIframe)
.SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame)
.SetMethod("isOffscreen", &WebContents::IsOffScreen)
.SetMethod("startPainting", &WebContents::StartPainting)
.SetMethod("stopPainting", &WebContents::StopPainting)
.SetMethod("isPainting", &WebContents::IsPainting)
.SetMethod("setFrameRate", &WebContents::SetFrameRate)
.SetMethod("getFrameRate", &WebContents::GetFrameRate)
.SetMethod("invalidate", &WebContents::Invalidate)
.SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
.SetMethod("getZoomLevel", &WebContents::GetZoomLevel)
.SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
.SetMethod("getZoomFactor", &WebContents::GetZoomFactor)
.SetMethod("getType", &WebContents::GetType)
.SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths)
.SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences)
.SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
.SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
.SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker)
.SetMethod("inspectSharedWorkerById",
&WebContents::InspectSharedWorkerById)
.SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers)
#if BUILDFLAG(ENABLE_PRINTING)
.SetMethod("_print", &WebContents::Print)
.SetMethod("_printToPDF", &WebContents::PrintToPDF)
#endif
.SetMethod("_setNextChildWebPreferences",
&WebContents::SetNextChildWebPreferences)
.SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
.SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
.SetMethod("showDefinitionForSelection",
&WebContents::ShowDefinitionForSelection)
.SetMethod("copyImageAt", &WebContents::CopyImageAt)
.SetMethod("capturePage", &WebContents::CapturePage)
.SetMethod("setEmbedder", &WebContents::SetEmbedder)
.SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents)
.SetMethod("getNativeView", &WebContents::GetNativeView)
.SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured)
.SetMethod("setWebRTCIPHandlingPolicy",
&WebContents::SetWebRTCIPHandlingPolicy)
.SetMethod("setWebRTCUDPPortRange", &WebContents::SetWebRTCUDPPortRange)
.SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID)
.SetMethod("getWebRTCIPHandlingPolicy",
&WebContents::GetWebRTCIPHandlingPolicy)
.SetMethod("getWebRTCUDPPortRange", &WebContents::GetWebRTCUDPPortRange)
.SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot)
.SetMethod("setImageAnimationPolicy",
&WebContents::SetImageAnimationPolicy)
.SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo)
.SetProperty("id", &WebContents::ID)
.SetProperty("session", &WebContents::Session)
.SetProperty("hostWebContents", &WebContents::HostWebContents)
.SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
.SetProperty("debugger", &WebContents::Debugger)
.SetProperty("mainFrame", &WebContents::MainFrame)
.SetProperty("opener", &WebContents::Opener)
.Build();
}
const char* WebContents::GetTypeName() {
return GetClassName();
}
ElectronBrowserContext* WebContents::GetBrowserContext() const {
return static_cast<ElectronBrowserContext*>(
web_contents()->GetBrowserContext());
}
// static
gin::Handle<WebContents> WebContents::New(
v8::Isolate* isolate,
const gin_helper::Dictionary& options) {
gin::Handle<WebContents> handle =
gin::CreateHandle(isolate, new WebContents(isolate, options));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
gin::Handle<WebContents> WebContents::CreateAndTake(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type) {
gin::Handle<WebContents> handle = gin::CreateHandle(
isolate, new WebContents(isolate, std::move(web_contents), type));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
WebContents* WebContents::From(content::WebContents* web_contents) {
if (!web_contents)
return nullptr;
auto* data = static_cast<UserDataLink*>(
web_contents->GetUserData(kElectronApiWebContentsKey));
return data ? data->web_contents.get() : nullptr;
}
// static
gin::Handle<WebContents> WebContents::FromOrCreate(
v8::Isolate* isolate,
content::WebContents* web_contents) {
WebContents* api_web_contents = From(web_contents);
if (!api_web_contents) {
api_web_contents = new WebContents(isolate, web_contents);
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, api_web_contents, "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
}
return gin::CreateHandle(isolate, api_web_contents);
}
// static
gin::Handle<WebContents> WebContents::CreateFromWebPreferences(
v8::Isolate* isolate,
const gin_helper::Dictionary& web_preferences) {
// Check if webPreferences has |webContents| option.
gin::Handle<WebContents> web_contents;
if (web_preferences.GetHidden("webContents", &web_contents) &&
!web_contents.IsEmpty()) {
// Set webPreferences from options if using an existing webContents.
// These preferences will be used when the webContent launches new
// render processes.
auto* existing_preferences =
WebContentsPreferences::From(web_contents->web_contents());
gin_helper::Dictionary web_preferences_dict;
if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(),
&web_preferences_dict)) {
existing_preferences->SetFromDictionary(web_preferences_dict);
absl::optional<SkColor> color =
existing_preferences->GetBackgroundColor();
web_contents->web_contents()->SetPageBaseBackgroundColor(color);
// Because web preferences don't recognize transparency,
// only set rwhv background color if a color exists
auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView();
if (rwhv && color.has_value())
SetBackgroundColor(rwhv, color.value());
}
} else {
// Create one if not.
web_contents = WebContents::New(isolate, web_preferences);
}
return web_contents;
}
// static
WebContents* WebContents::FromID(int32_t id) {
return GetAllWebContents().Lookup(id);
}
// static
std::list<WebContents*> WebContents::GetWebContentsList() {
std::list<WebContents*> list;
for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
!iter.IsAtEnd(); iter.Advance()) {
list.push_back(iter.GetCurrentValue());
}
return list;
}
// static
gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin};
} // namespace electron::api
namespace {
using electron::api::GetAllWebContents;
using electron::api::WebContents;
using electron::api::WebFrameMain;
gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) {
WebContents* contents = WebContents::FromID(id);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromFrame(v8::Isolate* isolate,
WebFrameMain* web_frame) {
content::RenderFrameHost* rfh = web_frame->render_frame_host();
content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh);
WebContents* contents = WebContents::From(source);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromDevToolsTargetID(
v8::Isolate* isolate,
std::string target_id) {
auto agent_host = content::DevToolsAgentHost::GetForId(target_id);
WebContents* contents =
agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr;
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8(
v8::Isolate* isolate) {
std::vector<gin::Handle<WebContents>> list;
for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
!iter.IsAtEnd(); iter.Advance()) {
list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue()));
}
return list;
}
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("WebContents", WebContents::GetConstructor(context));
dict.SetMethod("fromId", &WebContentsFromID);
dict.SetMethod("fromFrame", &WebContentsFromFrame);
dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID);
dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8);
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 19,847 |
[Bug]: loadURL after did-start-loading crashes electron
|
### Preflight Checklist
* [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project.
* [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to.
* [X] I have searched the issue tracker for an issue that matches the one I want to file, without success.
### Issue Details
* **Electron Version:**
* 5.0.10 , 6 ,7
* **Operating System:**
* Windows 10
* **Last Known Working Electron version:** ?
### Expected Behavior
No crash
### Actual Behavior
In electron 5 it crashes with the following code: 2147483651
in electron 6 and 7 it just seems to hang but is basically dead
### To Reproduce
```
const { app, BrowserWindow, BrowserView } = require("electron");
const init = () => {
let browserWindow = new BrowserWindow({
show: true,
});
browserWindow.loadURL("https://www.google.com");
let browserWindow2 = new BrowserWindow({
show: true,
});
browserWindow2.webContents.once("did-start-loading", () => {
browserWindow2.loadURL("https://www.google.com");
});
browserWindow2.loadURL("https://www.test.com");
};
app.on("ready", () => {
init();
});
```
<!--
If you provide a URL, please list the commands required to clone/setup/run your repo e.g.
```sh
$ git clone $YOUR_URL -b $BRANCH
$ npm install
$ npm start || electron .
```
-->
### Additional Information
<!-- Add any other context about the problem here. -->
|
https://github.com/electron/electron/issues/19847
|
https://github.com/electron/electron/pull/40143
|
563c370d51f302b6d4a7fee8b47e1cc3e1ca2fe3
|
86df4db6f10afbe5872f8ecbcbfe6191374fc1f7
| 2019-08-20T20:05:40Z |
c++
| 2023-10-10T10:46:04Z |
spec/api-web-contents-spec.ts
|
import { expect } from 'chai';
import { AddressInfo } from 'node:net';
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as http from 'node:http';
import { BrowserWindow, ipcMain, webContents, session, app, BrowserView, WebContents, deprecate } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import { ifdescribe, defer, waitUntil, listen, ifit } from './lib/spec-helpers';
import { once } from 'node:events';
import { setTimeout } from 'node:timers/promises';
const pdfjs = require('pdfjs-dist');
const fixturesPath = path.resolve(__dirname, 'fixtures');
const mainFixturesPath = path.resolve(__dirname, 'fixtures');
const features = process._linkedBinding('electron_common_features');
describe('webContents module', () => {
describe('getAllWebContents() API', () => {
afterEach(closeAllWindows);
it('returns an array of web contents', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { webviewTag: true }
});
w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html'));
await once(w.webContents, 'did-attach-webview') as [any, WebContents];
w.webContents.openDevTools();
await once(w.webContents, 'devtools-opened');
const all = webContents.getAllWebContents().sort((a, b) => {
return a.id - b.id;
});
expect(all).to.have.length(3);
expect(all[0].getType()).to.equal('window');
expect(all[all.length - 2].getType()).to.equal('webview');
expect(all[all.length - 1].getType()).to.equal('remote');
});
});
describe('fromId()', () => {
it('returns undefined for an unknown id', () => {
expect(webContents.fromId(12345)).to.be.undefined();
});
});
describe('fromFrame()', () => {
it('returns WebContents for mainFrame', () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create();
expect(webContents.fromFrame(contents.mainFrame)).to.equal(contents);
});
it('returns undefined for disposed frame', async () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create();
const { mainFrame } = contents;
contents.destroy();
await waitUntil(() => typeof webContents.fromFrame(mainFrame) === 'undefined');
});
it('throws when passing invalid argument', async () => {
let errored = false;
try {
webContents.fromFrame({} as any);
} catch {
errored = true;
}
expect(errored).to.be.true();
});
});
describe('fromDevToolsTargetId()', () => {
it('returns WebContents for attached DevTools target', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
try {
await w.webContents.debugger.attach('1.3');
const { targetInfo } = await w.webContents.debugger.sendCommand('Target.getTargetInfo');
expect(webContents.fromDevToolsTargetId(targetInfo.targetId)).to.equal(w.webContents);
} finally {
await w.webContents.debugger.detach();
}
});
it('returns undefined for an unknown id', () => {
expect(webContents.fromDevToolsTargetId('nope')).to.be.undefined();
});
});
describe('will-prevent-unload event', function () {
afterEach(closeAllWindows);
it('does not emit if beforeunload returns undefined in a BrowserWindow', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.once('will-prevent-unload', () => {
expect.fail('should not have fired');
});
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
it('does not emit if beforeunload returns undefined in a BrowserView', async () => {
const w = new BrowserWindow({ show: false });
const view = new BrowserView();
w.setBrowserView(view);
view.setBounds(w.getBounds());
view.webContents.once('will-prevent-unload', () => {
expect.fail('should not have fired');
});
await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
it('emits if beforeunload returns false in a BrowserWindow', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
await once(w.webContents, 'will-prevent-unload');
});
it('emits if beforeunload returns false in a BrowserView', async () => {
const w = new BrowserWindow({ show: false });
const view = new BrowserView();
w.setBrowserView(view);
view.setBounds(w.getBounds());
await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
await once(view.webContents, 'will-prevent-unload');
});
it('supports calling preventDefault on will-prevent-unload events in a BrowserWindow', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.once('will-prevent-unload', event => event.preventDefault());
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
});
describe('webContents.send(channel, args...)', () => {
afterEach(closeAllWindows);
it('throws an error when the channel is missing', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
(w.webContents.send as any)();
}).to.throw('Missing required channel argument');
expect(() => {
w.webContents.send(null as any);
}).to.throw('Missing required channel argument');
});
it('does not block node async APIs when sent before document is ready', (done) => {
// Please reference https://github.com/electron/electron/issues/19368 if
// this test fails.
ipcMain.once('async-node-api-done', () => {
done();
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
sandbox: false,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html'));
setTimeout(50).then(() => {
w.webContents.send('test');
});
});
});
ifdescribe(features.isPrintingEnabled())('webContents.print()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
it('throws when invalid settings are passed', () => {
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print(true);
}).to.throw('webContents.print(): Invalid print settings specified.');
});
it('throws when an invalid pageSize is passed', () => {
const badSize = 5;
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print({ pageSize: badSize });
}).to.throw(`Unsupported pageSize: ${badSize}`);
});
it('throws when an invalid callback is passed', () => {
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print({}, true);
}).to.throw('webContents.print(): Invalid optional callback provided.');
});
it('fails when an invalid deviceName is passed', (done) => {
w.webContents.print({ deviceName: 'i-am-a-nonexistent-printer' }, (success, reason) => {
expect(success).to.equal(false);
expect(reason).to.match(/Invalid deviceName provided/);
done();
});
});
it('throws when an invalid pageSize is passed', () => {
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print({ pageSize: 'i-am-a-bad-pagesize' }, () => {});
}).to.throw('Unsupported pageSize: i-am-a-bad-pagesize');
});
it('throws when an invalid custom pageSize is passed', () => {
expect(() => {
w.webContents.print({
pageSize: {
width: 100,
height: 200
}
});
}).to.throw('height and width properties must be minimum 352 microns.');
});
it('does not crash with custom margins', () => {
expect(() => {
w.webContents.print({
silent: true,
margins: {
marginType: 'custom',
top: 1,
bottom: 1,
left: 1,
right: 1
}
});
}).to.not.throw();
});
});
describe('webContents.executeJavaScript', () => {
describe('in about:blank', () => {
const expected = 'hello, world!';
const expectedErrorMsg = 'woops!';
const code = `(() => "${expected}")()`;
const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`;
const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`;
const errorTypes = new Set([
Error,
ReferenceError,
EvalError,
RangeError,
SyntaxError,
TypeError,
URIError
]);
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false } });
await w.loadURL('about:blank');
});
after(closeAllWindows);
it('resolves the returned promise with the result', async () => {
const result = await w.webContents.executeJavaScript(code);
expect(result).to.equal(expected);
});
it('resolves the returned promise with the result if the code returns an asynchronous promise', async () => {
const result = await w.webContents.executeJavaScript(asyncCode);
expect(result).to.equal(expected);
});
it('rejects the returned promise if an async error is thrown', async () => {
await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg);
});
it('rejects the returned promise with an error if an Error.prototype is thrown', async () => {
for (const error of errorTypes) {
await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`))
.to.eventually.be.rejectedWith(error);
}
});
});
describe('on a real page', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((request, response) => {
response.end();
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('works after page load and during subframe load', async () => {
await w.loadURL(serverUrl);
// initiate a sub-frame load, then try and execute script during it
await w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe')
iframe.src = '${serverUrl}/slow'
document.body.appendChild(iframe)
null // don't return the iframe
`);
await w.webContents.executeJavaScript('console.log(\'hello\')');
});
it('executes after page load', async () => {
const executeJavaScript = w.webContents.executeJavaScript('(() => "test")()');
w.loadURL(serverUrl);
const result = await executeJavaScript;
expect(result).to.equal('test');
});
});
});
describe('webContents.executeJavaScriptInIsolatedWorld', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } });
await w.loadURL('about:blank');
});
it('resolves the returned promise with the result', async () => {
await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X = 123' }]);
const isolatedResult = await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X' }]);
const mainWorldResult = await w.webContents.executeJavaScript('window.X');
expect(isolatedResult).to.equal(123);
expect(mainWorldResult).to.equal(undefined);
});
});
describe('loadURL() promise API', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
it('resolves when done loading', async () => {
await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled();
});
it('resolves when done loading a file URL', async () => {
await expect(w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'))).to.eventually.be.fulfilled();
});
it('resolves when navigating within the page', async () => {
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
await setTimeout();
await expect(w.loadURL(w.getURL() + '#foo')).to.eventually.be.fulfilled();
});
it('resolves after browser initiated navigation', async () => {
let finishedLoading = false;
w.webContents.on('did-finish-load', function () {
finishedLoading = true;
});
await w.loadFile(path.join(fixturesPath, 'pages', 'navigate_in_page_and_wait.html'));
expect(finishedLoading).to.be.true();
});
it('rejects when failing to load a file URL', async () => {
await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected()
.and.have.property('code', 'ERR_FILE_NOT_FOUND');
});
// FIXME: Temporarily disable on WOA until
// https://github.com/electron/electron/issues/20008 is resolved
ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('rejects when loading fails due to DNS not resolved', async () => {
await expect(w.loadURL('https://err.name.not.resolved')).to.eventually.be.rejected()
.and.have.property('code', 'ERR_NAME_NOT_RESOLVED');
});
it('rejects when navigation is cancelled due to a bad scheme', async () => {
await expect(w.loadURL('bad-scheme://foo')).to.eventually.be.rejected()
.and.have.property('code', 'ERR_FAILED');
});
it('does not crash when loading a new URL with emulation settings set', async () => {
const setEmulation = async () => {
if (w.webContents) {
w.webContents.debugger.attach('1.3');
const deviceMetrics = {
width: 700,
height: 600,
deviceScaleFactor: 2,
mobile: true,
dontSetVisibleSize: true
};
await w.webContents.debugger.sendCommand(
'Emulation.setDeviceMetricsOverride',
deviceMetrics
);
}
};
try {
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
await setEmulation();
await w.loadURL('data:text/html,<h1>HELLO</h1>');
await setEmulation();
} catch (e) {
expect((e as Error).message).to.match(/Debugger is already attached to the target/);
}
});
it('sets appropriate error information on rejection', async () => {
let err: any;
try {
await w.loadURL('file:non-existent');
} catch (e) {
err = e;
}
expect(err).not.to.be.null();
expect(err.code).to.eql('ERR_FILE_NOT_FOUND');
expect(err.errno).to.eql(-6);
expect(err.url).to.eql(process.platform === 'win32' ? 'file://non-existent/' : 'file:///non-existent');
});
it('rejects if the load is aborted', async () => {
const s = http.createServer(() => { /* never complete the request */ });
const { port } = await listen(s);
const p = expect(w.loadURL(`http://127.0.0.1:${port}`)).to.eventually.be.rejectedWith(Error, /ERR_ABORTED/);
// load a different file before the first load completes, causing the
// first load to be aborted.
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
await p;
s.close();
});
it("doesn't reject when a subframe fails to load", async () => {
let resp = null as unknown as http.ServerResponse;
const s = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<iframe src="http://err.name.not.resolved"></iframe>');
resp = res;
// don't end the response yet
});
const { port } = await listen(s);
const p = new Promise<void>(resolve => {
w.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => {
if (!isMainFrame) {
resolve();
}
});
});
const main = w.loadURL(`http://127.0.0.1:${port}`);
await p;
resp.end();
await main;
s.close();
});
it("doesn't resolve when a subframe loads", async () => {
let resp = null as unknown as http.ServerResponse;
const s = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<iframe src="about:blank"></iframe>');
resp = res;
// don't end the response yet
});
const { port } = await listen(s);
const p = new Promise<void>(resolve => {
w.webContents.on('did-frame-finish-load', (event, isMainFrame) => {
if (!isMainFrame) {
resolve();
}
});
});
const main = w.loadURL(`http://127.0.0.1:${port}`);
await p;
resp.destroy(); // cause the main request to fail
await expect(main).to.eventually.be.rejected()
.and.have.property('errno', -355); // ERR_INCOMPLETE_CHUNKED_ENCODING
s.close();
});
});
describe('getFocusedWebContents() API', () => {
afterEach(closeAllWindows);
// FIXME
ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('returns the focused web contents', async () => {
const w = new BrowserWindow({ show: true });
await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id);
const devToolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools();
await devToolsOpened;
expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.devToolsWebContents!.id);
const devToolsClosed = once(w.webContents, 'devtools-closed');
w.webContents.closeDevTools();
await devToolsClosed;
expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id);
});
it('does not crash when called on a detached dev tools window', async () => {
const w = new BrowserWindow({ show: true });
w.webContents.openDevTools({ mode: 'detach' });
w.webContents.inspectElement(100, 100);
// For some reason we have to wait for two focused events...?
await once(w.webContents, 'devtools-focused');
expect(() => { webContents.getFocusedWebContents(); }).to.not.throw();
// Work around https://github.com/electron/electron/issues/19985
await setTimeout();
const devToolsClosed = once(w.webContents, 'devtools-closed');
w.webContents.closeDevTools();
await devToolsClosed;
expect(() => { webContents.getFocusedWebContents(); }).to.not.throw();
});
});
describe('setDevToolsWebContents() API', () => {
afterEach(closeAllWindows);
it('sets arbitrary webContents as devtools', async () => {
const w = new BrowserWindow({ show: false });
const devtools = new BrowserWindow({ show: false });
const promise = once(devtools.webContents, 'dom-ready');
w.webContents.setDevToolsWebContents(devtools.webContents);
w.webContents.openDevTools();
await promise;
expect(devtools.webContents.getURL().startsWith('devtools://devtools')).to.be.true();
const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name');
expect(result).to.equal('InspectorFrontendHostImpl');
devtools.destroy();
});
});
describe('isFocused() API', () => {
it('returns false when the window is hidden', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(w.isVisible()).to.be.false();
expect(w.webContents.isFocused()).to.be.false();
});
});
describe('isCurrentlyAudible() API', () => {
afterEach(closeAllWindows);
it('returns whether audio is playing', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
await w.webContents.executeJavaScript(`
window.context = new AudioContext
// Start in suspended state, because of the
// new web audio api policy.
context.suspend()
window.oscillator = context.createOscillator()
oscillator.connect(context.destination)
oscillator.start()
`);
let p = once(w.webContents, 'audio-state-changed');
w.webContents.executeJavaScript('context.resume()');
await p;
expect(w.webContents.isCurrentlyAudible()).to.be.true();
p = once(w.webContents, 'audio-state-changed');
w.webContents.executeJavaScript('oscillator.stop()');
await p;
expect(w.webContents.isCurrentlyAudible()).to.be.false();
});
});
describe('openDevTools() API', () => {
afterEach(closeAllWindows);
it('can show window with activation', async () => {
const w = new BrowserWindow({ show: false });
const focused = once(w, 'focus');
w.show();
await focused;
expect(w.isFocused()).to.be.true();
const blurred = once(w, 'blur');
w.webContents.openDevTools({ mode: 'detach', activate: true });
await Promise.all([
once(w.webContents, 'devtools-opened'),
once(w.webContents, 'devtools-focused')
]);
await blurred;
expect(w.isFocused()).to.be.false();
});
it('can show window without activation', async () => {
const w = new BrowserWindow({ show: false });
const devtoolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools({ mode: 'detach', activate: false });
await devtoolsOpened;
expect(w.webContents.isDevToolsOpened()).to.be.true();
});
it('can show a DevTools window with custom title', async () => {
const w = new BrowserWindow({ show: false });
const devtoolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools({ mode: 'detach', activate: false, title: 'myTitle' });
await devtoolsOpened;
expect(w.webContents.getDevToolsTitle()).to.equal('myTitle');
});
});
describe('setDevToolsTitle() API', () => {
afterEach(closeAllWindows);
it('can set devtools title with function', async () => {
const w = new BrowserWindow({ show: false });
const devtoolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools({ mode: 'detach', activate: false });
await devtoolsOpened;
expect(w.webContents.isDevToolsOpened()).to.be.true();
w.webContents.setDevToolsTitle('newTitle');
expect(w.webContents.getDevToolsTitle()).to.equal('newTitle');
});
});
describe('before-input-event event', () => {
afterEach(closeAllWindows);
it('can prevent document keyboard events', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html'));
const keyDown = new Promise(resolve => {
ipcMain.once('keydown', (event, key) => resolve(key));
});
w.webContents.once('before-input-event', (event, input) => {
if (input.key === 'a') event.preventDefault();
});
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' });
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' });
expect(await keyDown).to.equal('b');
});
it('has the correct properties', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const testBeforeInput = async (opts: any) => {
const modifiers = [];
if (opts.shift) modifiers.push('shift');
if (opts.control) modifiers.push('control');
if (opts.alt) modifiers.push('alt');
if (opts.meta) modifiers.push('meta');
if (opts.isAutoRepeat) modifiers.push('isAutoRepeat');
const p = once(w.webContents, 'before-input-event') as Promise<[any, Electron.Input]>;
w.webContents.sendInputEvent({
type: opts.type,
keyCode: opts.keyCode,
modifiers: modifiers as any
});
const [, input] = await p;
expect(input.type).to.equal(opts.type);
expect(input.key).to.equal(opts.key);
expect(input.code).to.equal(opts.code);
expect(input.isAutoRepeat).to.equal(opts.isAutoRepeat);
expect(input.shift).to.equal(opts.shift);
expect(input.control).to.equal(opts.control);
expect(input.alt).to.equal(opts.alt);
expect(input.meta).to.equal(opts.meta);
};
await testBeforeInput({
type: 'keyDown',
key: 'A',
code: 'KeyA',
keyCode: 'a',
shift: true,
control: true,
alt: true,
meta: true,
isAutoRepeat: true
});
await testBeforeInput({
type: 'keyUp',
key: '.',
code: 'Period',
keyCode: '.',
shift: false,
control: true,
alt: true,
meta: false,
isAutoRepeat: false
});
await testBeforeInput({
type: 'keyUp',
key: '!',
code: 'Digit1',
keyCode: '1',
shift: true,
control: false,
alt: false,
meta: true,
isAutoRepeat: false
});
await testBeforeInput({
type: 'keyUp',
key: 'Tab',
code: 'Tab',
keyCode: 'Tab',
shift: false,
control: true,
alt: false,
meta: false,
isAutoRepeat: true
});
});
});
// On Mac, zooming isn't done with the mouse wheel.
ifdescribe(process.platform !== 'darwin')('zoom-changed', () => {
afterEach(closeAllWindows);
it('is emitted with the correct zoom-in info', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const testZoomChanged = async () => {
w.webContents.sendInputEvent({
type: 'mouseWheel',
x: 300,
y: 300,
deltaX: 0,
deltaY: 1,
wheelTicksX: 0,
wheelTicksY: 1,
modifiers: ['control', 'meta']
});
const [, zoomDirection] = await once(w.webContents, 'zoom-changed') as [any, string];
expect(zoomDirection).to.equal('in');
};
await testZoomChanged();
});
it('is emitted with the correct zoom-out info', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const testZoomChanged = async () => {
w.webContents.sendInputEvent({
type: 'mouseWheel',
x: 300,
y: 300,
deltaX: 0,
deltaY: -1,
wheelTicksX: 0,
wheelTicksY: -1,
modifiers: ['control', 'meta']
});
const [, zoomDirection] = await once(w.webContents, 'zoom-changed') as [any, string];
expect(zoomDirection).to.equal('out');
};
await testZoomChanged();
});
});
describe('sendInputEvent(event)', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html'));
});
afterEach(closeAllWindows);
it('can send keydown events', async () => {
const keydown = once(ipcMain, 'keydown');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
expect(key).to.equal('a');
expect(code).to.equal('KeyA');
expect(keyCode).to.equal(65);
expect(shiftKey).to.be.false();
expect(ctrlKey).to.be.false();
expect(altKey).to.be.false();
});
it('can send keydown events with modifiers', async () => {
const keydown = once(ipcMain, 'keydown');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z', modifiers: ['shift', 'ctrl'] });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
expect(key).to.equal('Z');
expect(code).to.equal('KeyZ');
expect(keyCode).to.equal(90);
expect(shiftKey).to.be.true();
expect(ctrlKey).to.be.true();
expect(altKey).to.be.false();
});
it('can send keydown events with special keys', async () => {
const keydown = once(ipcMain, 'keydown');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab', modifiers: ['alt'] });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
expect(key).to.equal('Tab');
expect(code).to.equal('Tab');
expect(keyCode).to.equal(9);
expect(shiftKey).to.be.false();
expect(ctrlKey).to.be.false();
expect(altKey).to.be.true();
});
it('can send char events', async () => {
const keypress = once(ipcMain, 'keypress');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' });
w.webContents.sendInputEvent({ type: 'char', keyCode: 'A' });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress;
expect(key).to.equal('a');
expect(code).to.equal('KeyA');
expect(keyCode).to.equal(65);
expect(shiftKey).to.be.false();
expect(ctrlKey).to.be.false();
expect(altKey).to.be.false();
});
it('can correctly convert accelerators to key codes', async () => {
const keyup = once(ipcMain, 'keyup');
w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' });
w.webContents.sendInputEvent({ keyCode: 'Space', type: 'char' });
w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' });
w.webContents.sendInputEvent({ keyCode: 'Space', type: 'char' });
w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' });
w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'keyUp' });
await keyup;
const inputText = await w.webContents.executeJavaScript('document.getElementById("input").value');
expect(inputText).to.equal('+ + +');
});
it('can send char events with modifiers', async () => {
const keypress = once(ipcMain, 'keypress');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' });
w.webContents.sendInputEvent({ type: 'char', keyCode: 'Z', modifiers: ['shift', 'ctrl'] });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress;
expect(key).to.equal('Z');
expect(code).to.equal('KeyZ');
expect(keyCode).to.equal(90);
expect(shiftKey).to.be.true();
expect(ctrlKey).to.be.true();
expect(altKey).to.be.false();
});
});
describe('insertCSS', () => {
afterEach(closeAllWindows);
it('supports inserting CSS', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await w.webContents.insertCSS('body { background-repeat: round; }');
const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
expect(result).to.equal('round');
});
it('supports removing inserted CSS', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
const key = await w.webContents.insertCSS('body { background-repeat: round; }');
await w.webContents.removeInsertedCSS(key);
const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
expect(result).to.equal('repeat');
});
});
describe('inspectElement()', () => {
afterEach(closeAllWindows);
it('supports inspecting an element in the devtools', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
const event = once(w.webContents, 'devtools-opened');
w.webContents.inspectElement(10, 10);
await event;
});
});
describe('startDrag({file, icon})', () => {
it('throws errors for a missing file or a missing/empty icon', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.webContents.startDrag({ icon: path.join(fixturesPath, 'assets', 'logo.png') } as any);
}).to.throw('Must specify either \'file\' or \'files\' option');
expect(() => {
w.webContents.startDrag({ file: __filename } as any);
}).to.throw('\'icon\' parameter is required');
expect(() => {
w.webContents.startDrag({ file: __filename, icon: path.join(mainFixturesPath, 'blank.png') });
}).to.throw(/Failed to load image from path (.+)/);
});
});
describe('focus APIs', () => {
describe('focus()', () => {
afterEach(closeAllWindows);
it('does not blur the focused window when the web contents is hidden', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
w.show();
await w.loadURL('about:blank');
w.focus();
const child = new BrowserWindow({ show: false });
child.loadURL('about:blank');
child.webContents.focus();
const currentFocused = w.isFocused();
const childFocused = child.isFocused();
child.close();
expect(currentFocused).to.be.true();
expect(childFocused).to.be.false();
});
});
const moveFocusToDevTools = async (win: BrowserWindow) => {
const devToolsOpened = once(win.webContents, 'devtools-opened');
win.webContents.openDevTools({ mode: 'right' });
await devToolsOpened;
win.webContents.devToolsWebContents!.focus();
};
describe('focus event', () => {
afterEach(closeAllWindows);
it('is triggered when web contents is focused', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
await moveFocusToDevTools(w);
const focusPromise = once(w.webContents, 'focus');
w.webContents.focus();
await expect(focusPromise).to.eventually.be.fulfilled();
});
});
describe('blur event', () => {
afterEach(closeAllWindows);
it('is triggered when web contents is blurred', async () => {
const w = new BrowserWindow({ show: true });
await w.loadURL('about:blank');
w.webContents.focus();
const blurPromise = once(w.webContents, 'blur');
await moveFocusToDevTools(w);
await expect(blurPromise).to.eventually.be.fulfilled();
});
});
});
describe('getOSProcessId()', () => {
afterEach(closeAllWindows);
it('returns a valid process id', async () => {
const w = new BrowserWindow({ show: false });
expect(w.webContents.getOSProcessId()).to.equal(0);
await w.loadURL('about:blank');
expect(w.webContents.getOSProcessId()).to.be.above(0);
});
});
describe('getMediaSourceId()', () => {
afterEach(closeAllWindows);
it('returns a valid stream id', () => {
const w = new BrowserWindow({ show: false });
expect(w.webContents.getMediaSourceId(w.webContents)).to.be.a('string').that.is.not.empty();
});
});
describe('userAgent APIs', () => {
it('is not empty by default', () => {
const w = new BrowserWindow({ show: false });
const userAgent = w.webContents.getUserAgent();
expect(userAgent).to.be.a('string').that.is.not.empty();
});
it('can set the user agent (functions)', () => {
const w = new BrowserWindow({ show: false });
const userAgent = w.webContents.getUserAgent();
w.webContents.setUserAgent('my-user-agent');
expect(w.webContents.getUserAgent()).to.equal('my-user-agent');
w.webContents.setUserAgent(userAgent);
expect(w.webContents.getUserAgent()).to.equal(userAgent);
});
it('can set the user agent (properties)', () => {
const w = new BrowserWindow({ show: false });
const userAgent = w.webContents.userAgent;
w.webContents.userAgent = 'my-user-agent';
expect(w.webContents.userAgent).to.equal('my-user-agent');
w.webContents.userAgent = userAgent;
expect(w.webContents.userAgent).to.equal(userAgent);
});
});
describe('audioMuted APIs', () => {
it('can set the audio mute level (functions)', () => {
const w = new BrowserWindow({ show: false });
w.webContents.setAudioMuted(true);
expect(w.webContents.isAudioMuted()).to.be.true();
w.webContents.setAudioMuted(false);
expect(w.webContents.isAudioMuted()).to.be.false();
});
it('can set the audio mute level (functions)', () => {
const w = new BrowserWindow({ show: false });
w.webContents.audioMuted = true;
expect(w.webContents.audioMuted).to.be.true();
w.webContents.audioMuted = false;
expect(w.webContents.audioMuted).to.be.false();
});
});
describe('zoom api', () => {
const hostZoomMap: Record<string, number> = {
host1: 0.3,
host2: 0.7,
host3: 0.2
};
before(() => {
const protocol = session.defaultSession.protocol;
protocol.registerStringProtocol(standardScheme, (request, callback) => {
const response = `<script>
const {ipcRenderer} = require('electron')
ipcRenderer.send('set-zoom', window.location.hostname)
ipcRenderer.on(window.location.hostname + '-zoom-set', () => {
ipcRenderer.send(window.location.hostname + '-zoom-level')
})
</script>`;
callback({ data: response, mimeType: 'text/html' });
});
});
after(() => {
const protocol = session.defaultSession.protocol;
protocol.unregisterProtocol(standardScheme);
});
afterEach(closeAllWindows);
it('throws on an invalid zoomFactor', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(() => {
w.webContents.setZoomFactor(0.0);
}).to.throw(/'zoomFactor' must be a double greater than 0.0/);
expect(() => {
w.webContents.setZoomFactor(-2.0);
}).to.throw(/'zoomFactor' must be a double greater than 0.0/);
});
it('can set the correct zoom level (functions)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomLevel = w.webContents.getZoomLevel();
expect(zoomLevel).to.eql(0.0);
w.webContents.setZoomLevel(0.5);
const newZoomLevel = w.webContents.getZoomLevel();
expect(newZoomLevel).to.eql(0.5);
} finally {
w.webContents.setZoomLevel(0);
}
});
it('can set the correct zoom level (properties)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomLevel = w.webContents.zoomLevel;
expect(zoomLevel).to.eql(0.0);
w.webContents.zoomLevel = 0.5;
const newZoomLevel = w.webContents.zoomLevel;
expect(newZoomLevel).to.eql(0.5);
} finally {
w.webContents.zoomLevel = 0;
}
});
it('can set the correct zoom factor (functions)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomFactor = w.webContents.getZoomFactor();
expect(zoomFactor).to.eql(1.0);
w.webContents.setZoomFactor(0.5);
const newZoomFactor = w.webContents.getZoomFactor();
expect(newZoomFactor).to.eql(0.5);
} finally {
w.webContents.setZoomFactor(1.0);
}
});
it('can set the correct zoom factor (properties)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomFactor = w.webContents.zoomFactor;
expect(zoomFactor).to.eql(1.0);
w.webContents.zoomFactor = 0.5;
const newZoomFactor = w.webContents.zoomFactor;
expect(newZoomFactor).to.eql(0.5);
} finally {
w.webContents.zoomFactor = 1.0;
}
});
it('can persist zoom level across navigation', (done) => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
let finalNavigation = false;
ipcMain.on('set-zoom', (e, host) => {
const zoomLevel = hostZoomMap[host];
if (!finalNavigation) w.webContents.zoomLevel = zoomLevel;
e.sender.send(`${host}-zoom-set`);
});
ipcMain.on('host1-zoom-level', (e) => {
try {
const zoomLevel = e.sender.getZoomLevel();
const expectedZoomLevel = hostZoomMap.host1;
expect(zoomLevel).to.equal(expectedZoomLevel);
if (finalNavigation) {
done();
} else {
w.loadURL(`${standardScheme}://host2`);
}
} catch (e) {
done(e);
}
});
ipcMain.once('host2-zoom-level', (e) => {
try {
const zoomLevel = e.sender.getZoomLevel();
const expectedZoomLevel = hostZoomMap.host2;
expect(zoomLevel).to.equal(expectedZoomLevel);
finalNavigation = true;
w.webContents.goBack();
} catch (e) {
done(e);
}
});
w.loadURL(`${standardScheme}://host1`);
});
it('can propagate zoom level across same session', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
const w2 = new BrowserWindow({ show: false });
defer(() => {
w2.setClosable(true);
w2.close();
});
await w.loadURL(`${standardScheme}://host3`);
w.webContents.zoomLevel = hostZoomMap.host3;
await w2.loadURL(`${standardScheme}://host3`);
const zoomLevel1 = w.webContents.zoomLevel;
expect(zoomLevel1).to.equal(hostZoomMap.host3);
const zoomLevel2 = w2.webContents.zoomLevel;
expect(zoomLevel1).to.equal(zoomLevel2);
});
it('cannot propagate zoom level across different session', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
const w2 = new BrowserWindow({
show: false,
webPreferences: {
partition: 'temp'
}
});
const protocol = w2.webContents.session.protocol;
protocol.registerStringProtocol(standardScheme, (request, callback) => {
callback('hello');
});
defer(() => {
w2.setClosable(true);
w2.close();
protocol.unregisterProtocol(standardScheme);
});
await w.loadURL(`${standardScheme}://host3`);
w.webContents.zoomLevel = hostZoomMap.host3;
await w2.loadURL(`${standardScheme}://host3`);
const zoomLevel1 = w.webContents.zoomLevel;
expect(zoomLevel1).to.equal(hostZoomMap.host3);
const zoomLevel2 = w2.webContents.zoomLevel;
expect(zoomLevel2).to.equal(0);
expect(zoomLevel1).to.not.equal(zoomLevel2);
});
it('can persist when it contains iframe', (done) => {
const w = new BrowserWindow({ show: false });
const server = http.createServer((req, res) => {
setTimeout(200).then(() => {
res.end();
});
});
listen(server).then(({ url }) => {
const content = `<iframe src=${url}></iframe>`;
w.webContents.on('did-frame-finish-load', (e, isMainFrame) => {
if (!isMainFrame) {
try {
const zoomLevel = w.webContents.zoomLevel;
expect(zoomLevel).to.equal(2.0);
w.webContents.zoomLevel = 0;
done();
} catch (e) {
done(e);
} finally {
server.close();
}
}
});
w.webContents.on('dom-ready', () => {
w.webContents.zoomLevel = 2.0;
});
w.loadURL(`data:text/html,${content}`);
});
});
it('cannot propagate when used with webframe', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const w2 = new BrowserWindow({ show: false });
const temporaryZoomSet = once(ipcMain, 'temporary-zoom-set');
w.loadFile(path.join(fixturesPath, 'pages', 'webframe-zoom.html'));
await temporaryZoomSet;
const finalZoomLevel = w.webContents.getZoomLevel();
await w2.loadFile(path.join(fixturesPath, 'pages', 'c.html'));
const zoomLevel1 = w.webContents.zoomLevel;
const zoomLevel2 = w2.webContents.zoomLevel;
w2.setClosable(true);
w2.close();
expect(zoomLevel1).to.equal(finalZoomLevel);
expect(zoomLevel2).to.equal(0);
expect(zoomLevel1).to.not.equal(zoomLevel2);
});
describe('with unique domains', () => {
let server: http.Server;
let serverUrl: string;
let crossSiteUrl: string;
before(async () => {
server = http.createServer((req, res) => {
setTimeout().then(() => res.end('hey'));
});
serverUrl = (await listen(server)).url;
crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
});
after(() => {
server.close();
});
it('cannot persist zoom level after navigation with webFrame', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const source = `
const {ipcRenderer, webFrame} = require('electron')
webFrame.setZoomLevel(0.6)
ipcRenderer.send('zoom-level-set', webFrame.getZoomLevel())
`;
const zoomLevelPromise = once(ipcMain, 'zoom-level-set');
await w.loadURL(serverUrl);
await w.webContents.executeJavaScript(source);
let [, zoomLevel] = await zoomLevelPromise;
expect(zoomLevel).to.equal(0.6);
const loadPromise = once(w.webContents, 'did-finish-load');
await w.loadURL(crossSiteUrl);
await loadPromise;
zoomLevel = w.webContents.zoomLevel;
expect(zoomLevel).to.equal(0);
});
});
});
describe('webrtc ip policy api', () => {
afterEach(closeAllWindows);
it('can set and get webrtc ip policies', () => {
const w = new BrowserWindow({ show: false });
const policies = [
'default',
'default_public_interface_only',
'default_public_and_private_interfaces',
'disable_non_proxied_udp'
] as const;
for (const policy of policies) {
w.webContents.setWebRTCIPHandlingPolicy(policy);
expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy);
}
});
});
describe('webrtc udp port range policy api', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
it('check default webrtc udp port range is { min: 0, max: 0 }', () => {
const settings = w.webContents.getWebRTCUDPPortRange();
expect(settings).to.deep.equal({ min: 0, max: 0 });
});
it('can set and get webrtc udp port range policy with correct arguments', () => {
w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65535 });
const settings = w.webContents.getWebRTCUDPPortRange();
expect(settings).to.deep.equal({ min: 1, max: 65535 });
});
it('can not set webrtc udp port range policy with invalid arguments', () => {
expect(() => {
w.webContents.setWebRTCUDPPortRange({ min: 0, max: 65535 });
}).to.throw("'min' and 'max' must be in the (0, 65535] range or [0, 0]");
expect(() => {
w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65536 });
}).to.throw("'min' and 'max' must be in the (0, 65535] range or [0, 0]");
expect(() => {
w.webContents.setWebRTCUDPPortRange({ min: 60000, max: 56789 });
}).to.throw("'max' must be greater than or equal to 'min'");
});
it('can reset webrtc udp port range policy to default with { min: 0, max: 0 }', () => {
w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65535 });
const settings = w.webContents.getWebRTCUDPPortRange();
expect(settings).to.deep.equal({ min: 1, max: 65535 });
w.webContents.setWebRTCUDPPortRange({ min: 0, max: 0 });
const defaultSetting = w.webContents.getWebRTCUDPPortRange();
expect(defaultSetting).to.deep.equal({ min: 0, max: 0 });
});
});
describe('opener api', () => {
afterEach(closeAllWindows);
it('can get opener with window.open()', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>;
w.webContents.executeJavaScript('window.open("about:blank")', true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame);
});
it('has no opener when using "noopener"', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>;
w.webContents.executeJavaScript('window.open("about:blank", undefined, "noopener")', true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.be.null();
});
it('can get opener with a[target=_blank][rel=opener]', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>;
w.webContents.executeJavaScript(`(function() {
const a = document.createElement('a');
a.target = '_blank';
a.rel = 'opener';
a.href = 'about:blank';
a.click();
}())`, true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame);
});
it('has no opener with a[target=_blank][rel=noopener]', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>;
w.webContents.executeJavaScript(`(function() {
const a = document.createElement('a');
a.target = '_blank';
a.rel = 'noopener';
a.href = 'about:blank';
a.click();
}())`, true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.be.null();
});
});
describe('render view deleted events', () => {
let server: http.Server;
let serverUrl: string;
let crossSiteUrl: string;
before(async () => {
server = http.createServer((req, res) => {
const respond = () => {
if (req.url === '/redirect-cross-site') {
res.setHeader('Location', `${crossSiteUrl}/redirected`);
res.statusCode = 302;
res.end();
} else if (req.url === '/redirected') {
res.end('<html><script>window.localStorage</script></html>');
} else if (req.url === '/first-window-open') {
res.end(`<html><script>window.open('${serverUrl}/second-window-open', 'first child');</script></html>`);
} else if (req.url === '/second-window-open') {
res.end('<html><script>window.open(\'wrong://url\', \'second child\');</script></html>');
} else {
res.end();
}
};
setTimeout().then(respond);
});
serverUrl = (await listen(server)).url;
crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
});
after(() => {
server.close();
});
afterEach(closeAllWindows);
it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => {
const w = new BrowserWindow({ show: false });
let currentRenderViewDeletedEmitted = false;
const renderViewDeletedHandler = () => {
currentRenderViewDeletedEmitted = true;
};
w.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler);
w.webContents.on('did-finish-load', () => {
w.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler);
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.loadURL(`${serverUrl}/redirect-cross-site`);
await destroyed;
expect(currentRenderViewDeletedEmitted).to.be.false('current-render-view-deleted was emitted');
});
it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => {
const parentWindow = new BrowserWindow({ show: false });
let currentRenderViewDeletedEmitted = false;
let childWindow: BrowserWindow | null = null;
const destroyed = once(parentWindow.webContents, 'destroyed');
const renderViewDeletedHandler = () => {
currentRenderViewDeletedEmitted = true;
};
const childWindowCreated = new Promise<void>((resolve) => {
app.once('browser-window-created', (event, window) => {
childWindow = window;
window.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler);
resolve();
});
});
parentWindow.loadURL(`${serverUrl}/first-window-open`);
await childWindowCreated;
childWindow!.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler);
parentWindow.close();
await destroyed;
expect(currentRenderViewDeletedEmitted).to.be.false('child window was destroyed');
});
it('emits current-render-view-deleted if the current RVHs are deleted', async () => {
const w = new BrowserWindow({ show: false });
let currentRenderViewDeletedEmitted = false;
w.webContents.on('current-render-view-deleted' as any, () => {
currentRenderViewDeletedEmitted = true;
});
w.webContents.on('did-finish-load', () => {
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.loadURL(`${serverUrl}/redirect-cross-site`);
await destroyed;
expect(currentRenderViewDeletedEmitted).to.be.true('current-render-view-deleted wasn\'t emitted');
});
it('emits render-view-deleted if any RVHs are deleted', async () => {
const w = new BrowserWindow({ show: false });
let rvhDeletedCount = 0;
w.webContents.on('render-view-deleted' as any, () => {
rvhDeletedCount++;
});
w.webContents.on('did-finish-load', () => {
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.loadURL(`${serverUrl}/redirect-cross-site`);
await destroyed;
const expectedRenderViewDeletedEventCount = 1;
expect(rvhDeletedCount).to.equal(expectedRenderViewDeletedEventCount, 'render-view-deleted wasn\'t emitted the expected nr. of times');
});
});
describe('setIgnoreMenuShortcuts(ignore)', () => {
afterEach(closeAllWindows);
it('does not throw', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.webContents.setIgnoreMenuShortcuts(true);
w.webContents.setIgnoreMenuShortcuts(false);
}).to.not.throw();
});
});
const crashPrefs = [
{
nodeIntegration: true
},
{
sandbox: true
}
];
const nicePrefs = (o: any) => {
let s = '';
for (const key of Object.keys(o)) {
s += `${key}=${o[key]}, `;
}
return `(${s.slice(0, s.length - 2)})`;
};
for (const prefs of crashPrefs) {
describe(`crash with webPreferences ${nicePrefs(prefs)}`, () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
it('isCrashed() is false by default', () => {
expect(w.webContents.isCrashed()).to.equal(false);
});
it('forcefullyCrashRenderer() crashes the process with reason=killed||crashed', async () => {
expect(w.webContents.isCrashed()).to.equal(false);
const crashEvent = once(w.webContents, 'render-process-gone') as Promise<[any, Electron.RenderProcessGoneDetails]>;
w.webContents.forcefullyCrashRenderer();
const [, details] = await crashEvent;
expect(details.reason === 'killed' || details.reason === 'crashed').to.equal(true, 'reason should be killed || crashed');
expect(w.webContents.isCrashed()).to.equal(true);
});
it('a crashed process is recoverable with reload()', async () => {
expect(w.webContents.isCrashed()).to.equal(false);
w.webContents.forcefullyCrashRenderer();
w.webContents.reload();
expect(w.webContents.isCrashed()).to.equal(false);
});
});
}
// Destroying webContents in its event listener is going to crash when
// Electron is built in Debug mode.
describe('destroy()', () => {
let server: http.Server;
let serverUrl: string;
before((done) => {
server = http.createServer((request, response) => {
switch (request.url) {
case '/net-error':
response.destroy();
break;
case '/200':
response.end();
break;
default:
done('unsupported endpoint');
}
});
listen(server).then(({ url }) => {
serverUrl = url;
done();
});
});
after(() => {
server.close();
});
const events = [
{ name: 'did-start-loading', url: '/200' },
{ name: 'dom-ready', url: '/200' },
{ name: 'did-stop-loading', url: '/200' },
{ name: 'did-finish-load', url: '/200' },
// FIXME: Multiple Emit calls inside an observer assume that object
// will be alive till end of the observer. Synchronous `destroy` api
// violates this contract and crashes.
{ name: 'did-frame-finish-load', url: '/200' },
{ name: 'did-fail-load', url: '/net-error' }
];
for (const e of events) {
it(`should not crash when invoked synchronously inside ${e.name} handler`, async function () {
// This test is flaky on Windows CI and we don't know why, but the
// purpose of this test is to make sure Electron does not crash so it
// is fine to retry this test for a few times.
this.retries(3);
const contents = (webContents as typeof ElectronInternal.WebContents).create();
const originalEmit = contents.emit.bind(contents);
contents.emit = (...args) => { return originalEmit(...args); };
contents.once(e.name as any, () => contents.destroy());
const destroyed = once(contents, 'destroyed');
contents.loadURL(serverUrl + e.url);
await destroyed;
});
}
});
describe('did-change-theme-color event', () => {
afterEach(closeAllWindows);
it('is triggered with correct theme color', (done) => {
const w = new BrowserWindow({ show: true });
let count = 0;
w.webContents.on('did-change-theme-color', (e, color) => {
try {
if (count === 0) {
count += 1;
expect(color).to.equal('#FFEEDD');
w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
} else if (count === 1) {
expect(color).to.be.null();
done();
}
} catch (e) {
done(e);
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'theme-color.html'));
});
});
describe('console-message event', () => {
afterEach(closeAllWindows);
it('is triggered with correct log message', (done) => {
const w = new BrowserWindow({ show: true });
w.webContents.on('console-message', (e, level, message) => {
// Don't just assert as Chromium might emit other logs that we should ignore.
if (message === 'a') {
done();
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'a.html'));
});
});
describe('ipc-message event', () => {
afterEach(closeAllWindows);
it('emits when the renderer process sends an asynchronous message', async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.webContents.loadURL('about:blank');
w.webContents.executeJavaScript(`
require('electron').ipcRenderer.send('message', 'Hello World!')
`);
const [, channel, message] = await once(w.webContents, 'ipc-message');
expect(channel).to.equal('message');
expect(message).to.equal('Hello World!');
});
});
describe('ipc-message-sync event', () => {
afterEach(closeAllWindows);
it('emits when the renderer process sends a synchronous message', async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.webContents.loadURL('about:blank');
const promise: Promise<[string, string]> = new Promise(resolve => {
w.webContents.once('ipc-message-sync', (event, channel, arg) => {
event.returnValue = 'foobar';
resolve([channel, arg]);
});
});
const result = await w.webContents.executeJavaScript(`
require('electron').ipcRenderer.sendSync('message', 'Hello World!')
`);
const [channel, message] = await promise;
expect(channel).to.equal('message');
expect(message).to.equal('Hello World!');
expect(result).to.equal('foobar');
});
});
describe('referrer', () => {
afterEach(closeAllWindows);
it('propagates referrer information to new target=_blank windows', (done) => {
const w = new BrowserWindow({ show: false });
const server = http.createServer((req, res) => {
if (req.url === '/should_have_referrer') {
try {
expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`);
return done();
} catch (e) {
return done(e);
} finally {
server.close();
}
}
res.end('<a id="a" href="/should_have_referrer" target="_blank">link</a>');
});
listen(server).then(({ url }) => {
w.webContents.once('did-finish-load', () => {
w.webContents.setWindowOpenHandler(details => {
expect(details.referrer.url).to.equal(url + '/');
expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin');
return { action: 'allow' };
});
w.webContents.executeJavaScript('a.click()');
});
w.loadURL(url);
});
});
it('propagates referrer information to windows opened with window.open', (done) => {
const w = new BrowserWindow({ show: false });
const server = http.createServer((req, res) => {
if (req.url === '/should_have_referrer') {
try {
expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`);
return done();
} catch (e) {
return done(e);
}
}
res.end('');
});
listen(server).then(({ url }) => {
w.webContents.once('did-finish-load', () => {
w.webContents.setWindowOpenHandler(details => {
expect(details.referrer.url).to.equal(url + '/');
expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin');
return { action: 'allow' };
});
w.webContents.executeJavaScript('window.open(location.href + "should_have_referrer")');
});
w.loadURL(url);
});
});
});
describe('webframe messages in sandboxed contents', () => {
afterEach(closeAllWindows);
it('responds to executeJavaScript', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const result = await w.webContents.executeJavaScript('37 + 5');
expect(result).to.equal(42);
});
});
describe('preload-error event', () => {
afterEach(closeAllWindows);
const generateSpecs = (description: string, sandbox: boolean) => {
describe(description, () => {
it('is triggered when unhandled exception is thrown', async () => {
const preload = path.join(fixturesPath, 'module', 'preload-error-exception.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload
}
});
const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>;
w.loadURL('about:blank');
const [, preloadPath, error] = await promise;
expect(preloadPath).to.equal(preload);
expect(error.message).to.equal('Hello World!');
});
it('is triggered on syntax errors', async () => {
const preload = path.join(fixturesPath, 'module', 'preload-error-syntax.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload
}
});
const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>;
w.loadURL('about:blank');
const [, preloadPath, error] = await promise;
expect(preloadPath).to.equal(preload);
expect(error.message).to.equal('foobar is not defined');
});
it('is triggered when preload script loading fails', async () => {
const preload = path.join(fixturesPath, 'module', 'preload-invalid.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload
}
});
const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>;
w.loadURL('about:blank');
const [, preloadPath, error] = await promise;
expect(preloadPath).to.equal(preload);
expect(error.message).to.contain('preload-invalid.js');
});
});
};
generateSpecs('without sandbox', false);
generateSpecs('with sandbox', true);
});
describe('takeHeapSnapshot()', () => {
afterEach(closeAllWindows);
it('works with sandboxed renderers', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
await w.loadURL('about:blank');
const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot');
const cleanup = () => {
try {
fs.unlinkSync(filePath);
} catch {
// ignore error
}
};
try {
await w.webContents.takeHeapSnapshot(filePath);
const stats = fs.statSync(filePath);
expect(stats.size).not.to.be.equal(0);
} finally {
cleanup();
}
});
it('fails with invalid file path', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
await w.loadURL('about:blank');
const badPath = path.join('i', 'am', 'a', 'super', 'bad', 'path');
const promise = w.webContents.takeHeapSnapshot(badPath);
return expect(promise).to.be.eventually.rejectedWith(Error, `Failed to take heap snapshot with invalid file path ${badPath}`);
});
it('fails with invalid render process', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot');
w.webContents.destroy();
const promise = w.webContents.takeHeapSnapshot(filePath);
return expect(promise).to.be.eventually.rejectedWith(Error, 'Failed to take heap snapshot with nonexistent render frame');
});
});
describe('setBackgroundThrottling()', () => {
afterEach(closeAllWindows);
it('does not crash when allowing', () => {
const w = new BrowserWindow({ show: false });
w.webContents.setBackgroundThrottling(true);
});
it('does not crash when called via BrowserWindow', () => {
const w = new BrowserWindow({ show: false });
w.setBackgroundThrottling(true);
});
it('does not crash when disallowing', () => {
const w = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: true } });
w.webContents.setBackgroundThrottling(false);
});
});
describe('getBackgroundThrottling()', () => {
afterEach(closeAllWindows);
it('works via getter', () => {
const w = new BrowserWindow({ show: false });
w.webContents.setBackgroundThrottling(false);
expect(w.webContents.getBackgroundThrottling()).to.equal(false);
w.webContents.setBackgroundThrottling(true);
expect(w.webContents.getBackgroundThrottling()).to.equal(true);
});
it('works via property', () => {
const w = new BrowserWindow({ show: false });
w.webContents.backgroundThrottling = false;
expect(w.webContents.backgroundThrottling).to.equal(false);
w.webContents.backgroundThrottling = true;
expect(w.webContents.backgroundThrottling).to.equal(true);
});
it('works via BrowserWindow', () => {
const w = new BrowserWindow({ show: false });
w.setBackgroundThrottling(false);
expect(w.getBackgroundThrottling()).to.equal(false);
w.setBackgroundThrottling(true);
expect(w.getBackgroundThrottling()).to.equal(true);
});
});
ifdescribe(features.isPrintingEnabled())('getPrintersAsync()', () => {
afterEach(closeAllWindows);
it('can get printer list', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const printers = await w.webContents.getPrintersAsync();
expect(printers).to.be.an('array');
});
});
ifdescribe(features.isPrintingEnabled())('printToPDF()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
});
afterEach(closeAllWindows);
it('rejects on incorrectly typed parameters', async () => {
const badTypes = {
landscape: [],
displayHeaderFooter: '123',
printBackground: 2,
scale: 'not-a-number',
pageSize: 'IAmAPageSize',
margins: 'terrible',
pageRanges: { oops: 'im-not-the-right-key' },
headerTemplate: [1, 2, 3],
footerTemplate: [4, 5, 6],
preferCSSPageSize: 'no'
};
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
// These will hard crash in Chromium unless we type-check
for (const [key, value] of Object.entries(badTypes)) {
const param = { [key]: value };
await expect(w.webContents.printToPDF(param)).to.eventually.be.rejected();
}
});
it('does not crash when called multiple times in parallel', async () => {
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
const promises = [];
for (let i = 0; i < 3; i++) {
promises.push(w.webContents.printToPDF({}));
}
const results = await Promise.all(promises);
for (const data of results) {
expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
}
});
it('does not crash when called multiple times in sequence', async () => {
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
const results = [];
for (let i = 0; i < 3; i++) {
const result = await w.webContents.printToPDF({});
results.push(result);
}
for (const data of results) {
expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
}
});
it('can print a PDF with default settings', async () => {
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
const data = await w.webContents.printToPDF({});
expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
});
type PageSizeString = Exclude<Required<Electron.PrintToPDFOptions>['pageSize'], Electron.Size>;
it('with custom page sizes', async () => {
const paperFormats: Record<PageSizeString, ElectronInternal.PageSize> = {
Letter: { width: 8.5, height: 11 },
Legal: { width: 8.5, height: 14 },
Tabloid: { width: 11, height: 17 },
Ledger: { width: 17, height: 11 },
A0: { width: 33.1, height: 46.8 },
A1: { width: 23.4, height: 33.1 },
A2: { width: 16.54, height: 23.4 },
A3: { width: 11.7, height: 16.54 },
A4: { width: 8.27, height: 11.7 },
A5: { width: 5.83, height: 8.27 },
A6: { width: 4.13, height: 5.83 }
};
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
for (const format of Object.keys(paperFormats) as PageSizeString[]) {
const data = await w.webContents.printToPDF({ pageSize: format });
const doc = await pdfjs.getDocument(data).promise;
const page = await doc.getPage(1);
// page.view is [top, left, width, height].
const width = page.view[2] / 72;
const height = page.view[3] / 72;
const approxEq = (a: number, b: number, epsilon = 0.01) => Math.abs(a - b) <= epsilon;
expect(approxEq(width, paperFormats[format].width)).to.be.true();
expect(approxEq(height, paperFormats[format].height)).to.be.true();
}
});
it('with custom header and footer', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
const data = await w.webContents.printToPDF({
displayHeaderFooter: true,
headerTemplate: '<div>I\'m a PDF header</div>',
footerTemplate: '<div>I\'m a PDF footer</div>'
});
const doc = await pdfjs.getDocument(data).promise;
const page = await doc.getPage(1);
const { items } = await page.getTextContent();
// Check that generated PDF contains a header.
const containsText = (text: RegExp) => items.some(({ str }: { str: string }) => str.match(text));
expect(containsText(/I'm a PDF header/)).to.be.true();
expect(containsText(/I'm a PDF footer/)).to.be.true();
});
it('in landscape mode', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
const data = await w.webContents.printToPDF({ landscape: true });
const doc = await pdfjs.getDocument(data).promise;
const page = await doc.getPage(1);
// page.view is [top, left, width, height].
const width = page.view[2];
const height = page.view[3];
expect(width).to.be.greaterThan(height);
});
it('with custom page ranges', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-large.html'));
const data = await w.webContents.printToPDF({
pageRanges: '1-3',
landscape: true
});
const doc = await pdfjs.getDocument(data).promise;
// Check that correct # of pages are rendered.
expect(doc.numPages).to.equal(3);
});
it('does not tag PDFs by default', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
const data = await w.webContents.printToPDF({});
const doc = await pdfjs.getDocument(data).promise;
const markInfo = await doc.getMarkInfo();
expect(markInfo).to.be.null();
});
it('can generate tag data for PDFs', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
const data = await w.webContents.printToPDF({ generateTaggedPDF: true });
const doc = await pdfjs.getDocument(data).promise;
const markInfo = await doc.getMarkInfo();
expect(markInfo).to.deep.equal({
Marked: true,
UserProperties: false,
Suspects: false
});
});
});
describe('PictureInPicture video', () => {
afterEach(closeAllWindows);
it('works as expected', async function () {
const w = new BrowserWindow({ webPreferences: { sandbox: true } });
// TODO(codebytere): figure out why this workaround is needed and remove.
// It is not germane to the actual test.
await w.loadFile(path.join(fixturesPath, 'blank.html'));
await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html'));
await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')', true);
const result = await w.webContents.executeJavaScript('runTest(true)', true);
expect(result).to.be.true();
});
});
describe('Shared Workers', () => {
afterEach(closeAllWindows);
it('can get multiple shared workers', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const ready = once(ipcMain, 'ready');
w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html'));
await ready;
const sharedWorkers = w.webContents.getAllSharedWorkers();
expect(sharedWorkers).to.have.lengthOf(2);
expect(sharedWorkers[0].url).to.contain('shared-worker');
expect(sharedWorkers[1].url).to.contain('shared-worker');
});
it('can inspect a specific shared worker', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const ready = once(ipcMain, 'ready');
w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html'));
await ready;
const sharedWorkers = w.webContents.getAllSharedWorkers();
const devtoolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.inspectSharedWorkerById(sharedWorkers[0].id);
await devtoolsOpened;
const devtoolsClosed = once(w.webContents, 'devtools-closed');
w.webContents.closeDevTools();
await devtoolsClosed;
});
});
describe('login event', () => {
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
let serverPort: number;
let proxyServer: http.Server;
let proxyServerPort: number;
before(async () => {
server = http.createServer((request, response) => {
if (request.url === '/no-auth') {
return response.end('ok');
}
if (request.headers.authorization) {
response.writeHead(200, { 'Content-type': 'text/plain' });
return response.end(request.headers.authorization);
}
response
.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' })
.end('401');
});
({ port: serverPort, url: serverUrl } = await listen(server));
});
before(async () => {
proxyServer = http.createServer((request, response) => {
if (request.headers['proxy-authorization']) {
response.writeHead(200, { 'Content-type': 'text/plain' });
return response.end(request.headers['proxy-authorization']);
}
response
.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' })
.end();
});
proxyServerPort = (await listen(proxyServer)).port;
});
afterEach(async () => {
await session.defaultSession.clearAuthCache();
});
after(() => {
server.close();
proxyServer.close();
});
it('is emitted when navigating', async () => {
const [user, pass] = ['user', 'pass'];
const w = new BrowserWindow({ show: false });
let eventRequest: any;
let eventAuthInfo: any;
w.webContents.on('login', (event, request, authInfo, cb) => {
eventRequest = request;
eventAuthInfo = authInfo;
event.preventDefault();
cb(user, pass);
});
await w.loadURL(serverUrl);
const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`);
expect(eventRequest.url).to.equal(serverUrl + '/');
expect(eventAuthInfo.isProxy).to.be.false();
expect(eventAuthInfo.scheme).to.equal('basic');
expect(eventAuthInfo.host).to.equal('127.0.0.1');
expect(eventAuthInfo.port).to.equal(serverPort);
expect(eventAuthInfo.realm).to.equal('Foo');
});
it('is emitted when a proxy requests authorization', async () => {
const customSession = session.fromPartition(`${Math.random()}`);
await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' });
const [user, pass] = ['user', 'pass'];
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
let eventRequest: any;
let eventAuthInfo: any;
w.webContents.on('login', (event, request, authInfo, cb) => {
eventRequest = request;
eventAuthInfo = authInfo;
event.preventDefault();
cb(user, pass);
});
await w.loadURL(`${serverUrl}/no-auth`);
const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`);
expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`);
expect(eventAuthInfo.isProxy).to.be.true();
expect(eventAuthInfo.scheme).to.equal('basic');
expect(eventAuthInfo.host).to.equal('127.0.0.1');
expect(eventAuthInfo.port).to.equal(proxyServerPort);
expect(eventAuthInfo.realm).to.equal('Foo');
});
it('cancels authentication when callback is called with no arguments', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.on('login', (event, request, authInfo, cb) => {
event.preventDefault();
cb();
});
await w.loadURL(serverUrl);
const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
expect(body).to.equal('401');
});
});
describe('page-title-updated event', () => {
afterEach(closeAllWindows);
it('is emitted with a full title for pages with no navigation', async () => {
const bw = new BrowserWindow({ show: false });
await bw.loadURL('about:blank');
bw.webContents.executeJavaScript('child = window.open("", "", "show=no"); null');
const [, child] = await once(app, 'web-contents-created') as [any, WebContents];
bw.webContents.executeJavaScript('child.document.title = "new title"');
const [, title] = await once(child, 'page-title-updated') as [any, string];
expect(title).to.equal('new title');
});
});
describe('crashed event', () => {
afterEach(() => deprecate.setHandler(null));
it('does not crash main process when destroying WebContents in it', (done) => {
const contents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true });
contents.once('crashed', () => {
contents.destroy();
done();
});
contents.loadURL('about:blank').then(() => contents.forcefullyCrashRenderer());
});
it('logs a warning', async () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true });
await contents.loadURL('about:blank');
const messages: string[] = [];
deprecate.setHandler(message => messages.push(message));
const crashEvent = once(contents, 'crashed');
contents.forcefullyCrashRenderer();
const [, killed] = await crashEvent;
expect(killed).to.be.a('boolean');
expect(messages).to.deep.equal(['\'crashed event\' is deprecated and will be removed. Please use \'render-process-gone event\' instead.']);
});
});
describe('context-menu event', () => {
afterEach(closeAllWindows);
it('emits when right-clicked in page', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const promise = once(w.webContents, 'context-menu') as Promise<[any, Electron.ContextMenuParams]>;
// Simulate right-click to create context-menu event.
const opts = { x: 0, y: 0, button: 'right' as const };
w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' });
w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' });
const [, params] = await promise;
expect(params.pageURL).to.equal(w.webContents.getURL());
expect(params.frame).to.be.an('object');
expect(params.x).to.be.a('number');
expect(params.y).to.be.a('number');
});
});
describe('close() method', () => {
afterEach(closeAllWindows);
it('closes when close() is called', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
const destroyed = once(w, 'destroyed');
w.close();
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
it('closes when close() is called after loading a page', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
const destroyed = once(w, 'destroyed');
w.close();
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
it('can be GCed before loading a page', async () => {
const v8Util = process._linkedBinding('electron_common_v8_util');
let registry: FinalizationRegistry<unknown> | null = null;
const cleanedUp = new Promise<number>(resolve => {
registry = new FinalizationRegistry(resolve as any);
});
(() => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
registry!.register(w, 42);
})();
const i = setInterval(() => v8Util.requestGarbageCollectionForTesting(), 100);
defer(() => clearInterval(i));
expect(await cleanedUp).to.equal(42);
});
it('causes its parent browserwindow to be closed', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const closed = once(w, 'closed');
w.webContents.close();
await closed;
expect(w.isDestroyed()).to.be.true();
});
it('ignores beforeunload if waitForBeforeUnload not specified', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
w.on('will-prevent-unload', () => { throw new Error('unexpected will-prevent-unload'); });
const destroyed = once(w, 'destroyed');
w.close();
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
it('runs beforeunload if waitForBeforeUnload is specified', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
const willPreventUnload = once(w, 'will-prevent-unload');
w.close({ waitForBeforeUnload: true });
await willPreventUnload;
expect(w.isDestroyed()).to.be.false();
});
it('overriding beforeunload prevention results in webcontents close', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
w.once('will-prevent-unload', e => e.preventDefault());
const destroyed = once(w, 'destroyed');
w.close({ waitForBeforeUnload: true });
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
});
describe('content-bounds-updated event', () => {
afterEach(closeAllWindows);
it('emits when moveTo is called', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('window.moveTo(100, 100)', true);
const [, rect] = await once(w.webContents, 'content-bounds-updated') as [any, Electron.Rectangle];
const { width, height } = w.getBounds();
expect(rect).to.deep.equal({
x: 100,
y: 100,
width,
height
});
await new Promise(setImmediate);
expect(w.getBounds().x).to.equal(100);
expect(w.getBounds().y).to.equal(100);
});
it('emits when resizeTo is called', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('window.resizeTo(100, 100)', true);
const [, rect] = await once(w.webContents, 'content-bounds-updated') as [any, Electron.Rectangle];
const { x, y } = w.getBounds();
expect(rect).to.deep.equal({
x,
y,
width: 100,
height: 100
});
await new Promise(setImmediate);
expect({
width: w.getBounds().width,
height: w.getBounds().height
}).to.deep.equal(process.platform === 'win32' ? {
// The width is reported as being larger on Windows? I'm not sure why
// this is.
width: 136,
height: 100
} : {
width: 100,
height: 100
});
});
it('does not change window bounds if cancelled', async () => {
const w = new BrowserWindow({ show: false });
const { width, height } = w.getBounds();
w.loadURL('about:blank');
w.webContents.once('content-bounds-updated', e => e.preventDefault());
await w.webContents.executeJavaScript('window.resizeTo(100, 100)', true);
await new Promise(setImmediate);
expect(w.getBounds().width).to.equal(width);
expect(w.getBounds().height).to.equal(height);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 19,847 |
[Bug]: loadURL after did-start-loading crashes electron
|
### Preflight Checklist
* [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project.
* [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to.
* [X] I have searched the issue tracker for an issue that matches the one I want to file, without success.
### Issue Details
* **Electron Version:**
* 5.0.10 , 6 ,7
* **Operating System:**
* Windows 10
* **Last Known Working Electron version:** ?
### Expected Behavior
No crash
### Actual Behavior
In electron 5 it crashes with the following code: 2147483651
in electron 6 and 7 it just seems to hang but is basically dead
### To Reproduce
```
const { app, BrowserWindow, BrowserView } = require("electron");
const init = () => {
let browserWindow = new BrowserWindow({
show: true,
});
browserWindow.loadURL("https://www.google.com");
let browserWindow2 = new BrowserWindow({
show: true,
});
browserWindow2.webContents.once("did-start-loading", () => {
browserWindow2.loadURL("https://www.google.com");
});
browserWindow2.loadURL("https://www.test.com");
};
app.on("ready", () => {
init();
});
```
<!--
If you provide a URL, please list the commands required to clone/setup/run your repo e.g.
```sh
$ git clone $YOUR_URL -b $BRANCH
$ npm install
$ npm start || electron .
```
-->
### Additional Information
<!-- Add any other context about the problem here. -->
|
https://github.com/electron/electron/issues/19847
|
https://github.com/electron/electron/pull/40143
|
563c370d51f302b6d4a7fee8b47e1cc3e1ca2fe3
|
86df4db6f10afbe5872f8ecbcbfe6191374fc1f7
| 2019-08-20T20:05:40Z |
c++
| 2023-10-10T10:46:04Z |
shell/browser/api/electron_api_web_contents.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_web_contents.h"
#include <limits>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/containers/contains.h"
#include "base/containers/fixed_flat_map.h"
#include "base/containers/id_map.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/current_thread.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
#include "chrome/browser/ui/views/eye_dropper/eye_dropper.h"
#include "chrome/common/pref_names.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/security_state/content/content_utils.h"
#include "components/security_state/core/security_state.h"
#include "content/browser/renderer_host/frame_tree_node.h" // nogncheck
#include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/desktop_media_id.h"
#include "content/public/browser/desktop_streams_registry.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/service_worker_context.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/input/native_web_keyboard_event.h"
#include "content/public/common/referrer_type_converters.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/webplugininfo.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "gin/arguments.h"
#include "gin/data_object_builder.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "media/base/mime_util.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "ppapi/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "printing/print_job_constants.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/browser/api/electron_api_browser_window.h"
#include "shell/browser/api/electron_api_debugger.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/api/electron_api_web_frame_main.h"
#include "shell/browser/api/message_port.h"
#include "shell/browser/browser.h"
#include "shell/browser/child_web_contents_tracker.h"
#include "shell/browser/electron_autofill_driver_factory.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/electron_javascript_dialog_manager.h"
#include "shell/browser/electron_navigation_throttle.h"
#include "shell/browser/file_select_helper.h"
#include "shell/browser/native_window.h"
#include "shell/browser/osr/osr_render_widget_host_view.h"
#include "shell/browser/osr/osr_web_contents_view.h"
#include "shell/browser/session_preferences.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/file_dialog.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/browser/web_contents_zoom_controller.h"
#include "shell/browser/web_view_guest_delegate.h"
#include "shell/browser/web_view_manager.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/color_util.h"
#include "shell/common/electron_constants.h"
#include "shell/common/gin_converters/base_converter.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/content_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/frame_converter.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/optional_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/language_util.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "shell/common/thread_restrictions.h"
#include "shell/common/v8_value_serializer.h"
#include "storage/browser/file_system/isolated_context.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/mojom/frame/find_in_page.mojom.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h"
#include "third_party/blink/public/mojom/renderer_preferences.mojom.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
#if BUILDFLAG(IS_WIN)
#include "shell/browser/native_window_views.h"
#endif
#if !BUILDFLAG(IS_MAC)
#include "ui/aura/window.h"
#else
#include "ui/base/cocoa/defaults_utils.h"
#endif
#if BUILDFLAG(IS_LINUX)
#include "ui/linux/linux_ui.h"
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
#include "ui/gfx/font_render_params.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/script_executor.h"
#include "extensions/browser/view_type_utils.h"
#include "extensions/common/mojom/view_type.mojom.h"
#include "shell/browser/extensions/electron_extension_web_contents_observer.h"
#endif
#if BUILDFLAG(ENABLE_PRINTING)
#include "chrome/browser/printing/print_view_manager_base.h"
#include "components/printing/browser/print_manager_utils.h"
#include "components/printing/browser/print_to_pdf/pdf_print_result.h"
#include "components/printing/browser/print_to_pdf/pdf_print_utils.h"
#include "printing/backend/print_backend.h" // nogncheck
#include "printing/mojom/print.mojom.h" // nogncheck
#include "printing/page_range.h"
#include "shell/browser/printing/print_view_manager_electron.h"
#if BUILDFLAG(IS_WIN)
#include "printing/backend/win_helper.h"
#endif
#endif // BUILDFLAG(ENABLE_PRINTING)
#if BUILDFLAG(ENABLE_PDF_VIEWER)
#include "components/pdf/browser/pdf_document_helper.h" // nogncheck
#include "shell/browser/electron_pdf_document_helper_client.h"
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/public/browser/plugin_service.h"
#endif
#if !IS_MAS_BUILD()
#include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck
#endif
namespace gin {
#if BUILDFLAG(ENABLE_PRINTING)
template <>
struct Converter<printing::mojom::MarginType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::MarginType* out) {
using Val = printing::mojom::MarginType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"custom", Val::kCustomMargins},
{"default", Val::kDefaultMargins},
{"none", Val::kNoMargins},
{"printableArea", Val::kPrintableAreaMargins},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<printing::mojom::DuplexMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::DuplexMode* out) {
using Val = printing::mojom::DuplexMode;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"longEdge", Val::kLongEdge},
{"shortEdge", Val::kShortEdge},
{"simplex", Val::kSimplex},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
#endif
template <>
struct Converter<WindowOpenDisposition> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
WindowOpenDisposition val) {
std::string disposition = "other";
switch (val) {
case WindowOpenDisposition::CURRENT_TAB:
disposition = "default";
break;
case WindowOpenDisposition::NEW_FOREGROUND_TAB:
disposition = "foreground-tab";
break;
case WindowOpenDisposition::NEW_BACKGROUND_TAB:
disposition = "background-tab";
break;
case WindowOpenDisposition::NEW_POPUP:
case WindowOpenDisposition::NEW_WINDOW:
disposition = "new-window";
break;
case WindowOpenDisposition::SAVE_TO_DISK:
disposition = "save-to-disk";
break;
default:
break;
}
return gin::ConvertToV8(isolate, disposition);
}
};
template <>
struct Converter<content::SavePageType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
content::SavePageType* out) {
using Val = content::SavePageType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"htmlcomplete", Val::SAVE_PAGE_TYPE_AS_COMPLETE_HTML},
{"htmlonly", Val::SAVE_PAGE_TYPE_AS_ONLY_HTML},
{"mhtml", Val::SAVE_PAGE_TYPE_AS_MHTML},
});
return FromV8WithLowerLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<electron::api::WebContents::Type> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
electron::api::WebContents::Type val) {
using Type = electron::api::WebContents::Type;
std::string type;
switch (val) {
case Type::kBackgroundPage:
type = "backgroundPage";
break;
case Type::kBrowserWindow:
type = "window";
break;
case Type::kBrowserView:
type = "browserView";
break;
case Type::kRemote:
type = "remote";
break;
case Type::kWebView:
type = "webview";
break;
case Type::kOffScreen:
type = "offscreen";
break;
default:
break;
}
return gin::ConvertToV8(isolate, type);
}
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::api::WebContents::Type* out) {
using Val = electron::api::WebContents::Type;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"backgroundPage", Val::kBackgroundPage},
{"browserView", Val::kBrowserView},
{"offscreen", Val::kOffScreen},
{"webview", Val::kWebView},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<scoped_refptr<content::DevToolsAgentHost>> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const scoped_refptr<content::DevToolsAgentHost>& val) {
gin_helper::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("id", val->GetId());
dict.Set("url", val->GetURL().spec());
return dict.GetHandle();
}
};
} // namespace gin
namespace electron::api {
namespace {
constexpr base::StringPiece CursorTypeToString(
ui::mojom::CursorType cursor_type) {
switch (cursor_type) {
case ui::mojom::CursorType::kPointer:
return "pointer";
case ui::mojom::CursorType::kCross:
return "crosshair";
case ui::mojom::CursorType::kHand:
return "hand";
case ui::mojom::CursorType::kIBeam:
return "text";
case ui::mojom::CursorType::kWait:
return "wait";
case ui::mojom::CursorType::kHelp:
return "help";
case ui::mojom::CursorType::kEastResize:
return "e-resize";
case ui::mojom::CursorType::kNorthResize:
return "n-resize";
case ui::mojom::CursorType::kNorthEastResize:
return "ne-resize";
case ui::mojom::CursorType::kNorthWestResize:
return "nw-resize";
case ui::mojom::CursorType::kSouthResize:
return "s-resize";
case ui::mojom::CursorType::kSouthEastResize:
return "se-resize";
case ui::mojom::CursorType::kSouthWestResize:
return "sw-resize";
case ui::mojom::CursorType::kWestResize:
return "w-resize";
case ui::mojom::CursorType::kNorthSouthResize:
return "ns-resize";
case ui::mojom::CursorType::kEastWestResize:
return "ew-resize";
case ui::mojom::CursorType::kNorthEastSouthWestResize:
return "nesw-resize";
case ui::mojom::CursorType::kNorthWestSouthEastResize:
return "nwse-resize";
case ui::mojom::CursorType::kColumnResize:
return "col-resize";
case ui::mojom::CursorType::kRowResize:
return "row-resize";
case ui::mojom::CursorType::kMiddlePanning:
return "m-panning";
case ui::mojom::CursorType::kMiddlePanningVertical:
return "m-panning-vertical";
case ui::mojom::CursorType::kMiddlePanningHorizontal:
return "m-panning-horizontal";
case ui::mojom::CursorType::kEastPanning:
return "e-panning";
case ui::mojom::CursorType::kNorthPanning:
return "n-panning";
case ui::mojom::CursorType::kNorthEastPanning:
return "ne-panning";
case ui::mojom::CursorType::kNorthWestPanning:
return "nw-panning";
case ui::mojom::CursorType::kSouthPanning:
return "s-panning";
case ui::mojom::CursorType::kSouthEastPanning:
return "se-panning";
case ui::mojom::CursorType::kSouthWestPanning:
return "sw-panning";
case ui::mojom::CursorType::kWestPanning:
return "w-panning";
case ui::mojom::CursorType::kMove:
return "move";
case ui::mojom::CursorType::kVerticalText:
return "vertical-text";
case ui::mojom::CursorType::kCell:
return "cell";
case ui::mojom::CursorType::kContextMenu:
return "context-menu";
case ui::mojom::CursorType::kAlias:
return "alias";
case ui::mojom::CursorType::kProgress:
return "progress";
case ui::mojom::CursorType::kNoDrop:
return "nodrop";
case ui::mojom::CursorType::kCopy:
return "copy";
case ui::mojom::CursorType::kNone:
return "none";
case ui::mojom::CursorType::kNotAllowed:
return "not-allowed";
case ui::mojom::CursorType::kZoomIn:
return "zoom-in";
case ui::mojom::CursorType::kZoomOut:
return "zoom-out";
case ui::mojom::CursorType::kGrab:
return "grab";
case ui::mojom::CursorType::kGrabbing:
return "grabbing";
case ui::mojom::CursorType::kCustom:
return "custom";
case ui::mojom::CursorType::kNull:
return "null";
case ui::mojom::CursorType::kDndNone:
return "drag-drop-none";
case ui::mojom::CursorType::kDndMove:
return "drag-drop-move";
case ui::mojom::CursorType::kDndCopy:
return "drag-drop-copy";
case ui::mojom::CursorType::kDndLink:
return "drag-drop-link";
case ui::mojom::CursorType::kNorthSouthNoResize:
return "ns-no-resize";
case ui::mojom::CursorType::kEastWestNoResize:
return "ew-no-resize";
case ui::mojom::CursorType::kNorthEastSouthWestNoResize:
return "nesw-no-resize";
case ui::mojom::CursorType::kNorthWestSouthEastNoResize:
return "nwse-no-resize";
default:
return "default";
}
}
base::IDMap<WebContents*>& GetAllWebContents() {
static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents;
return *s_all_web_contents;
}
void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise,
base::ScopedClosureRunner capture_handle,
const SkBitmap& bitmap) {
// Hack to enable transparency in captured image
promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap));
capture_handle.RunAndReset();
}
absl::optional<base::TimeDelta> GetCursorBlinkInterval() {
#if BUILDFLAG(IS_MAC)
absl::optional<base::TimeDelta> system_value(
ui::TextInsertionCaretBlinkPeriodFromDefaults());
if (system_value)
return *system_value;
#elif BUILDFLAG(IS_LINUX)
if (auto* linux_ui = ui::LinuxUi::instance())
return linux_ui->GetCursorBlinkInterval();
#elif BUILDFLAG(IS_WIN)
const auto system_msec = ::GetCaretBlinkTime();
if (system_msec != 0) {
return (system_msec == INFINITE) ? base::TimeDelta()
: base::Milliseconds(system_msec);
}
#endif
return absl::nullopt;
}
#if BUILDFLAG(ENABLE_PRINTING)
// This will return false if no printer with the provided device_name can be
// found on the network. We need to check this because Chromium does not do
// sanity checking of device_name validity and so will crash on invalid names.
bool IsDeviceNameValid(const std::u16string& device_name) {
#if BUILDFLAG(IS_MAC)
base::apple::ScopedCFTypeRef<CFStringRef> new_printer_id(
base::SysUTF16ToCFStringRef(device_name));
PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get());
bool printer_exists = new_printer != nullptr;
PMRelease(new_printer);
return printer_exists;
#else
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name));
#endif
}
// This function returns a validated device name.
// If the user passed one to webContents.print(), we check that it's valid and
// return it or fail if the network doesn't recognize it. If the user didn't
// pass a device name, we first try to return the system default printer. If one
// isn't set, then pull all the printers and use the first one or fail if none
// exist.
std::pair<std::string, std::u16string> GetDeviceNameToUse(
const std::u16string& device_name) {
#if BUILDFLAG(IS_WIN)
// Blocking is needed here because Windows printer drivers are oftentimes
// not thread-safe and have to be accessed on the UI thread.
ScopedAllowBlockingForElectron allow_blocking;
#endif
if (!device_name.empty()) {
if (!IsDeviceNameValid(device_name))
return std::make_pair("Invalid deviceName provided", std::u16string());
return std::make_pair(std::string(), device_name);
}
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
std::string printer_name;
printing::mojom::ResultCode code =
print_backend->GetDefaultPrinterName(printer_name);
// We don't want to return if this fails since some devices won't have a
// default printer.
if (code != printing::mojom::ResultCode::kSuccess)
LOG(ERROR) << "Failed to get default printer name";
if (printer_name.empty()) {
printing::PrinterList printers;
if (print_backend->EnumeratePrinters(printers) !=
printing::mojom::ResultCode::kSuccess)
return std::make_pair("Failed to enumerate printers", std::u16string());
if (printers.empty())
return std::make_pair("No printers available on the network",
std::u16string());
printer_name = printers.front().printer_name;
}
return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name));
}
// Copied from
// chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54
scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() {
// USER_VISIBLE because the result is displayed in the print preview dialog.
#if !BUILDFLAG(IS_WIN)
static constexpr base::TaskTraits kTraits = {
base::MayBlock(), base::TaskPriority::USER_VISIBLE};
#endif
#if defined(USE_CUPS)
// CUPS is thread safe.
return base::ThreadPool::CreateTaskRunner(kTraits);
#elif BUILDFLAG(IS_WIN)
// Windows drivers are likely not thread-safe and need to be accessed on the
// UI thread.
return content::GetUIThreadTaskRunner({base::TaskPriority::USER_VISIBLE});
#else
// Be conservative on unsupported platforms.
return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits);
#endif
}
#endif
struct UserDataLink : public base::SupportsUserData::Data {
explicit UserDataLink(base::WeakPtr<WebContents> contents)
: web_contents(contents) {}
base::WeakPtr<WebContents> web_contents;
};
const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey;
const char kRootName[] = "<root>";
struct FileSystem {
FileSystem() = default;
FileSystem(const std::string& type,
const std::string& file_system_name,
const std::string& root_url,
const std::string& file_system_path)
: type(type),
file_system_name(file_system_name),
root_url(root_url),
file_system_path(file_system_path) {}
std::string type;
std::string file_system_name;
std::string root_url;
std::string file_system_path;
};
std::string RegisterFileSystem(content::WebContents* web_contents,
const base::FilePath& path) {
auto* isolated_context = storage::IsolatedContext::GetInstance();
std::string root_name(kRootName);
storage::IsolatedContext::ScopedFSHandle file_system =
isolated_context->RegisterFileSystemForPath(
storage::kFileSystemTypeLocal, std::string(), path, &root_name);
content::ChildProcessSecurityPolicy* policy =
content::ChildProcessSecurityPolicy::GetInstance();
content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
int renderer_id = render_view_host->GetProcess()->GetID();
policy->GrantReadFileSystem(renderer_id, file_system.id());
policy->GrantWriteFileSystem(renderer_id, file_system.id());
policy->GrantCreateFileForFileSystem(renderer_id, file_system.id());
policy->GrantDeleteFromFileSystem(renderer_id, file_system.id());
if (!policy->CanReadFile(renderer_id, path))
policy->GrantReadFile(renderer_id, path);
return file_system.id();
}
FileSystem CreateFileSystemStruct(content::WebContents* web_contents,
const std::string& file_system_id,
const std::string& file_system_path,
const std::string& type) {
const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL();
std::string file_system_name =
storage::GetIsolatedFileSystemName(origin, file_system_id);
std::string root_url = storage::GetIsolatedFileSystemRootURIString(
origin, file_system_id, kRootName);
return FileSystem(type, file_system_name, root_url, file_system_path);
}
base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) {
base::Value::Dict value;
value.Set("type", file_system.type);
value.Set("fileSystemName", file_system.file_system_name);
value.Set("rootURL", file_system.root_url);
value.Set("fileSystemPath", file_system.file_system_path);
return value;
}
void WriteToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::WriteFile(path, content.data(), content.size());
}
void AppendToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::AppendToFile(path, content);
}
PrefService* GetPrefService(content::WebContents* web_contents) {
auto* context = web_contents->GetBrowserContext();
return static_cast<electron::ElectronBrowserContext*>(context)->prefs();
}
std::map<std::string, std::string> GetAddedFileSystemPaths(
content::WebContents* web_contents) {
auto* pref_service = GetPrefService(web_contents);
const base::Value::Dict& file_system_paths =
pref_service->GetDict(prefs::kDevToolsFileSystemPaths);
std::map<std::string, std::string> result;
for (auto it : file_system_paths) {
std::string type =
it.second.is_string() ? it.second.GetString() : std::string();
result[it.first] = type;
}
return result;
}
bool IsDevToolsFileSystemAdded(content::WebContents* web_contents,
const std::string& file_system_path) {
return base::Contains(GetAddedFileSystemPaths(web_contents),
file_system_path);
}
void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) {
rwhv->SetBackgroundColor(color);
static_cast<content::RenderWidgetHostViewBase*>(rwhv)
->SetContentBackgroundColor(color);
}
content::RenderFrameHost* GetRenderFrameHost(
content::NavigationHandle* navigation_handle) {
int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId();
content::FrameTreeNode* frame_tree_node =
content::FrameTreeNode::GloballyFindByID(frame_tree_node_id);
content::RenderFrameHostManager* render_manager =
frame_tree_node->render_manager();
content::RenderFrameHost* frame_host = nullptr;
if (render_manager) {
frame_host = render_manager->speculative_frame_host();
if (!frame_host)
frame_host = render_manager->current_frame_host();
}
return frame_host;
}
} // namespace
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) {
switch (view_type) {
case extensions::mojom::ViewType::kExtensionBackgroundPage:
return WebContents::Type::kBackgroundPage;
case extensions::mojom::ViewType::kAppWindow:
case extensions::mojom::ViewType::kComponent:
case extensions::mojom::ViewType::kExtensionDialog:
case extensions::mojom::ViewType::kExtensionPopup:
case extensions::mojom::ViewType::kBackgroundContents:
case extensions::mojom::ViewType::kExtensionGuest:
case extensions::mojom::ViewType::kTabContents:
case extensions::mojom::ViewType::kOffscreenDocument:
case extensions::mojom::ViewType::kExtensionSidePanel:
case extensions::mojom::ViewType::kInvalid:
return WebContents::Type::kRemote;
}
}
#endif
WebContents::WebContents(v8::Isolate* isolate,
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
type_(Type::kRemote),
id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// WebContents created by extension host will have valid ViewType set.
extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents);
if (view_type != extensions::mojom::ViewType::kInvalid) {
InitWithExtensionView(isolate, web_contents, view_type);
}
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents);
script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents);
#endif
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
SetUserAgent(GetBrowserContext()->GetUserAgent());
web_contents->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type)
: content::WebContentsObserver(web_contents.get()),
type_(type),
id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
DCHECK(type != Type::kRemote)
<< "Can't take ownership of a remote WebContents";
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
InitWithSessionAndOptions(isolate, std::move(web_contents), session,
gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
const gin_helper::Dictionary& options)
: id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
// Read options.
options.Get("backgroundThrottling", &background_throttling_);
// Get type
options.Get("type", &type_);
bool b = false;
if (options.Get(options::kOffscreen, &b) && b)
type_ = Type::kOffScreen;
// Init embedder earlier
options.Get("embedder", &embedder_);
// Whether to enable DevTools.
options.Get("devTools", &enable_devtools_);
// BrowserViews are not attached to a window initially so they should start
// off as hidden. This is also important for compositor recycling. See:
// https://github.com/electron/electron/pull/21372
bool initially_shown = type_ != Type::kBrowserView;
options.Get(options::kShow, &initially_shown);
// Obtain the session.
std::string partition;
gin::Handle<api::Session> session;
if (options.Get("session", &session) && !session.IsEmpty()) {
} else if (options.Get("partition", &partition)) {
session = Session::FromPartition(isolate, partition);
} else {
// Use the default session if not specified.
session = Session::FromPartition(isolate, "");
}
session_.Reset(isolate, session.ToV8());
std::unique_ptr<content::WebContents> web_contents;
if (IsGuest()) {
scoped_refptr<content::SiteInstance> site_instance =
content::SiteInstance::CreateForURL(session->browser_context(),
GURL("chrome-guest://fake-host"));
content::WebContents::CreateParams params(session->browser_context(),
site_instance);
guest_delegate_ =
std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this);
params.guest_delegate = guest_delegate_.get();
if (embedder_ && embedder_->IsOffScreen()) {
auto* view = new OffScreenWebContentsView(
false,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
web_contents = content::WebContents::Create(params);
}
} else if (IsOffScreen()) {
// webPreferences does not have a transparent option, so if the window needs
// to be transparent, that will be set at electron_api_browser_window.cc#L57
// and we then need to pull it back out and check it here.
std::string background_color;
options.GetHidden(options::kBackgroundColor, &background_color);
bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT;
content::WebContents::CreateParams params(session->browser_context());
auto* view = new OffScreenWebContentsView(
transparent,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
content::WebContents::CreateParams params(session->browser_context());
params.initially_hidden = !initially_shown;
web_contents = content::WebContents::Create(params);
}
InitWithSessionAndOptions(isolate, std::move(web_contents), session, options);
}
void WebContents::InitZoomController(content::WebContents* web_contents,
const gin_helper::Dictionary& options) {
WebContentsZoomController::CreateForWebContents(web_contents);
zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
double zoom_factor;
if (options.Get(options::kZoomFactor, &zoom_factor))
zoom_controller_->SetDefaultZoomFactor(zoom_factor);
// Nothing to do with ZoomController, but this function gets called in all
// init cases!
content::RenderViewHost* host = web_contents->GetRenderViewHost();
if (host)
host->GetWidget()->AddInputEventObserver(this);
}
void WebContents::InitWithSessionAndOptions(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> owned_web_contents,
gin::Handle<api::Session> session,
const gin_helper::Dictionary& options) {
Observe(owned_web_contents.get());
InitWithWebContents(std::move(owned_web_contents), session->browser_context(),
IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
auto* prefs = web_contents()->GetMutableRendererPrefs();
// Collect preferred languages from OS and browser process. accept_languages
// effects HTTP header, navigator.languages, and CJK fallback font selection.
//
// Note that an application locale set to the browser process might be
// different with the one set to the preference list.
// (e.g. overridden with --lang)
std::string accept_languages =
g_browser_process->GetApplicationLocale() + ",";
for (auto const& language : electron::GetPreferredLanguages()) {
if (language == g_browser_process->GetApplicationLocale())
continue;
accept_languages += language + ",";
}
accept_languages.pop_back();
prefs->accept_languages = accept_languages;
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
// Update font settings.
static const gfx::FontRenderParams params(
gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr));
prefs->should_antialias_text = params.antialiasing;
prefs->use_subpixel_positioning = params.subpixel_positioning;
prefs->hinting = params.hinting;
prefs->use_autohinter = params.autohinter;
prefs->use_bitmaps = params.use_bitmaps;
prefs->subpixel_rendering = params.subpixel_rendering;
#endif
// Honor the system's cursor blink rate settings
if (auto interval = GetCursorBlinkInterval())
prefs->caret_blink_interval = *interval;
// Save the preferences in C++.
// If there's already a WebContentsPreferences object, we created it as part
// of the webContents.setWindowOpenHandler path, so don't overwrite it.
if (!WebContentsPreferences::From(web_contents())) {
new WebContentsPreferences(web_contents(), options);
}
// Trigger re-calculation of webkit prefs.
web_contents()->NotifyPreferencesChanged();
WebContentsPermissionHelper::CreateForWebContents(web_contents());
InitZoomController(web_contents(), options);
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents());
script_executor_ =
std::make_unique<extensions::ScriptExecutor>(web_contents());
#endif
AutofillDriverFactory::CreateForWebContents(web_contents());
SetUserAgent(GetBrowserContext()->GetUserAgent());
if (IsGuest()) {
NativeWindow* owner_window = nullptr;
if (embedder_) {
// New WebContents's owner_window is the embedder's owner_window.
auto* relay =
NativeWindowRelay::FromWebContents(embedder_->web_contents());
if (relay)
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
}
web_contents()->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
void WebContents::InitWithExtensionView(v8::Isolate* isolate,
content::WebContents* web_contents,
extensions::mojom::ViewType view_type) {
// Must reassign type prior to calling `Init`.
type_ = GetTypeFromViewType(view_type);
if (type_ == Type::kRemote)
return;
if (type_ == Type::kBackgroundPage)
// non-background-page WebContents are retained by other classes. We need
// to pin here to prevent background-page WebContents from being GC'd.
// The background page api::WebContents will live until the underlying
// content::WebContents is destroyed.
Pin(isolate);
// Allow toggling DevTools for background pages
Observe(web_contents);
InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents),
GetBrowserContext(), IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
}
#endif
void WebContents::InitWithWebContents(
std::unique_ptr<content::WebContents> web_contents,
ElectronBrowserContext* browser_context,
bool is_guest) {
browser_context_ = browser_context;
web_contents->SetDelegate(this);
#if BUILDFLAG(ENABLE_PRINTING)
PrintViewManagerElectron::CreateForWebContents(web_contents.get());
#endif
// Determine whether the WebContents is offscreen.
auto* web_preferences = WebContentsPreferences::From(web_contents.get());
offscreen_ = web_preferences && web_preferences->IsOffscreen();
// Create InspectableWebContents.
inspectable_web_contents_ = std::make_unique<InspectableWebContents>(
std::move(web_contents), browser_context->prefs(), is_guest);
inspectable_web_contents_->SetDelegate(this);
}
WebContents::~WebContents() {
if (owner_window_) {
owner_window_->RemoveBackgroundThrottlingSource(this);
}
if (web_contents()) {
content::RenderViewHost* host = web_contents()->GetRenderViewHost();
if (host)
host->GetWidget()->RemoveInputEventObserver(this);
}
if (!inspectable_web_contents_) {
WebContentsDestroyed();
return;
}
inspectable_web_contents_->GetView()->SetDelegate(nullptr);
// This event is only for internal use, which is emitted when WebContents is
// being destroyed.
Emit("will-destroy");
// For guest view based on OOPIF, the WebContents is released by the embedder
// frame, and we need to clear the reference to the memory.
bool not_owned_by_this = IsGuest() && attached_;
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// And background pages are owned by extensions::ExtensionHost.
if (type_ == Type::kBackgroundPage)
not_owned_by_this = true;
#endif
if (not_owned_by_this) {
inspectable_web_contents_->ReleaseWebContents();
WebContentsDestroyed();
}
// InspectableWebContents will be automatically destroyed.
}
void WebContents::DeleteThisIfAlive() {
// It is possible that the FirstWeakCallback has been called but the
// SecondWeakCallback has not, in this case the garbage collection of
// WebContents has already started and we should not |delete this|.
// Calling |GetWrapper| can detect this corner case.
auto* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
delete this;
}
void WebContents::Destroy() {
// The content::WebContents should be destroyed asynchronously when possible
// as user may choose to destroy WebContents during an event of it.
if (Browser::Get()->is_shutting_down() || IsGuest()) {
DeleteThisIfAlive();
} else {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&WebContents::DeleteThisIfAlive, GetWeakPtr()));
}
}
void WebContents::Close(absl::optional<gin_helper::Dictionary> options) {
bool dispatch_beforeunload = false;
if (options)
options->Get("waitForBeforeUnload", &dispatch_beforeunload);
if (dispatch_beforeunload &&
web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) {
NotifyUserActivation();
web_contents()->DispatchBeforeUnload(false /* auto_cancel */);
} else {
web_contents()->Close();
}
}
bool WebContents::DidAddMessageToConsole(
content::WebContents* source,
blink::mojom::ConsoleMessageLevel level,
const std::u16string& message,
int32_t line_no,
const std::u16string& source_id) {
return Emit("console-message", static_cast<int32_t>(level), message, line_no,
source_id);
}
void WebContents::OnCreateWindow(
const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const std::string& features,
const scoped_refptr<network::ResourceRequestBody>& body) {
Emit("-new-window", target_url, frame_name, disposition, features, referrer,
body);
}
void WebContents::WebContentsCreatedWithFullParams(
content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const content::mojom::CreateNewWindowParams& params,
content::WebContents* new_contents) {
ChildWebContentsTracker::CreateForWebContents(new_contents);
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents);
tracker->url = params.target_url;
tracker->frame_name = params.frame_name;
tracker->referrer = params.referrer.To<content::Referrer>();
tracker->raw_features = params.raw_features;
tracker->body = params.body;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary dict;
gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate),
&dict);
pending_child_web_preferences_.Reset();
// Associate the preferences passed in via `setWindowOpenHandler` with the
// content::WebContents that was just created for the child window. These
// preferences will be picked up by the RenderWidgetHost via its call to the
// delegate's OverrideWebkitPrefs.
new WebContentsPreferences(new_contents, dict);
}
bool WebContents::IsWebContentsCreationOverridden(
content::SiteInstance* source_site_instance,
content::mojom::WindowContainerType window_container_type,
const GURL& opener_url,
const content::mojom::CreateNewWindowParams& params) {
bool default_prevented = Emit(
"-will-add-new-contents", params.target_url, params.frame_name,
params.raw_features, params.disposition, *params.referrer, params.body);
// If the app prevented the default, redirect to CreateCustomWebContents,
// which always returns nullptr, which will result in the window open being
// prevented (window.open() will return null in the renderer).
return default_prevented;
}
void WebContents::SetNextChildWebPreferences(
const gin_helper::Dictionary preferences) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
// Store these prefs for when Chrome calls WebContentsCreatedWithFullParams
// with the new child contents.
pending_child_web_preferences_.Reset(isolate, preferences.GetHandle());
}
content::WebContents* WebContents::CreateCustomWebContents(
content::RenderFrameHost* opener,
content::SiteInstance* source_site_instance,
bool is_new_browsing_instance,
const GURL& opener_url,
const std::string& frame_name,
const GURL& target_url,
const content::StoragePartitionConfig& partition_config,
content::SessionStorageNamespace* session_storage_namespace) {
return nullptr;
}
void WebContents::AddNewContents(
content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) {
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get());
DCHECK(tracker);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto api_web_contents =
CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow);
// We call RenderFrameCreated here as at this point the empty "about:blank"
// render frame has already been created. If the window never navigates again
// RenderFrameCreated won't be called and certain prefs like
// "kBackgroundColor" will not be applied.
auto* frame = api_web_contents->MainFrame();
if (frame) {
api_web_contents->HandleNewRenderFrame(frame);
}
if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
window_features.bounds.x(), window_features.bounds.y(),
window_features.bounds.width(), window_features.bounds.height(),
tracker->url, tracker->frame_name, tracker->referrer,
tracker->raw_features, tracker->body)) {
api_web_contents->Destroy();
}
}
content::WebContents* WebContents::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
auto weak_this = GetWeakPtr();
if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {
Emit("-new-window", params.url, "", params.disposition, "", params.referrer,
params.post_data);
return nullptr;
}
if (!weak_this || !web_contents())
return nullptr;
content::NavigationController::LoadURLParams load_url_params(params.url);
load_url_params.referrer = params.referrer;
load_url_params.transition_type = params.transition;
load_url_params.extra_headers = params.extra_headers;
load_url_params.should_replace_current_entry =
params.should_replace_current_entry;
load_url_params.is_renderer_initiated = params.is_renderer_initiated;
load_url_params.started_from_context_menu = params.started_from_context_menu;
load_url_params.initiator_origin = params.initiator_origin;
load_url_params.source_site_instance = params.source_site_instance;
load_url_params.frame_tree_node_id = params.frame_tree_node_id;
load_url_params.redirect_chain = params.redirect_chain;
load_url_params.has_user_gesture = params.user_gesture;
load_url_params.blob_url_loader_factory = params.blob_url_loader_factory;
load_url_params.href_translate = params.href_translate;
load_url_params.reload_type = params.reload_type;
if (params.post_data) {
load_url_params.load_type =
content::NavigationController::LOAD_TYPE_HTTP_POST;
load_url_params.post_data = params.post_data;
}
source->GetController().LoadURLWithParams(load_url_params);
return source;
}
void WebContents::BeforeUnloadFired(content::WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) {
if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen ||
type_ == Type::kBrowserView)
*proceed_to_fire_unload = proceed;
else
*proceed_to_fire_unload = true;
// Note that Chromium does not emit this for navigations.
Emit("before-unload-fired", proceed);
}
void WebContents::SetContentsBounds(content::WebContents* source,
const gfx::Rect& rect) {
if (!Emit("content-bounds-updated", rect))
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnSetContentBounds(rect);
}
void WebContents::CloseContents(content::WebContents* source) {
Emit("close");
auto* autofill_driver_factory =
AutofillDriverFactory::FromWebContents(web_contents());
if (autofill_driver_factory) {
autofill_driver_factory->CloseAllPopups();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnCloseContents();
// This is handled by the embedder frame.
if (!IsGuest())
Destroy();
}
void WebContents::ActivateContents(content::WebContents* source) {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnActivateContents();
}
void WebContents::UpdateTargetURL(content::WebContents* source,
const GURL& url) {
Emit("update-target-url", url);
}
bool WebContents::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (type_ == Type::kWebView && embedder_) {
// Send the unhandled keyboard events back to the embedder.
return embedder_->HandleKeyboardEvent(source, event);
} else {
return PlatformHandleKeyboardEvent(source, event);
}
}
#if !BUILDFLAG(IS_MAC)
// NOTE: The macOS version of this function is found in
// electron_api_web_contents_mac.mm, as it requires calling into objective-C
// code.
bool WebContents::PlatformHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
// Escape exits tabbed fullscreen mode.
if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) {
ExitFullscreenModeForTab(source);
return true;
}
// Check if the webContents has preferences and to ignore shortcuts
auto* web_preferences = WebContentsPreferences::From(source);
if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts())
return false;
// Let the NativeWindow handle other parts.
if (owner_window()) {
owner_window()->HandleKeyboardEvent(source, event);
return true;
}
return false;
}
#endif
content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (exclusive_access_manager_.HandleUserKeyEvent(event))
return content::KeyboardEventProcessingResult::HANDLED;
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown ||
event.GetType() == blink::WebInputEvent::Type::kKeyUp) {
// For backwards compatibility, pretend that `kRawKeyDown` events are
// actually `kKeyDown`.
content::NativeWebKeyboardEvent tweaked_event(event);
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown)
tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown);
bool prevent_default = Emit("before-input-event", tweaked_event);
if (prevent_default) {
return content::KeyboardEventProcessingResult::HANDLED;
}
}
return content::KeyboardEventProcessingResult::NOT_HANDLED;
}
void WebContents::ContentsZoomChange(bool zoom_in) {
Emit("zoom-changed", zoom_in ? "in" : "out");
}
Profile* WebContents::GetProfile() {
return nullptr;
}
bool WebContents::IsFullscreen() const {
if (!owner_window())
return false;
return owner_window()->IsFullscreen() || is_html_fullscreen();
}
void WebContents::EnterFullscreen(const GURL& url,
ExclusiveAccessBubbleType bubble_type,
const int64_t display_id) {}
void WebContents::ExitFullscreen() {}
void WebContents::UpdateExclusiveAccessExitBubbleContent(
const GURL& url,
ExclusiveAccessBubbleType bubble_type,
ExclusiveAccessBubbleHideCallback bubble_first_hide_callback,
bool notify_download,
bool force_update) {}
void WebContents::OnExclusiveAccessUserInput() {}
content::WebContents* WebContents::GetActiveWebContents() {
return web_contents();
}
bool WebContents::CanUserExitFullscreen() const {
return true;
}
bool WebContents::IsExclusiveAccessBubbleDisplayed() const {
return false;
}
void WebContents::EnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options) {
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(source);
auto callback =
base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab,
base::Unretained(this), requesting_frame, options);
permission_helper->RequestFullscreenPermission(requesting_frame, callback);
}
void WebContents::OnEnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options,
bool allowed) {
if (!allowed || !owner_window())
return;
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
if (IsFullscreenForTabOrPending(source)) {
DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame());
return;
}
owner_window()->set_fullscreen_transition_type(
NativeWindow::FullScreenTransitionType::kHTML);
exclusive_access_manager_.fullscreen_controller()->EnterFullscreenModeForTab(
requesting_frame, options.display_id);
SetHtmlApiFullscreen(true);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
if (!owner_window())
return;
// This needs to be called before we exit fullscreen on the native window,
// or the controller will incorrectly think we weren't fullscreen and bail.
exclusive_access_manager_.fullscreen_controller()->ExitFullscreenModeForTab(
source);
SetHtmlApiFullscreen(false);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too. Chrome does this indirectly from
// `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::RendererUnresponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host,
base::RepeatingClosure hang_monitor_restarter) {
Emit("unresponsive");
}
void WebContents::RendererResponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host) {
Emit("responsive");
}
bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) {
Emit("context-menu", std::make_pair(params, &render_frame_host));
return true;
}
void WebContents::FindReply(content::WebContents* web_contents,
int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update) {
if (!final_update)
return;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto result = gin_helper::Dictionary::CreateEmpty(isolate);
result.Set("requestId", request_id);
result.Set("matches", number_of_matches);
result.Set("selectionArea", selection_rect);
result.Set("activeMatchOrdinal", active_match_ordinal);
result.Set("finalUpdate", final_update); // Deprecate after 2.0
Emit("found-in-page", result.GetHandle());
}
void WebContents::RequestExclusivePointerAccess(
content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target,
bool allowed) {
if (allowed) {
exclusive_access_manager_.mouse_lock_controller()->RequestToLockMouse(
web_contents, user_gesture, last_unlocked_by_target);
} else {
web_contents->GotResponseToLockMouseRequest(
blink::mojom::PointerLockResult::kPermissionDenied);
}
}
void WebContents::RequestToLockMouse(content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestPointerLockPermission(
user_gesture, last_unlocked_by_target,
base::BindOnce(&WebContents::RequestExclusivePointerAccess,
base::Unretained(this)));
}
void WebContents::LostMouseLock() {
exclusive_access_manager_.mouse_lock_controller()->LostMouseLock();
}
void WebContents::RequestKeyboardLock(content::WebContents* web_contents,
bool esc_key_locked) {
exclusive_access_manager_.keyboard_lock_controller()->RequestKeyboardLock(
web_contents, esc_key_locked);
}
void WebContents::CancelKeyboardLockRequest(
content::WebContents* web_contents) {
exclusive_access_manager_.keyboard_lock_controller()
->CancelKeyboardLockRequest(web_contents);
}
bool WebContents::CheckMediaAccessPermission(
content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::mojom::MediaStreamType type) {
auto* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
return permission_helper->CheckMediaAccessPermission(security_origin, type);
}
void WebContents::RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestMediaAccessPermission(request, std::move(callback));
}
content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager(
content::WebContents* source) {
if (!dialog_manager_)
dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>();
return dialog_manager_.get();
}
void WebContents::OnAudioStateChanged(bool audible) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
gin::Dictionary dict(isolate, event_object);
dict.Set("audible", audible);
EmitWithoutEvent("audio-state-changed", event);
}
void WebContents::BeforeUnloadFired(bool proceed) {
// Do nothing, we override this method just to avoid compilation error since
// there are two virtual functions named BeforeUnloadFired.
}
void WebContents::HandleNewRenderFrame(
content::RenderFrameHost* render_frame_host) {
auto* rwhv = render_frame_host->GetView();
if (!rwhv)
return;
// Set the background color of RenderWidgetHostView.
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences) {
auto maybe_color = web_preferences->GetBackgroundColor();
bool guest = IsGuest() || type_ == Type::kBrowserView;
// If webPreferences has no color stored we need to explicitly set guest
// webContents background color to transparent.
auto bg_color =
maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE);
web_contents()->SetPageBaseBackgroundColor(bg_color);
SetBackgroundColor(rwhv, bg_color);
}
if (!background_throttling_)
render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false);
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (rwh_impl)
rwh_impl->disable_hidden_ = !background_throttling_;
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->MaybeSetupMojoConnection();
}
void WebContents::OnBackgroundColorChanged() {
absl::optional<SkColor> color = web_contents()->GetBackgroundColor();
if (color.has_value()) {
auto* const view = web_contents()->GetRenderWidgetHostView();
static_cast<content::RenderWidgetHostViewBase*>(view)
->SetContentBackgroundColor(color.value());
}
}
void WebContents::RenderFrameCreated(
content::RenderFrameHost* render_frame_host) {
HandleNewRenderFrame(render_frame_host);
// RenderFrameCreated is called for speculative frames which may not be
// used in certain cross-origin navigations. Invoking
// RenderFrameHost::GetLifecycleState currently crashes when called for
// speculative frames so we need to filter it out for now. Check
// https://crbug.com/1183639 for details on when this can be removed.
auto* rfh_impl =
static_cast<content::RenderFrameHostImpl*>(render_frame_host);
if (rfh_impl->lifecycle_state() ==
content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) {
return;
}
content::RenderFrameHost::LifecycleState lifecycle_state =
render_frame_host->GetLifecycleState();
if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.SetGetter("frame", render_frame_host);
Emit("frame-created", details);
}
}
void WebContents::RenderFrameDeleted(
content::RenderFrameHost* render_frame_host) {
// A RenderFrameHost can be deleted when:
// - A WebContents is removed and its containing frames are disposed.
// - An <iframe> is removed from the DOM.
// - Cross-origin navigation creates a new RFH in a separate process which
// is swapped by content::RenderFrameHostManager.
//
// WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID
// to find an existing instance of WebFrameMain. During a cross-origin
// navigation, the deleted RFH will be the old host which was swapped out. In
// this special case, we need to also ensure that WebFrameMain's internal RFH
// matches before marking it as disposed.
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame && web_frame->render_frame_host() == render_frame_host)
web_frame->MarkRenderFrameDisposed();
}
void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) {
if (new_host->IsInPrimaryMainFrame()) {
if (old_host)
old_host->GetRenderWidgetHost()->RemoveInputEventObserver(this);
if (new_host)
new_host->GetRenderWidgetHost()->AddInputEventObserver(this);
}
// During cross-origin navigation, a FrameTreeNode will swap out its RFH.
// If an instance of WebFrameMain exists, it will need to have its RFH
// swapped as well.
//
// |old_host| can be a nullptr so we use |new_host| for looking up the
// WebFrameMain instance.
auto* web_frame = WebFrameMain::FromRenderFrameHost(new_host);
if (web_frame) {
web_frame->UpdateRenderFrameHost(new_host);
}
}
void WebContents::FrameDeleted(int frame_tree_node_id) {
auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id);
if (web_frame)
web_frame->Destroyed();
}
void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
// This event is necessary for tracking any states with respect to
// intermediate render view hosts aka speculative render view hosts. Currently
// used by object-registry.js to ref count remote objects.
Emit("render-view-deleted", render_view_host->GetProcess()->GetID());
if (web_contents()->GetRenderViewHost() == render_view_host) {
// When the RVH that has been deleted is the current RVH it means that the
// the web contents are being closed. This is communicated by this event.
// Currently tracked by guest-window-manager.ts to destroy the
// BrowserWindow.
Emit("current-render-view-deleted",
render_view_host->GetProcess()->GetID());
}
}
void WebContents::PrimaryMainFrameRenderProcessGone(
base::TerminationStatus status) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("reason", status);
details.Set("exitCode", web_contents()->GetCrashedErrorCode());
Emit("render-process-gone", details);
}
void WebContents::PluginCrashed(const base::FilePath& plugin_path,
base::ProcessId plugin_pid) {
#if BUILDFLAG(ENABLE_PLUGINS)
content::WebPluginInfo info;
auto* plugin_service = content::PluginService::GetInstance();
plugin_service->GetPluginInfoByPath(plugin_path, &info);
Emit("plugin-crashed", info.name, info.version);
#endif // BUILDFLAG(ENABLE_PLUGINS)
}
void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id) {
Emit("media-started-playing");
}
void WebContents::MediaStoppedPlaying(
const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id,
content::WebContentsObserver::MediaStoppedReason reason) {
Emit("media-paused");
}
void WebContents::DidChangeThemeColor() {
auto theme_color = web_contents()->GetThemeColor();
if (theme_color) {
Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value()));
} else {
Emit("did-change-theme-color", nullptr);
}
}
void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) {
set_fullscreen_frame(rfh);
}
void WebContents::OnWebContentsFocused(
content::RenderWidgetHost* render_widget_host) {
Emit("focus");
}
void WebContents::OnWebContentsLostFocus(
content::RenderWidgetHost* render_widget_host) {
Emit("blur");
}
void WebContents::DOMContentLoaded(
content::RenderFrameHost* render_frame_host) {
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->DOMContentLoaded();
if (!render_frame_host->GetParent())
Emit("dom-ready");
}
void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url) {
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
auto weak_this = GetWeakPtr();
Emit("did-frame-finish-load", is_main_frame, frame_process_id,
frame_routing_id);
// β οΈWARNING!β οΈ
// Emit() triggers JS which can call destroy() on |this|. It's not safe to
// assume that |this| points to valid memory at this point.
if (is_main_frame && weak_this && web_contents())
Emit("did-finish-load");
}
void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
const GURL& url,
int error_code) {
// See DocumentLoader::StartLoadingResponse() - when we navigate to a media
// resource the original request for the media resource, which resulted in a
// committed navigation, is simply discarded. The media element created
// inside the MediaDocument then makes *another new* request for the same
// media resource.
bool is_media_document =
media::IsSupportedMediaMimeType(web_contents()->GetContentsMimeType());
if (error_code == net::ERR_ABORTED && is_media_document)
return;
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id,
frame_routing_id);
}
void WebContents::DidStartLoading() {
Emit("did-start-loading");
}
void WebContents::DidStopLoading() {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences && web_preferences->ShouldUsePreferredSizeMode())
web_contents()->GetRenderViewHost()->EnablePreferredSizeMode();
Emit("did-stop-loading");
}
bool WebContents::EmitNavigationEvent(
const std::string& event_name,
content::NavigationHandle* navigation_handle) {
bool is_main_frame = navigation_handle->IsInMainFrame();
int frame_process_id = -1, frame_routing_id = -1;
content::RenderFrameHost* frame_host = GetRenderFrameHost(navigation_handle);
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
bool is_same_document = navigation_handle->IsSameDocument();
auto url = navigation_handle->GetURL();
content::RenderFrameHost* initiator_frame_host =
navigation_handle->GetInitiatorFrameToken().has_value()
? content::RenderFrameHost::FromFrameToken(
navigation_handle->GetInitiatorProcessId(),
navigation_handle->GetInitiatorFrameToken().value())
: nullptr;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
gin_helper::Dictionary dict(isolate, event_object);
dict.Set("url", url);
dict.Set("isSameDocument", is_same_document);
dict.Set("isMainFrame", is_main_frame);
dict.Set("frame", frame_host);
dict.SetGetter("initiator", initiator_frame_host);
EmitWithoutEvent(event_name, event, url, is_same_document, is_main_frame,
frame_process_id, frame_routing_id);
return event->GetDefaultPrevented();
}
void WebContents::Message(bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Message", "channel", channel);
// webContents.emit('-ipc-message', new Event(), internal, channel,
// arguments);
EmitWithSender("-ipc-message", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), internal,
channel, std::move(arguments));
}
void WebContents::Invoke(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::InvokeCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel);
// webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments);
EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::OnFirstNonEmptyLayout(
content::RenderFrameHost* render_frame_host) {
if (render_frame_host == web_contents()->GetPrimaryMainFrame()) {
Emit("ready-to-show");
}
}
// This object wraps the InvokeCallback so that if it gets GC'd by V8, we can
// still call the callback and send an error. Not doing so causes a Mojo DCHECK,
// since Mojo requires callbacks to be called before they are destroyed.
class ReplyChannel : public gin::Wrappable<ReplyChannel> {
public:
using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback;
static gin::Handle<ReplyChannel> Create(v8::Isolate* isolate,
InvokeCallback callback) {
return gin::CreateHandle(isolate, new ReplyChannel(std::move(callback)));
}
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override {
return gin::Wrappable<ReplyChannel>::GetObjectTemplateBuilder(isolate)
.SetMethod("sendReply", &ReplyChannel::SendReply);
}
const char* GetTypeName() override { return "ReplyChannel"; }
void SendError(const std::string& msg) {
v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
// If there's no current context, it means we're shutting down, so we
// don't need to send an event.
if (!isolate->GetCurrentContext().IsEmpty()) {
v8::HandleScope scope(isolate);
auto message = gin::DataObjectBuilder(isolate).Set("error", msg).Build();
SendReply(isolate, message);
}
}
private:
explicit ReplyChannel(InvokeCallback callback)
: callback_(std::move(callback)) {}
~ReplyChannel() override {
if (callback_)
SendError("reply was never sent");
}
bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> arg) {
if (!callback_)
return false;
blink::CloneableMessage message;
if (!gin::ConvertFromV8(isolate, arg, &message)) {
return false;
}
std::move(callback_).Run(std::move(message));
return true;
}
InvokeCallback callback_;
};
gin::WrapperInfo ReplyChannel::kWrapperInfo = {gin::kEmbedderNativeGin};
gin::Handle<gin_helper::internal::Event> WebContents::MakeEventWithSender(
v8::Isolate* isolate,
content::RenderFrameHost* frame,
electron::mojom::ElectronApiIPC::InvokeCallback callback) {
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper)) {
if (callback) {
// We must always invoke the callback if present.
ReplyChannel::Create(isolate, std::move(callback))
->SendError("WebContents was destroyed");
}
return gin::Handle<gin_helper::internal::Event>();
}
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
gin_helper::Dictionary dict(isolate, event.ToV8().As<v8::Object>());
if (callback)
dict.Set("_replyChannel",
ReplyChannel::Create(isolate, std::move(callback)));
if (frame) {
dict.Set("frameId", frame->GetRoutingID());
dict.Set("processId", frame->GetProcess()->GetID());
}
return event;
}
void WebContents::ReceivePostMessage(
const std::string& channel,
blink::TransferableMessage message,
content::RenderFrameHost* render_frame_host) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto wrapped_ports =
MessagePort::EntanglePorts(isolate, std::move(message.ports));
v8::Local<v8::Value> message_value =
electron::DeserializeV8Value(isolate, message);
EmitWithSender("-ipc-ports", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), false,
channel, message_value, std::move(wrapped_ports));
}
void WebContents::MessageSync(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::MessageSyncCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel);
// webContents.emit('-ipc-message-sync', new Event(sender, message), internal,
// channel, arguments);
EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::MessageHost(const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel);
// webContents.emit('ipc-message-host', new Event(), channel, args);
EmitWithSender("ipc-message-host", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), channel,
std::move(arguments));
}
void WebContents::UpdateDraggableRegions(
std::vector<mojom::DraggableRegionPtr> regions) {
if (owner_window() && owner_window()->has_frame())
return;
draggable_region_ = DraggableRegionsToSkRegion(regions);
}
void WebContents::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-start-navigation", navigation_handle);
}
void WebContents::DidRedirectNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-redirect-navigation", navigation_handle);
}
void WebContents::ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) {
// Don't focus content in an inactive window.
if (!owner_window())
return;
#if BUILDFLAG(IS_MAC)
if (!owner_window()->IsActive())
return;
#else
if (!owner_window()->widget()->IsActive())
return;
#endif
// Don't focus content after subframe navigations.
if (!navigation_handle->IsInMainFrame())
return;
// Only focus for top-level contents.
if (type_ != Type::kBrowserWindow)
return;
web_contents()->SetInitialFocus();
}
void WebContents::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (owner_window_) {
owner_window_->NotifyLayoutWindowControlsOverlay();
}
if (!navigation_handle->HasCommitted())
return;
bool is_main_frame = navigation_handle->IsInMainFrame();
content::RenderFrameHost* frame_host =
navigation_handle->GetRenderFrameHost();
int frame_process_id = -1, frame_routing_id = -1;
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
if (!navigation_handle->IsErrorPage()) {
// FIXME: All the Emit() calls below could potentially result in |this|
// being destroyed (by JS listening for the event and calling
// webContents.destroy()).
auto url = navigation_handle->GetURL();
bool is_same_document = navigation_handle->IsSameDocument();
if (is_same_document) {
Emit("did-navigate-in-page", url, is_main_frame, frame_process_id,
frame_routing_id);
} else {
const net::HttpResponseHeaders* http_response =
navigation_handle->GetResponseHeaders();
std::string http_status_text;
int http_response_code = -1;
if (http_response) {
http_status_text = http_response->GetStatusText();
http_response_code = http_response->response_code();
}
Emit("did-frame-navigate", url, http_response_code, http_status_text,
is_main_frame, frame_process_id, frame_routing_id);
if (is_main_frame) {
Emit("did-navigate", url, http_response_code, http_status_text);
}
}
if (IsGuest())
Emit("load-commit", url, is_main_frame);
} else {
auto url = navigation_handle->GetURL();
int code = navigation_handle->GetNetErrorCode();
auto description = net::ErrorToShortString(code);
Emit("did-fail-provisional-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
// Do not emit "did-fail-load" for canceled requests.
if (code != net::ERR_ABORTED) {
EmitWarning(
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()),
"Failed to load URL: " + url.possibly_invalid_spec() +
" with error: " + description,
"electron");
Emit("did-fail-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
}
}
content::NavigationEntry* entry = navigation_handle->GetNavigationEntry();
// This check is needed due to an issue in Chromium
// Check the Chromium issue to keep updated:
// https://bugs.chromium.org/p/chromium/issues/detail?id=1178663
// If a history entry has been made and the forward/back call has been made,
// proceed with setting the new title
if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK))
WebContents::TitleWasSet(entry);
}
void WebContents::TitleWasSet(content::NavigationEntry* entry) {
std::u16string final_title;
bool explicit_set = true;
if (entry) {
auto title = entry->GetTitle();
auto url = entry->GetURL();
if (url.SchemeIsFile() && title.empty()) {
final_title = base::UTF8ToUTF16(url.ExtractFileName());
explicit_set = false;
} else {
final_title = title;
}
} else {
final_title = web_contents()->GetTitle();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnPageTitleUpdated(final_title, explicit_set);
Emit("page-title-updated", final_title, explicit_set);
}
void WebContents::DidUpdateFaviconURL(
content::RenderFrameHost* render_frame_host,
const std::vector<blink::mojom::FaviconURLPtr>& urls) {
std::set<GURL> unique_urls;
for (const auto& iter : urls) {
if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon)
continue;
const GURL& url = iter->icon_url;
if (url.is_valid())
unique_urls.insert(url);
}
Emit("page-favicon-updated", unique_urls);
}
void WebContents::DevToolsReloadPage() {
Emit("devtools-reload-page");
}
void WebContents::DevToolsFocused() {
Emit("devtools-focused");
}
void WebContents::DevToolsOpened() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
DCHECK(inspectable_web_contents_);
DCHECK(inspectable_web_contents_->GetDevToolsWebContents());
auto handle = FromOrCreate(
isolate, inspectable_web_contents_->GetDevToolsWebContents());
devtools_web_contents_.Reset(isolate, handle.ToV8());
// Set inspected tabID.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "setInspectedTabId", base::Value(ID()));
// Inherit owner window in devtools when it doesn't have one.
auto* devtools = inspectable_web_contents_->GetDevToolsWebContents();
bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey());
if (owner_window() && !has_window)
handle->SetOwnerWindow(devtools, owner_window());
Emit("devtools-opened");
}
void WebContents::DevToolsClosed() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
devtools_web_contents_.Reset();
Emit("devtools-closed");
}
void WebContents::DevToolsResized() {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnDevToolsResized();
}
void WebContents::SetOwnerWindow(NativeWindow* owner_window) {
SetOwnerWindow(GetWebContents(), owner_window);
}
void WebContents::SetOwnerWindow(content::WebContents* web_contents,
NativeWindow* owner_window) {
if (owner_window_) {
owner_window_->RemoveBackgroundThrottlingSource(this);
}
if (owner_window) {
owner_window_ = owner_window->GetWeakPtr();
NativeWindowRelay::CreateForWebContents(web_contents,
owner_window->GetWeakPtr());
owner_window_->AddBackgroundThrottlingSource(this);
} else {
owner_window_ = nullptr;
web_contents->RemoveUserData(NativeWindowRelay::UserDataKey());
}
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetNativeWindow(owner_window);
}
content::WebContents* WebContents::GetWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetWebContents();
}
content::WebContents* WebContents::GetDevToolsWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetDevToolsWebContents();
}
void WebContents::WebContentsDestroyed() {
// Clear the pointer stored in wrapper.
if (GetAllWebContents().Lookup(id_))
GetAllWebContents().Remove(id_);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
wrapper->SetAlignedPointerInInternalField(0, nullptr);
// Tell WebViewGuestDelegate that the WebContents has been destroyed.
if (guest_delegate_)
guest_delegate_->WillDestroy();
Observe(nullptr);
Emit("destroyed");
}
void WebContents::NavigationEntryCommitted(
const content::LoadCommittedDetails& details) {
Emit("navigation-entry-committed", details.entry->GetURL(),
details.is_same_document, details.did_replace_entry);
}
bool WebContents::GetBackgroundThrottling() const {
return background_throttling_;
}
void WebContents::SetBackgroundThrottling(bool allowed) {
background_throttling_ = allowed;
if (owner_window_) {
owner_window_->UpdateBackgroundThrottlingState();
}
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (!rfh)
return;
auto* rwhv = rfh->GetView();
if (!rwhv)
return;
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (!rwh_impl)
return;
rwh_impl->disable_hidden_ = !background_throttling_;
web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed);
if (rwh_impl->is_hidden()) {
rwh_impl->WasShown({});
}
}
int WebContents::GetProcessID() const {
return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
}
base::ProcessId WebContents::GetOSProcessID() const {
base::ProcessHandle process_handle = web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->GetProcess()
.Handle();
return base::GetProcId(process_handle);
}
WebContents::Type WebContents::GetType() const {
return type_;
}
bool WebContents::Equal(const WebContents* web_contents) const {
return ID() == web_contents->ID();
}
GURL WebContents::GetURL() const {
return web_contents()->GetLastCommittedURL();
}
void WebContents::LoadURL(const GURL& url,
const gin_helper::Dictionary& options) {
if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL),
net::ErrorToShortString(net::ERR_INVALID_URL),
url.possibly_invalid_spec(), true);
return;
}
content::NavigationController::LoadURLParams params(url);
if (!options.Get("httpReferrer", ¶ms.referrer)) {
GURL http_referrer;
if (options.Get("httpReferrer", &http_referrer))
params.referrer =
content::Referrer(http_referrer.GetAsReferrer(),
network::mojom::ReferrerPolicy::kDefault);
}
std::string user_agent;
if (options.Get("userAgent", &user_agent))
SetUserAgent(user_agent);
std::string extra_headers;
if (options.Get("extraHeaders", &extra_headers))
params.extra_headers = extra_headers;
scoped_refptr<network::ResourceRequestBody> body;
if (options.Get("postData", &body)) {
params.post_data = body;
params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
}
GURL base_url_for_data_url;
if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
params.base_url_for_data_url = base_url_for_data_url;
params.load_type = content::NavigationController::LOAD_TYPE_DATA;
}
bool reload_ignoring_cache = false;
if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) &&
reload_ignoring_cache) {
params.reload_type = content::ReloadType::BYPASSING_CACHE;
}
// Calling LoadURLWithParams() can trigger JS which destroys |this|.
auto weak_this = GetWeakPtr();
params.transition_type = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
// Discard non-committed entries to ensure that we don't re-use a pending
// entry
web_contents()->GetController().DiscardNonCommittedEntries();
web_contents()->GetController().LoadURLWithParams(params);
// β οΈWARNING!β οΈ
// LoadURLWithParams() triggers JS events which can call destroy() on |this|.
// It's not safe to assume that |this| points to valid memory at this point.
if (!weak_this || !web_contents())
return;
// Required to make beforeunload handler work.
NotifyUserActivation();
}
// TODO(MarshallOfSound): Figure out what we need to do with post data here, I
// believe the default behavior when we pass "true" is to phone out to the
// delegate and then the controller expects this method to be called again with
// "false" if the user approves the reload. For now this would result in
// ".reload()" calls on POST data domains failing silently. Passing false would
// result in them succeeding, but reposting which although more correct could be
// considering a breaking change.
void WebContents::Reload() {
web_contents()->GetController().Reload(content::ReloadType::NORMAL,
/* check_for_repost */ true);
}
void WebContents::ReloadIgnoringCache() {
web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE,
/* check_for_repost */ true);
}
void WebContents::DownloadURL(const GURL& url, gin::Arguments* args) {
std::map<std::string, std::string> headers;
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
if (options.Has("headers") && !options.Get("headers", &headers)) {
args->ThrowTypeError("Invalid value for headers - must be an object");
return;
}
}
std::unique_ptr<download::DownloadUrlParameters> download_params(
content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
web_contents(), url, MISSING_TRAFFIC_ANNOTATION));
for (const auto& [name, value] : headers) {
download_params->add_request_header(name, value);
}
auto* download_manager =
web_contents()->GetBrowserContext()->GetDownloadManager();
download_manager->DownloadUrl(std::move(download_params));
}
std::u16string WebContents::GetTitle() const {
return web_contents()->GetTitle();
}
bool WebContents::IsLoading() const {
return web_contents()->IsLoading();
}
bool WebContents::IsLoadingMainFrame() const {
return web_contents()->ShouldShowLoadingUI();
}
bool WebContents::IsWaitingForResponse() const {
return web_contents()->IsWaitingForResponse();
}
void WebContents::Stop() {
web_contents()->Stop();
}
bool WebContents::CanGoBack() const {
return web_contents()->GetController().CanGoBack();
}
void WebContents::GoBack() {
if (CanGoBack())
web_contents()->GetController().GoBack();
}
bool WebContents::CanGoForward() const {
return web_contents()->GetController().CanGoForward();
}
void WebContents::GoForward() {
if (CanGoForward())
web_contents()->GetController().GoForward();
}
bool WebContents::CanGoToOffset(int offset) const {
return web_contents()->GetController().CanGoToOffset(offset);
}
void WebContents::GoToOffset(int offset) {
if (CanGoToOffset(offset))
web_contents()->GetController().GoToOffset(offset);
}
bool WebContents::CanGoToIndex(int index) const {
return index >= 0 && index < GetHistoryLength();
}
void WebContents::GoToIndex(int index) {
if (CanGoToIndex(index))
web_contents()->GetController().GoToIndex(index);
}
int WebContents::GetActiveIndex() const {
return web_contents()->GetController().GetCurrentEntryIndex();
}
void WebContents::ClearHistory() {
// In some rare cases (normally while there is no real history) we are in a
// state where we can't prune navigation entries
if (web_contents()->GetController().CanPruneAllButLastCommitted()) {
web_contents()->GetController().PruneAllButLastCommitted();
}
}
int WebContents::GetHistoryLength() const {
return web_contents()->GetController().GetEntryCount();
}
const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy;
}
void WebContents::SetWebRTCIPHandlingPolicy(
const std::string& webrtc_ip_handling_policy) {
if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
return;
web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
webrtc_ip_handling_policy;
web_contents()->SyncRendererPrefs();
}
v8::Local<v8::Value> WebContents::GetWebRTCUDPPortRange(
v8::Isolate* isolate) const {
auto* prefs = web_contents()->GetMutableRendererPrefs();
auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
dict.Set("min", static_cast<uint32_t>(prefs->webrtc_udp_min_port));
dict.Set("max", static_cast<uint32_t>(prefs->webrtc_udp_max_port));
return dict.GetHandle();
}
void WebContents::SetWebRTCUDPPortRange(gin::Arguments* args) {
uint32_t min = 0, max = 0;
gin_helper::Dictionary range;
if (!args->GetNext(&range) || !range.Get("min", &min) ||
!range.Get("max", &max)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'min' and 'max' are both required");
return;
}
if ((0 == min && 0 != max) || max > UINT16_MAX) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError(
"'min' and 'max' must be in the (0, 65535] range or [0, 0]");
return;
}
if (min > max) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'max' must be greater than or equal to 'min'");
return;
}
auto* prefs = web_contents()->GetMutableRendererPrefs();
if (prefs->webrtc_udp_min_port == static_cast<uint16_t>(min) &&
prefs->webrtc_udp_max_port == static_cast<uint16_t>(max)) {
return;
}
prefs->webrtc_udp_min_port = min;
prefs->webrtc_udp_max_port = max;
web_contents()->SyncRendererPrefs();
}
std::string WebContents::GetMediaSourceID(
content::WebContents* request_web_contents) {
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host)
return std::string();
content::DesktopMediaID media_id(
content::DesktopMediaID::TYPE_WEB_CONTENTS,
content::DesktopMediaID::kNullId,
content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(),
frame_host->GetRoutingID()));
auto* request_frame_host = request_web_contents->GetPrimaryMainFrame();
if (!request_frame_host)
return std::string();
std::string id =
content::DesktopStreamsRegistry::GetInstance()->RegisterStream(
request_frame_host->GetProcess()->GetID(),
request_frame_host->GetRoutingID(),
url::Origin::Create(request_frame_host->GetLastCommittedURL()
.DeprecatedGetOriginAsURL()),
media_id, content::kRegistryStreamTypeTab);
return id;
}
bool WebContents::IsCrashed() const {
return web_contents()->IsCrashed();
}
void WebContents::ForcefullyCrashRenderer() {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
if (!rwh)
return;
content::RenderProcessHost* rph = rwh->GetProcess();
if (rph) {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// A generic |CrashDumpHungChildProcess()| is not implemented for Linux.
// Instead we send an explicit IPC to crash on the renderer's IO thread.
rph->ForceCrash();
#else
// Try to generate a crash report for the hung process.
#if !IS_MAS_BUILD()
CrashDumpHungChildProcess(rph->GetProcess().Handle());
#endif
rph->Shutdown(content::RESULT_CODE_HUNG);
#endif
}
}
void WebContents::SetUserAgent(const std::string& user_agent) {
blink::UserAgentOverride ua_override;
ua_override.ua_string_override = user_agent;
if (!user_agent.empty())
ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata();
web_contents()->SetUserAgentOverride(ua_override, false);
}
std::string WebContents::GetUserAgent() {
return web_contents()->GetUserAgentOverride().ua_string_override;
}
v8::Local<v8::Promise> WebContents::SavePage(
const base::FilePath& full_file_path,
const content::SavePageType& save_type) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!full_file_path.IsAbsolute()) {
promise.RejectWithErrorMessage("Path must be absolute");
return handle;
}
auto* handler = new SavePageHandler(web_contents(), std::move(promise));
handler->Handle(full_file_path, save_type);
return handle;
}
void WebContents::OpenDevTools(gin::Arguments* args) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
std::string state;
if (type_ == Type::kWebView || type_ == Type::kBackgroundPage ||
!owner_window()) {
state = "detach";
}
bool activate = true;
std::string title;
if (args && args->Length() == 1) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("mode", &state);
options.Get("activate", &activate);
options.Get("title", &title);
}
}
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->SetDockState(state);
inspectable_web_contents_->SetDevToolsTitle(base::UTF8ToUTF16(title));
inspectable_web_contents_->ShowDevTools(activate);
}
void WebContents::CloseDevTools() {
if (type_ == Type::kRemote)
return;
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->CloseDevTools();
}
bool WebContents::IsDevToolsOpened() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->IsDevToolsViewShowing();
}
std::u16string WebContents::GetDevToolsTitle() {
if (type_ == Type::kRemote)
return std::u16string();
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->GetDevToolsTitle();
}
void WebContents::SetDevToolsTitle(const std::u16string& title) {
inspectable_web_contents_->SetDevToolsTitle(title);
}
bool WebContents::IsDevToolsFocused() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->GetView()->IsDevToolsViewFocused();
}
void WebContents::EnableDeviceEmulation(
const blink::DeviceEmulationParams& params) {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->EnableDeviceEmulation(params);
}
}
}
void WebContents::DisableDeviceEmulation() {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->DisableDeviceEmulation();
}
}
}
void WebContents::ToggleDevTools() {
if (IsDevToolsOpened())
CloseDevTools();
else
OpenDevTools(nullptr);
}
void WebContents::InspectElement(int x, int y) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
DCHECK(inspectable_web_contents_);
if (!inspectable_web_contents_->GetDevToolsWebContents())
OpenDevTools(nullptr);
inspectable_web_contents_->InspectElement(x, y);
}
void WebContents::InspectSharedWorkerById(const std::string& workerId) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
if (agent_host->GetId() == workerId) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
}
std::vector<scoped_refptr<content::DevToolsAgentHost>>
WebContents::GetAllSharedWorkers() {
std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers;
if (type_ == Type::kRemote)
return shared_workers;
if (!enable_devtools_)
return shared_workers;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
shared_workers.push_back(agent_host);
}
}
return shared_workers;
}
void WebContents::InspectSharedWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::InspectServiceWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeServiceWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::SetIgnoreMenuShortcuts(bool ignore) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
DCHECK(web_preferences);
web_preferences->SetIgnoreMenuShortcuts(ignore);
}
void WebContents::SetAudioMuted(bool muted) {
web_contents()->SetAudioMuted(muted);
}
bool WebContents::IsAudioMuted() {
return web_contents()->IsAudioMuted();
}
bool WebContents::IsCurrentlyAudible() {
return web_contents()->IsCurrentlyAudible();
}
#if BUILDFLAG(ENABLE_PRINTING)
void WebContents::OnGetDeviceNameToUse(
base::Value::Dict print_settings,
printing::CompletionCallback print_callback,
bool silent,
// <error, device_name>
std::pair<std::string, std::u16string> info) {
// The content::WebContents might be already deleted at this point, and the
// PrintViewManagerElectron class does not do null check.
if (!web_contents()) {
if (print_callback)
std::move(print_callback).Run(false, "failed");
return;
}
if (!info.first.empty()) {
if (print_callback)
std::move(print_callback).Run(false, info.first);
return;
}
// If the user has passed a deviceName use it, otherwise use default printer.
print_settings.Set(printing::kSettingDeviceName, info.second);
auto* print_view_manager =
PrintViewManagerElectron::FromWebContents(web_contents());
if (!print_view_manager)
return;
auto* focused_frame = web_contents()->GetFocusedFrame();
auto* rfh = focused_frame && focused_frame->HasSelection()
? focused_frame
: web_contents()->GetPrimaryMainFrame();
print_view_manager->PrintNow(rfh, silent, std::move(print_settings),
std::move(print_callback));
}
void WebContents::Print(gin::Arguments* args) {
auto options = gin_helper::Dictionary::CreateEmpty(args->isolate());
base::Value::Dict settings;
if (args->Length() >= 1 && !args->GetNext(&options)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid print settings specified.");
return;
}
printing::CompletionCallback callback;
if (args->Length() == 2 && !args->GetNext(&callback)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid optional callback provided.");
return;
}
// Set optional silent printing
bool silent = false;
options.Get("silent", &silent);
bool print_background = false;
options.Get("printBackground", &print_background);
settings.Set(printing::kSettingShouldPrintBackgrounds, print_background);
// Set custom margin settings
auto margins = gin_helper::Dictionary::CreateEmpty(args->isolate());
if (options.Get("margins", &margins)) {
printing::mojom::MarginType margin_type =
printing::mojom::MarginType::kDefaultMargins;
margins.Get("marginType", &margin_type);
settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type));
if (margin_type == printing::mojom::MarginType::kCustomMargins) {
base::Value::Dict custom_margins;
int top = 0;
margins.Get("top", &top);
custom_margins.Set(printing::kSettingMarginTop, top);
int bottom = 0;
margins.Get("bottom", &bottom);
custom_margins.Set(printing::kSettingMarginBottom, bottom);
int left = 0;
margins.Get("left", &left);
custom_margins.Set(printing::kSettingMarginLeft, left);
int right = 0;
margins.Get("right", &right);
custom_margins.Set(printing::kSettingMarginRight, right);
settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins));
}
} else {
settings.Set(
printing::kSettingMarginsType,
static_cast<int>(printing::mojom::MarginType::kDefaultMargins));
}
// Set whether to print color or greyscale
bool print_color = true;
options.Get("color", &print_color);
auto const color_model = print_color ? printing::mojom::ColorModel::kColor
: printing::mojom::ColorModel::kGray;
settings.Set(printing::kSettingColor, static_cast<int>(color_model));
// Is the orientation landscape or portrait.
bool landscape = false;
options.Get("landscape", &landscape);
settings.Set(printing::kSettingLandscape, landscape);
// We set the default to the system's default printer and only update
// if at the Chromium level if the user overrides.
// Printer device name as opened by the OS.
std::u16string device_name;
options.Get("deviceName", &device_name);
int scale_factor = 100;
options.Get("scaleFactor", &scale_factor);
settings.Set(printing::kSettingScaleFactor, scale_factor);
int pages_per_sheet = 1;
options.Get("pagesPerSheet", &pages_per_sheet);
settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet);
// True if the user wants to print with collate.
bool collate = true;
options.Get("collate", &collate);
settings.Set(printing::kSettingCollate, collate);
// The number of individual copies to print
int copies = 1;
options.Get("copies", &copies);
settings.Set(printing::kSettingCopies, copies);
// Strings to be printed as headers and footers if requested by the user.
std::string header;
options.Get("header", &header);
std::string footer;
options.Get("footer", &footer);
if (!(header.empty() && footer.empty())) {
settings.Set(printing::kSettingHeaderFooterEnabled, true);
settings.Set(printing::kSettingHeaderFooterTitle, header);
settings.Set(printing::kSettingHeaderFooterURL, footer);
} else {
settings.Set(printing::kSettingHeaderFooterEnabled, false);
}
// We don't want to allow the user to enable these settings
// but we need to set them or a CHECK is hit.
settings.Set(printing::kSettingPrinterType,
static_cast<int>(printing::mojom::PrinterType::kLocal));
settings.Set(printing::kSettingShouldPrintSelectionOnly, false);
settings.Set(printing::kSettingRasterizePdf, false);
// Set custom page ranges to print
std::vector<gin_helper::Dictionary> page_ranges;
if (options.Get("pageRanges", &page_ranges)) {
base::Value::List page_range_list;
for (auto& range : page_ranges) {
int from, to;
if (range.Get("from", &from) && range.Get("to", &to)) {
base::Value::Dict range_dict;
// Chromium uses 1-based page ranges, so increment each by 1.
range_dict.Set(printing::kSettingPageRangeFrom, from + 1);
range_dict.Set(printing::kSettingPageRangeTo, to + 1);
page_range_list.Append(std::move(range_dict));
} else {
continue;
}
}
if (!page_range_list.empty())
settings.Set(printing::kSettingPageRange, std::move(page_range_list));
}
// Duplex type user wants to use.
printing::mojom::DuplexMode duplex_mode =
printing::mojom::DuplexMode::kSimplex;
options.Get("duplexMode", &duplex_mode);
settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode));
// We've already done necessary parameter sanitization at the
// JS level, so we can simply pass this through.
base::Value media_size(base::Value::Type::DICT);
if (options.Get("mediaSize", &media_size))
settings.Set(printing::kSettingMediaSize, std::move(media_size));
// Set custom dots per inch (dpi)
gin_helper::Dictionary dpi_settings;
int dpi = 72;
if (options.Get("dpi", &dpi_settings)) {
int horizontal = 72;
dpi_settings.Get("horizontal", &horizontal);
settings.Set(printing::kSettingDpiHorizontal, horizontal);
int vertical = 72;
dpi_settings.Get("vertical", &vertical);
settings.Set(printing::kSettingDpiVertical, vertical);
} else {
settings.Set(printing::kSettingDpiHorizontal, dpi);
settings.Set(printing::kSettingDpiVertical, dpi);
}
print_task_runner_->PostTaskAndReplyWithResult(
FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name),
base::BindOnce(&WebContents::OnGetDeviceNameToUse,
weak_factory_.GetWeakPtr(), std::move(settings),
std::move(callback), silent));
}
// Partially duplicated and modified from
// headless/lib/browser/protocol/page_handler.cc;l=41
v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
// This allows us to track headless printing calls.
auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID);
auto landscape = settings.GetDict().FindBool("landscape");
auto display_header_footer =
settings.GetDict().FindBool("displayHeaderFooter");
auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds");
auto scale = settings.GetDict().FindDouble("scale");
auto paper_width = settings.GetDict().FindDouble("paperWidth");
auto paper_height = settings.GetDict().FindDouble("paperHeight");
auto margin_top = settings.GetDict().FindDouble("marginTop");
auto margin_bottom = settings.GetDict().FindDouble("marginBottom");
auto margin_left = settings.GetDict().FindDouble("marginLeft");
auto margin_right = settings.GetDict().FindDouble("marginRight");
auto page_ranges = *settings.GetDict().FindString("pageRanges");
auto header_template = *settings.GetDict().FindString("headerTemplate");
auto footer_template = *settings.GetDict().FindString("footerTemplate");
auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize");
auto generate_tagged_pdf =
settings.GetDict().FindBool("shouldGenerateTaggedPDF");
absl::variant<printing::mojom::PrintPagesParamsPtr, std::string>
print_pages_params = print_to_pdf::GetPrintPagesParams(
web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(),
landscape, display_header_footer, print_background, scale,
paper_width, paper_height, margin_top, margin_bottom, margin_left,
margin_right, absl::make_optional(header_template),
absl::make_optional(footer_template), prefer_css_page_size,
generate_tagged_pdf);
if (absl::holds_alternative<std::string>(print_pages_params)) {
auto error = absl::get<std::string>(print_pages_params);
promise.RejectWithErrorMessage("Invalid print parameters: " + error);
return handle;
}
auto* manager = PrintViewManagerElectron::FromWebContents(web_contents());
if (!manager) {
promise.RejectWithErrorMessage("Failed to find print manager");
return handle;
}
auto params = std::move(
absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params));
params->params->document_cookie = unique_id.value_or(0);
manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges,
std::move(params),
base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(),
std::move(promise)));
return handle;
}
void WebContents::OnPDFCreated(
gin_helper::Promise<v8::Local<v8::Value>> promise,
print_to_pdf::PdfPrintResult print_result,
scoped_refptr<base::RefCountedMemory> data) {
if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) {
promise.RejectWithErrorMessage(
"Failed to generate PDF: " +
print_to_pdf::PdfPrintResultToString(print_result));
return;
}
v8::Isolate* isolate = promise.isolate();
gin_helper::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate, promise.GetContext()));
v8::Local<v8::Value> buffer =
node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()),
data->size())
.ToLocalChecked();
promise.Resolve(buffer);
}
#endif
void WebContents::AddWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsAddFileSystem(std::string(), path);
}
void WebContents::RemoveWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsRemoveFileSystem(path);
}
void WebContents::Undo() {
web_contents()->Undo();
}
void WebContents::Redo() {
web_contents()->Redo();
}
void WebContents::Cut() {
web_contents()->Cut();
}
void WebContents::Copy() {
web_contents()->Copy();
}
void WebContents::CenterSelection() {
web_contents()->CenterSelection();
}
void WebContents::Paste() {
web_contents()->Paste();
}
void WebContents::PasteAndMatchStyle() {
web_contents()->PasteAndMatchStyle();
}
void WebContents::Delete() {
web_contents()->Delete();
}
void WebContents::SelectAll() {
web_contents()->SelectAll();
}
void WebContents::Unselect() {
web_contents()->CollapseSelection();
}
void WebContents::ScrollToTopOfDocument() {
web_contents()->ScrollToTopOfDocument();
}
void WebContents::ScrollToBottomOfDocument() {
web_contents()->ScrollToBottomOfDocument();
}
void WebContents::AdjustSelectionByCharacterOffset(gin::Arguments* args) {
int start_adjust = 0;
int end_adjust = 0;
gin_helper::Dictionary dict;
if (args->GetNext(&dict)) {
dict.Get("start", &start_adjust);
dict.Get("matchCase", &end_adjust);
}
// The selection menu is a Chrome-specific piece of UI.
// TODO(codebytere): maybe surface as an event in the future?
web_contents()->AdjustSelectionByCharacterOffset(
start_adjust, end_adjust, false /* show_selection_menu */);
}
void WebContents::Replace(const std::u16string& word) {
web_contents()->Replace(word);
}
void WebContents::ReplaceMisspelling(const std::u16string& word) {
web_contents()->ReplaceMisspelling(word);
}
uint32_t WebContents::FindInPage(gin::Arguments* args) {
std::u16string search_text;
if (!args->GetNext(&search_text) || search_text.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must provide a non-empty search content");
return 0;
}
uint32_t request_id = ++find_in_page_request_id_;
gin_helper::Dictionary dict;
auto options = blink::mojom::FindOptions::New();
if (args->GetNext(&dict)) {
dict.Get("forward", &options->forward);
dict.Get("matchCase", &options->match_case);
dict.Get("findNext", &options->new_session);
}
web_contents()->Find(request_id, search_text, std::move(options));
return request_id;
}
void WebContents::StopFindInPage(content::StopFindAction action) {
web_contents()->StopFinding(action);
}
void WebContents::ShowDefinitionForSelection() {
#if BUILDFLAG(IS_MAC)
auto* const view = web_contents()->GetRenderWidgetHostView();
if (view)
view->ShowDefinitionForSelection();
#endif
}
void WebContents::CopyImageAt(int x, int y) {
auto* const host = web_contents()->GetPrimaryMainFrame();
if (host)
host->CopyImageAt(x, y);
}
void WebContents::Focus() {
// Focusing on WebContents does not automatically focus the window on macOS
// and Linux, do it manually to match the behavior on Windows.
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
if (owner_window())
owner_window()->Focus(true);
#endif
web_contents()->Focus();
}
#if !BUILDFLAG(IS_MAC)
bool WebContents::IsFocused() const {
auto* view = web_contents()->GetRenderWidgetHostView();
if (!view)
return false;
if (GetType() != Type::kBackgroundPage) {
auto* window = web_contents()->GetNativeView()->GetToplevelWindow();
if (window && !window->IsVisible())
return false;
}
return view->HasFocus();
}
#endif
void WebContents::SendInputEvent(v8::Isolate* isolate,
v8::Local<v8::Value> input_event) {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
blink::WebInputEvent::Type type =
gin::GetWebInputEventType(isolate, input_event);
if (blink::WebInputEvent::IsMouseEventType(type)) {
blink::WebMouseEvent mouse_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) {
if (IsOffScreen()) {
GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event);
} else {
rwh->ForwardMouseEvent(mouse_event);
}
return;
}
} else if (blink::WebInputEvent::IsKeyboardEventType(type)) {
content::NativeWebKeyboardEvent keyboard_event(
blink::WebKeyboardEvent::Type::kRawKeyDown,
blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow());
if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) {
// For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`.
if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown)
keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown);
rwh->ForwardKeyboardEvent(keyboard_event);
return;
}
} else if (type == blink::WebInputEvent::Type::kMouseWheel) {
blink::WebMouseWheelEvent mouse_wheel_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
if (IsOffScreen()) {
GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent(
mouse_wheel_event);
} else {
// Chromium expects phase info in wheel events (and applies a
// DCHECK to verify it). See: https://crbug.com/756524.
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
// Send a synthetic wheel event with phaseEnded to finish scrolling.
mouse_wheel_event.has_synthetic_phase = true;
mouse_wheel_event.delta_x = 0;
mouse_wheel_event.delta_y = 0;
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kEventNonBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
}
return;
}
}
isolate->ThrowException(
v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object")));
}
void WebContents::BeginFrameSubscription(gin::Arguments* args) {
bool only_dirty = false;
FrameSubscriber::FrameCaptureCallback callback;
if (args->Length() > 1) {
if (!args->GetNext(&only_dirty)) {
args->ThrowError();
return;
}
}
if (!args->GetNext(&callback)) {
args->ThrowError();
return;
}
frame_subscriber_ =
std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty);
}
void WebContents::EndFrameSubscription() {
frame_subscriber_.reset();
}
void WebContents::StartDrag(const gin_helper::Dictionary& item,
gin::Arguments* args) {
base::FilePath file;
std::vector<base::FilePath> files;
if (!item.Get("files", &files) && item.Get("file", &file)) {
files.push_back(file);
}
v8::Local<v8::Value> icon_value;
if (!item.Get("icon", &icon_value)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'icon' parameter is required");
return;
}
NativeImage* icon = nullptr;
if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) ||
icon->image().IsEmpty()) {
return;
}
// Start dragging.
if (!files.empty()) {
base::CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop allow;
DragFileItems(files, icon->image(), web_contents()->GetNativeView());
} else {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must specify either 'file' or 'files' option");
}
}
v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) {
gin_helper::Promise<gfx::Image> promise(args->isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
gfx::Rect rect;
args->GetNext(&rect);
bool stay_hidden = false;
bool stay_awake = false;
if (args && args->Length() == 2) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("stayHidden", &stay_hidden);
options.Get("stayAwake", &stay_awake);
}
}
auto* const view = web_contents()->GetRenderWidgetHostView();
if (!view) {
promise.Resolve(gfx::Image());
return handle;
}
#if !BUILDFLAG(IS_MAC)
// If the view's renderer is suspended this may fail on Windows/Linux -
// bail if so. See CopyFromSurface in
// content/public/browser/render_widget_host_view.h.
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (rfh &&
rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) {
promise.Resolve(gfx::Image());
return handle;
}
#endif // BUILDFLAG(IS_MAC)
auto capture_handle = web_contents()->IncrementCapturerCount(
rect.size(), stay_hidden, stay_awake);
// Capture full page if user doesn't specify a |rect|.
const gfx::Size view_size =
rect.IsEmpty() ? view->GetViewBounds().size() : rect.size();
// By default, the requested bitmap size is the view size in screen
// coordinates. However, if there's more pixel detail available on the
// current system, increase the requested bitmap size to capture it all.
gfx::Size bitmap_size = view_size;
const gfx::NativeView native_view = view->GetNativeView();
const float scale = display::Screen::GetScreen()
->GetDisplayNearestView(native_view)
.device_scale_factor();
if (scale > 1.0f)
bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size,
base::BindOnce(&OnCapturePageDone, std::move(promise),
std::move(capture_handle)));
return handle;
}
bool WebContents::IsBeingCaptured() {
return web_contents()->IsBeingCaptured();
}
void WebContents::OnCursorChanged(const ui::Cursor& cursor) {
if (cursor.type() == ui::mojom::CursorType::kCustom) {
Emit("cursor-changed", CursorTypeToString(cursor.type()),
gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()),
cursor.image_scale_factor(),
gfx::Size(cursor.custom_bitmap().width(),
cursor.custom_bitmap().height()),
cursor.custom_hotspot());
} else {
Emit("cursor-changed", CursorTypeToString(cursor.type()));
}
}
bool WebContents::IsGuest() const {
return type_ == Type::kWebView;
}
void WebContents::AttachToIframe(content::WebContents* embedder_web_contents,
int embedder_frame_id) {
attached_ = true;
if (guest_delegate_)
guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id);
}
bool WebContents::IsOffScreen() const {
return type_ == Type::kOffScreen;
}
void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap));
}
void WebContents::StartPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(true);
}
void WebContents::StopPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(false);
}
bool WebContents::IsPainting() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv && osr_wcv->IsPainting();
}
void WebContents::SetFrameRate(int frame_rate) {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetFrameRate(frame_rate);
}
int WebContents::GetFrameRate() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv ? osr_wcv->GetFrameRate() : 0;
}
void WebContents::Invalidate() {
if (IsOffScreen()) {
auto* osr_rwhv = GetOffScreenRenderWidgetHostView();
if (osr_rwhv)
osr_rwhv->Invalidate();
} else {
auto* const window = owner_window();
if (window)
window->Invalidate();
}
}
gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) {
if (IsOffScreen() && wc == web_contents()) {
auto* relay = NativeWindowRelay::FromWebContents(web_contents());
if (relay) {
auto* owner_window = relay->GetNativeWindow();
return owner_window ? owner_window->GetSize() : gfx::Size();
}
}
return gfx::Size();
}
void WebContents::SetZoomLevel(double level) {
zoom_controller_->SetZoomLevel(level);
}
double WebContents::GetZoomLevel() const {
return zoom_controller_->GetZoomLevel();
}
void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower,
double factor) {
if (factor < std::numeric_limits<double>::epsilon()) {
thrower.ThrowError("'zoomFactor' must be a double greater than 0.0");
return;
}
auto level = blink::PageZoomFactorToZoomLevel(factor);
SetZoomLevel(level);
}
double WebContents::GetZoomFactor() const {
auto level = GetZoomLevel();
return blink::PageZoomLevelToZoomFactor(level);
}
void WebContents::SetTemporaryZoomLevel(double level) {
zoom_controller_->SetTemporaryZoomLevel(level);
}
void WebContents::DoGetZoomLevel(
electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback
callback) {
std::move(callback).Run(GetZoomLevel());
}
std::vector<base::FilePath> WebContents::GetPreloadPaths() const {
auto result = SessionPreferences::GetValidPreloads(GetBrowserContext());
if (auto* web_preferences = WebContentsPreferences::From(web_contents())) {
base::FilePath preload;
if (web_preferences->GetPreloadPath(&preload)) {
result.emplace_back(preload);
}
}
return result;
}
v8::Local<v8::Value> WebContents::GetLastWebPreferences(
v8::Isolate* isolate) const {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (!web_preferences)
return v8::Null(isolate);
return gin::ConvertToV8(isolate, *web_preferences->last_preference());
}
v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow(
v8::Isolate* isolate) const {
if (owner_window())
return BrowserWindow::From(isolate, owner_window());
else
return v8::Null(isolate);
}
v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
return v8::Local<v8::Value>::New(isolate, session_);
}
content::WebContents* WebContents::HostWebContents() const {
if (!embedder_)
return nullptr;
return embedder_->web_contents();
}
void WebContents::SetEmbedder(const WebContents* embedder) {
if (embedder) {
NativeWindow* owner_window = nullptr;
auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
if (relay) {
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
content::RenderWidgetHostView* rwhv =
web_contents()->GetRenderWidgetHostView();
if (rwhv) {
rwhv->Hide();
rwhv->Show();
}
}
}
void WebContents::SetDevToolsWebContents(const WebContents* devtools) {
if (inspectable_web_contents_)
inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents());
}
v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const {
gfx::NativeView ptr = web_contents()->GetNativeView();
auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr),
sizeof(gfx::NativeView));
if (buffer.IsEmpty())
return v8::Null(isolate);
else
return buffer.ToLocalChecked();
}
v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
if (devtools_web_contents_.IsEmpty())
return v8::Null(isolate);
else
return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
}
v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
if (debugger_.IsEmpty()) {
auto handle = electron::api::Debugger::Create(isolate, web_contents());
debugger_.Reset(isolate, handle.ToV8());
}
return v8::Local<v8::Value>::New(isolate, debugger_);
}
content::RenderFrameHost* WebContents::MainFrame() {
return web_contents()->GetPrimaryMainFrame();
}
content::RenderFrameHost* WebContents::Opener() {
return web_contents()->GetOpener();
}
void WebContents::NotifyUserActivation() {
content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame();
if (frame)
frame->NotifyUserActivation(
blink::mojom::UserActivationNotificationType::kInteraction);
}
void WebContents::SetImageAnimationPolicy(const std::string& new_policy) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
web_preferences->SetImageAnimationPolicy(new_policy);
web_contents()->OnWebPreferencesChanged();
}
void WebContents::OnInputEvent(const blink::WebInputEvent& event) {
Emit("input-event", event);
}
v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage("Failed to create memory dump");
return handle;
}
auto pid = frame_host->GetProcess()->GetProcess().Pid();
v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext());
memory_instrumentation::MemoryInstrumentation::GetInstance()
->RequestGlobalDumpForPid(
pid, std::vector<std::string>(),
base::BindOnce(&ElectronBindings::DidReceiveMemoryDump,
std::move(context), std::move(promise), pid));
return handle;
}
v8::Local<v8::Promise> WebContents::TakeHeapSnapshot(
v8::Isolate* isolate,
const base::FilePath& file_path) {
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
ScopedAllowBlockingForElectron allow_blocking;
uint32_t flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE;
// The snapshot file is passed to an untrusted process.
flags = base::File::AddFlagsForPassingToUntrustedProcess(flags);
base::File file(file_path, flags);
if (!file.IsValid()) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with invalid file path " +
#if BUILDFLAG(IS_WIN)
base::WideToUTF8(file_path.value()));
#else
file_path.value());
#endif
return handle;
}
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with invalid webContents main frame");
return handle;
}
if (!frame_host->IsRenderFrameLive()) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with nonexistent render frame");
return handle;
}
// This dance with `base::Owned` is to ensure that the interface stays alive
// until the callback is called. Otherwise it would be closed at the end of
// this function.
auto electron_renderer =
std::make_unique<mojo::Remote<mojom::ElectronRenderer>>();
frame_host->GetRemoteInterfaces()->GetInterface(
electron_renderer->BindNewPipeAndPassReceiver());
auto* raw_ptr = electron_renderer.get();
(*raw_ptr)->TakeHeapSnapshot(
mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())),
base::BindOnce(
[](mojo::Remote<mojom::ElectronRenderer>* ep,
gin_helper::Promise<void> promise, bool success) {
if (success) {
promise.Resolve();
} else {
promise.RejectWithErrorMessage("Failed to take heap snapshot");
}
},
base::Owned(std::move(electron_renderer)), std::move(promise)));
return handle;
}
void WebContents::UpdatePreferredSize(content::WebContents* web_contents,
const gfx::Size& pref_size) {
Emit("preferred-size-changed", pref_size);
}
bool WebContents::CanOverscrollContent() {
return false;
}
std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper(
content::RenderFrameHost* frame,
content::EyeDropperListener* listener) {
return ShowEyeDropper(frame, listener);
}
void WebContents::RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) {
FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener),
params);
}
void WebContents::EnumerateDirectory(
content::WebContents* web_contents,
scoped_refptr<content::FileSelectListener> listener,
const base::FilePath& path) {
FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path);
}
bool WebContents::IsFullscreenForTabOrPending(
const content::WebContents* source) {
if (!owner_window())
return is_html_fullscreen();
bool in_transition = owner_window()->fullscreen_transition_state() !=
NativeWindow::FullScreenTransitionState::kNone;
bool is_html_transition = owner_window()->fullscreen_transition_type() ==
NativeWindow::FullScreenTransitionType::kHTML;
return is_html_fullscreen() || (in_transition && is_html_transition);
}
content::FullscreenState WebContents::GetFullscreenState(
const content::WebContents* source) const {
// `const_cast` here because EAM does not have const getters
return const_cast<ExclusiveAccessManager*>(&exclusive_access_manager_)
->fullscreen_controller()
->GetFullscreenState(source);
}
bool WebContents::TakeFocus(content::WebContents* source, bool reverse) {
if (source && source->GetOutermostWebContents() == source) {
// If this is the outermost web contents and the user has tabbed or
// shift + tabbed through all the elements, reset the focus back to
// the first or last element so that it doesn't stay in the body.
source->FocusThroughTabTraversal(reverse);
return true;
}
return false;
}
content::PictureInPictureResult WebContents::EnterPictureInPicture(
content::WebContents* web_contents) {
return PictureInPictureWindowManager::GetInstance()
->EnterVideoPictureInPicture(web_contents);
}
void WebContents::ExitPictureInPicture() {
PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture();
}
void WebContents::DevToolsSaveToFile(const std::string& url,
const std::string& content,
bool save_as) {
base::FilePath path;
auto it = saved_files_.find(url);
if (it != saved_files_.end() && !save_as) {
path = it->second;
} else {
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.title = url;
settings.default_path = base::FilePath::FromUTF8Unsafe(url);
if (!file_dialog::ShowSaveDialogSync(settings, &path)) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "canceledSaveURL", base::Value(url));
return;
}
}
saved_files_[url] = path;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "savedURL", base::Value(url),
base::Value(path.AsUTF8Unsafe()));
file_task_runner_->PostTask(FROM_HERE,
base::BindOnce(&WriteToFile, path, content));
}
void WebContents::DevToolsAppendToFile(const std::string& url,
const std::string& content) {
auto it = saved_files_.find(url);
if (it == saved_files_.end())
return;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL",
base::Value(url));
file_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&AppendToFile, it->second, content));
}
void WebContents::DevToolsRequestFileSystems() {
auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents());
if (file_system_paths.empty()) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List()));
return;
}
std::vector<FileSystem> file_systems;
for (const auto& file_system_path : file_system_paths) {
base::FilePath path =
base::FilePath::FromUTF8Unsafe(file_system_path.first);
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
FileSystem file_system =
CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id,
file_system_path.first, file_system_path.second);
file_systems.push_back(file_system);
}
base::Value::List file_system_value;
for (const auto& file_system : file_systems)
file_system_value.Append(CreateFileSystemValue(file_system));
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded",
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsAddFileSystem(
const std::string& type,
const base::FilePath& file_system_path) {
base::FilePath path = file_system_path;
if (path.empty()) {
std::vector<base::FilePath> paths;
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY;
if (!file_dialog::ShowOpenDialogSync(settings, &paths))
return;
path = paths[0];
}
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe()))
return;
FileSystem file_system = CreateFileSystemStruct(
GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type);
base::Value::Dict file_system_value = CreateFileSystemValue(file_system);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Set(path.AsUTF8Unsafe(), type);
std::string error = ""; // No error
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemAdded", base::Value(error),
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsRemoveFileSystem(
const base::FilePath& file_system_path) {
if (!inspectable_web_contents_)
return;
std::string path = file_system_path.AsUTF8Unsafe();
storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath(
file_system_path);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Remove(path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemRemoved", base::Value(path));
}
void WebContents::DevToolsIndexPath(
int request_id,
const std::string& file_system_path,
const std::string& excluded_folders_message) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsIndexingDone(request_id, file_system_path);
return;
}
if (devtools_indexing_jobs_.count(request_id) != 0)
return;
std::vector<std::string> excluded_folders;
absl::optional<base::Value> parsed_excluded_folders =
base::JSONReader::Read(excluded_folders_message);
if (parsed_excluded_folders && parsed_excluded_folders->is_list()) {
for (const base::Value& folder_path : parsed_excluded_folders->GetList()) {
if (folder_path.is_string())
excluded_folders.push_back(folder_path.GetString());
}
}
devtools_indexing_jobs_[request_id] =
scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>(
devtools_file_system_indexer_->IndexPath(
file_system_path, excluded_folders,
base::BindRepeating(
&WebContents::OnDevToolsIndexingWorkCalculated,
weak_factory_.GetWeakPtr(), request_id, file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingWorked,
weak_factory_.GetWeakPtr(), request_id,
file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingDone,
weak_factory_.GetWeakPtr(), request_id,
file_system_path)));
}
void WebContents::DevToolsStopIndexing(int request_id) {
auto it = devtools_indexing_jobs_.find(request_id);
if (it == devtools_indexing_jobs_.end())
return;
it->second->Stop();
devtools_indexing_jobs_.erase(it);
}
void WebContents::DevToolsOpenInNewTab(const std::string& url) {
Emit("devtools-open-url", url);
}
void WebContents::DevToolsSearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsSearchCompleted(request_id, file_system_path,
std::vector<std::string>());
return;
}
devtools_file_system_indexer_->SearchInPath(
file_system_path, query,
base::BindRepeating(&WebContents::OnDevToolsSearchCompleted,
weak_factory_.GetWeakPtr(), request_id,
file_system_path));
}
void WebContents::DevToolsSetEyeDropperActive(bool active) {
auto* web_contents = GetWebContents();
if (!web_contents)
return;
if (active) {
eye_dropper_ = std::make_unique<DevToolsEyeDropper>(
web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper,
base::Unretained(this)));
} else {
eye_dropper_.reset();
}
}
void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) {
base::Value::Dict color;
color.Set("r", r);
color.Set("g", g);
color.Set("b", b);
color.Set("a", a);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color)));
}
#if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
ui::ImageModel WebContents::GetDevToolsWindowIcon() {
return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{};
}
#endif
#if BUILDFLAG(IS_LINUX)
void WebContents::GetDevToolsWindowWMClass(std::string* name,
std::string* class_name) {
*class_name = Browser::Get()->GetName();
*name = base::ToLowerASCII(*class_name);
}
#endif
void WebContents::OnDevToolsIndexingWorkCalculated(
int request_id,
const std::string& file_system_path,
int total_work) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id),
base::Value(file_system_path), base::Value(total_work));
}
void WebContents::OnDevToolsIndexingWorked(int request_id,
const std::string& file_system_path,
int worked) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingWorked", base::Value(request_id),
base::Value(file_system_path), base::Value(worked));
}
void WebContents::OnDevToolsIndexingDone(int request_id,
const std::string& file_system_path) {
devtools_indexing_jobs_.erase(request_id);
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone",
base::Value(request_id),
base::Value(file_system_path));
}
void WebContents::OnDevToolsSearchCompleted(
int request_id,
const std::string& file_system_path,
const std::vector<std::string>& file_paths) {
base::Value::List file_paths_value;
for (const auto& file_path : file_paths)
file_paths_value.Append(file_path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "searchCompleted", base::Value(request_id),
base::Value(file_system_path), base::Value(std::move(file_paths_value)));
}
void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) {
// Window is already in fullscreen mode, save the state.
if (enter_fullscreen && owner_window()->IsFullscreen()) {
native_fullscreen_ = true;
UpdateHtmlApiFullscreen(true);
return;
}
// Exit html fullscreen state but not window's fullscreen mode.
if (!enter_fullscreen && native_fullscreen_) {
UpdateHtmlApiFullscreen(false);
return;
}
// Set fullscreen on window if allowed.
auto* web_preferences = WebContentsPreferences::From(GetWebContents());
bool html_fullscreenable =
web_preferences
? !web_preferences->ShouldDisableHtmlFullscreenWindowResize()
: true;
if (html_fullscreenable)
owner_window_->SetFullScreen(enter_fullscreen);
UpdateHtmlApiFullscreen(enter_fullscreen);
native_fullscreen_ = false;
}
void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) {
if (fullscreen == is_html_fullscreen())
return;
html_fullscreen_ = fullscreen;
// Notify renderer of the html fullscreen change.
web_contents()
->GetRenderViewHost()
->GetWidget()
->SynchronizeVisualProperties();
// The embedder WebContents is separated from the frame tree of webview, so
// we must manually sync their fullscreen states.
if (embedder_)
embedder_->SetHtmlApiFullscreen(fullscreen);
if (fullscreen) {
Emit("enter-html-full-screen");
owner_window_->NotifyWindowEnterHtmlFullScreen();
} else {
Emit("leave-html-full-screen");
owner_window_->NotifyWindowLeaveHtmlFullScreen();
}
// Make sure all child webviews quit html fullscreen.
if (!fullscreen && !IsGuest()) {
auto* manager = WebViewManager::GetWebViewManager(web_contents());
manager->ForEachGuest(
web_contents(), base::BindRepeating([](content::WebContents* guest) {
WebContents* api_web_contents = WebContents::From(guest);
api_web_contents->SetHtmlApiFullscreen(false);
return false;
}));
}
}
// static
void WebContents::FillObjectTemplate(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin::InvokerOptions options;
options.holder_is_first_argument = true;
options.holder_type = GetClassName();
templ->Set(
gin::StringToSymbol(isolate, "isDestroyed"),
gin::CreateFunctionTemplate(
isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed),
options));
// We use gin_helper::ObjectTemplateBuilder instead of
// gin::ObjectTemplateBuilder here to handle the fact that WebContents is
// destroyable.
gin_helper::ObjectTemplateBuilder(isolate, templ)
.SetMethod("destroy", &WebContents::Destroy)
.SetMethod("close", &WebContents::Close)
.SetMethod("getBackgroundThrottling",
&WebContents::GetBackgroundThrottling)
.SetMethod("setBackgroundThrottling",
&WebContents::SetBackgroundThrottling)
.SetMethod("getProcessId", &WebContents::GetProcessID)
.SetMethod("getOSProcessId", &WebContents::GetOSProcessID)
.SetMethod("equal", &WebContents::Equal)
.SetMethod("_loadURL", &WebContents::LoadURL)
.SetMethod("reload", &WebContents::Reload)
.SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache)
.SetMethod("downloadURL", &WebContents::DownloadURL)
.SetMethod("getURL", &WebContents::GetURL)
.SetMethod("getTitle", &WebContents::GetTitle)
.SetMethod("isLoading", &WebContents::IsLoading)
.SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
.SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
.SetMethod("stop", &WebContents::Stop)
.SetMethod("canGoBack", &WebContents::CanGoBack)
.SetMethod("goBack", &WebContents::GoBack)
.SetMethod("canGoForward", &WebContents::CanGoForward)
.SetMethod("goForward", &WebContents::GoForward)
.SetMethod("canGoToOffset", &WebContents::CanGoToOffset)
.SetMethod("goToOffset", &WebContents::GoToOffset)
.SetMethod("canGoToIndex", &WebContents::CanGoToIndex)
.SetMethod("goToIndex", &WebContents::GoToIndex)
.SetMethod("getActiveIndex", &WebContents::GetActiveIndex)
.SetMethod("clearHistory", &WebContents::ClearHistory)
.SetMethod("length", &WebContents::GetHistoryLength)
.SetMethod("isCrashed", &WebContents::IsCrashed)
.SetMethod("forcefullyCrashRenderer",
&WebContents::ForcefullyCrashRenderer)
.SetMethod("setUserAgent", &WebContents::SetUserAgent)
.SetMethod("getUserAgent", &WebContents::GetUserAgent)
.SetMethod("savePage", &WebContents::SavePage)
.SetMethod("openDevTools", &WebContents::OpenDevTools)
.SetMethod("closeDevTools", &WebContents::CloseDevTools)
.SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
.SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
.SetMethod("getDevToolsTitle", &WebContents::GetDevToolsTitle)
.SetMethod("setDevToolsTitle", &WebContents::SetDevToolsTitle)
.SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation)
.SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation)
.SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
.SetMethod("inspectElement", &WebContents::InspectElement)
.SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts)
.SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
.SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
.SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible)
.SetMethod("undo", &WebContents::Undo)
.SetMethod("redo", &WebContents::Redo)
.SetMethod("cut", &WebContents::Cut)
.SetMethod("copy", &WebContents::Copy)
.SetMethod("centerSelection", &WebContents::CenterSelection)
.SetMethod("paste", &WebContents::Paste)
.SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
.SetMethod("delete", &WebContents::Delete)
.SetMethod("selectAll", &WebContents::SelectAll)
.SetMethod("unselect", &WebContents::Unselect)
.SetMethod("scrollToTop", &WebContents::ScrollToTopOfDocument)
.SetMethod("scrollToBottom", &WebContents::ScrollToBottomOfDocument)
.SetMethod("adjustSelection",
&WebContents::AdjustSelectionByCharacterOffset)
.SetMethod("replace", &WebContents::Replace)
.SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
.SetMethod("findInPage", &WebContents::FindInPage)
.SetMethod("stopFindInPage", &WebContents::StopFindInPage)
.SetMethod("focus", &WebContents::Focus)
.SetMethod("isFocused", &WebContents::IsFocused)
.SetMethod("sendInputEvent", &WebContents::SendInputEvent)
.SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription)
.SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
.SetMethod("startDrag", &WebContents::StartDrag)
.SetMethod("attachToIframe", &WebContents::AttachToIframe)
.SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame)
.SetMethod("isOffscreen", &WebContents::IsOffScreen)
.SetMethod("startPainting", &WebContents::StartPainting)
.SetMethod("stopPainting", &WebContents::StopPainting)
.SetMethod("isPainting", &WebContents::IsPainting)
.SetMethod("setFrameRate", &WebContents::SetFrameRate)
.SetMethod("getFrameRate", &WebContents::GetFrameRate)
.SetMethod("invalidate", &WebContents::Invalidate)
.SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
.SetMethod("getZoomLevel", &WebContents::GetZoomLevel)
.SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
.SetMethod("getZoomFactor", &WebContents::GetZoomFactor)
.SetMethod("getType", &WebContents::GetType)
.SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths)
.SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences)
.SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
.SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
.SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker)
.SetMethod("inspectSharedWorkerById",
&WebContents::InspectSharedWorkerById)
.SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers)
#if BUILDFLAG(ENABLE_PRINTING)
.SetMethod("_print", &WebContents::Print)
.SetMethod("_printToPDF", &WebContents::PrintToPDF)
#endif
.SetMethod("_setNextChildWebPreferences",
&WebContents::SetNextChildWebPreferences)
.SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
.SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
.SetMethod("showDefinitionForSelection",
&WebContents::ShowDefinitionForSelection)
.SetMethod("copyImageAt", &WebContents::CopyImageAt)
.SetMethod("capturePage", &WebContents::CapturePage)
.SetMethod("setEmbedder", &WebContents::SetEmbedder)
.SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents)
.SetMethod("getNativeView", &WebContents::GetNativeView)
.SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured)
.SetMethod("setWebRTCIPHandlingPolicy",
&WebContents::SetWebRTCIPHandlingPolicy)
.SetMethod("setWebRTCUDPPortRange", &WebContents::SetWebRTCUDPPortRange)
.SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID)
.SetMethod("getWebRTCIPHandlingPolicy",
&WebContents::GetWebRTCIPHandlingPolicy)
.SetMethod("getWebRTCUDPPortRange", &WebContents::GetWebRTCUDPPortRange)
.SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot)
.SetMethod("setImageAnimationPolicy",
&WebContents::SetImageAnimationPolicy)
.SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo)
.SetProperty("id", &WebContents::ID)
.SetProperty("session", &WebContents::Session)
.SetProperty("hostWebContents", &WebContents::HostWebContents)
.SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
.SetProperty("debugger", &WebContents::Debugger)
.SetProperty("mainFrame", &WebContents::MainFrame)
.SetProperty("opener", &WebContents::Opener)
.Build();
}
const char* WebContents::GetTypeName() {
return GetClassName();
}
ElectronBrowserContext* WebContents::GetBrowserContext() const {
return static_cast<ElectronBrowserContext*>(
web_contents()->GetBrowserContext());
}
// static
gin::Handle<WebContents> WebContents::New(
v8::Isolate* isolate,
const gin_helper::Dictionary& options) {
gin::Handle<WebContents> handle =
gin::CreateHandle(isolate, new WebContents(isolate, options));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
gin::Handle<WebContents> WebContents::CreateAndTake(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type) {
gin::Handle<WebContents> handle = gin::CreateHandle(
isolate, new WebContents(isolate, std::move(web_contents), type));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
WebContents* WebContents::From(content::WebContents* web_contents) {
if (!web_contents)
return nullptr;
auto* data = static_cast<UserDataLink*>(
web_contents->GetUserData(kElectronApiWebContentsKey));
return data ? data->web_contents.get() : nullptr;
}
// static
gin::Handle<WebContents> WebContents::FromOrCreate(
v8::Isolate* isolate,
content::WebContents* web_contents) {
WebContents* api_web_contents = From(web_contents);
if (!api_web_contents) {
api_web_contents = new WebContents(isolate, web_contents);
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, api_web_contents, "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
}
return gin::CreateHandle(isolate, api_web_contents);
}
// static
gin::Handle<WebContents> WebContents::CreateFromWebPreferences(
v8::Isolate* isolate,
const gin_helper::Dictionary& web_preferences) {
// Check if webPreferences has |webContents| option.
gin::Handle<WebContents> web_contents;
if (web_preferences.GetHidden("webContents", &web_contents) &&
!web_contents.IsEmpty()) {
// Set webPreferences from options if using an existing webContents.
// These preferences will be used when the webContent launches new
// render processes.
auto* existing_preferences =
WebContentsPreferences::From(web_contents->web_contents());
gin_helper::Dictionary web_preferences_dict;
if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(),
&web_preferences_dict)) {
existing_preferences->SetFromDictionary(web_preferences_dict);
absl::optional<SkColor> color =
existing_preferences->GetBackgroundColor();
web_contents->web_contents()->SetPageBaseBackgroundColor(color);
// Because web preferences don't recognize transparency,
// only set rwhv background color if a color exists
auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView();
if (rwhv && color.has_value())
SetBackgroundColor(rwhv, color.value());
}
} else {
// Create one if not.
web_contents = WebContents::New(isolate, web_preferences);
}
return web_contents;
}
// static
WebContents* WebContents::FromID(int32_t id) {
return GetAllWebContents().Lookup(id);
}
// static
std::list<WebContents*> WebContents::GetWebContentsList() {
std::list<WebContents*> list;
for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
!iter.IsAtEnd(); iter.Advance()) {
list.push_back(iter.GetCurrentValue());
}
return list;
}
// static
gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin};
} // namespace electron::api
namespace {
using electron::api::GetAllWebContents;
using electron::api::WebContents;
using electron::api::WebFrameMain;
gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) {
WebContents* contents = WebContents::FromID(id);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromFrame(v8::Isolate* isolate,
WebFrameMain* web_frame) {
content::RenderFrameHost* rfh = web_frame->render_frame_host();
content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh);
WebContents* contents = WebContents::From(source);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromDevToolsTargetID(
v8::Isolate* isolate,
std::string target_id) {
auto agent_host = content::DevToolsAgentHost::GetForId(target_id);
WebContents* contents =
agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr;
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8(
v8::Isolate* isolate) {
std::vector<gin::Handle<WebContents>> list;
for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
!iter.IsAtEnd(); iter.Advance()) {
list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue()));
}
return list;
}
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("WebContents", WebContents::GetConstructor(context));
dict.SetMethod("fromId", &WebContentsFromID);
dict.SetMethod("fromFrame", &WebContentsFromFrame);
dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID);
dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8);
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 19,847 |
[Bug]: loadURL after did-start-loading crashes electron
|
### Preflight Checklist
* [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project.
* [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to.
* [X] I have searched the issue tracker for an issue that matches the one I want to file, without success.
### Issue Details
* **Electron Version:**
* 5.0.10 , 6 ,7
* **Operating System:**
* Windows 10
* **Last Known Working Electron version:** ?
### Expected Behavior
No crash
### Actual Behavior
In electron 5 it crashes with the following code: 2147483651
in electron 6 and 7 it just seems to hang but is basically dead
### To Reproduce
```
const { app, BrowserWindow, BrowserView } = require("electron");
const init = () => {
let browserWindow = new BrowserWindow({
show: true,
});
browserWindow.loadURL("https://www.google.com");
let browserWindow2 = new BrowserWindow({
show: true,
});
browserWindow2.webContents.once("did-start-loading", () => {
browserWindow2.loadURL("https://www.google.com");
});
browserWindow2.loadURL("https://www.test.com");
};
app.on("ready", () => {
init();
});
```
<!--
If you provide a URL, please list the commands required to clone/setup/run your repo e.g.
```sh
$ git clone $YOUR_URL -b $BRANCH
$ npm install
$ npm start || electron .
```
-->
### Additional Information
<!-- Add any other context about the problem here. -->
|
https://github.com/electron/electron/issues/19847
|
https://github.com/electron/electron/pull/40143
|
563c370d51f302b6d4a7fee8b47e1cc3e1ca2fe3
|
86df4db6f10afbe5872f8ecbcbfe6191374fc1f7
| 2019-08-20T20:05:40Z |
c++
| 2023-10-10T10:46:04Z |
spec/api-web-contents-spec.ts
|
import { expect } from 'chai';
import { AddressInfo } from 'node:net';
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as http from 'node:http';
import { BrowserWindow, ipcMain, webContents, session, app, BrowserView, WebContents, deprecate } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import { ifdescribe, defer, waitUntil, listen, ifit } from './lib/spec-helpers';
import { once } from 'node:events';
import { setTimeout } from 'node:timers/promises';
const pdfjs = require('pdfjs-dist');
const fixturesPath = path.resolve(__dirname, 'fixtures');
const mainFixturesPath = path.resolve(__dirname, 'fixtures');
const features = process._linkedBinding('electron_common_features');
describe('webContents module', () => {
describe('getAllWebContents() API', () => {
afterEach(closeAllWindows);
it('returns an array of web contents', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { webviewTag: true }
});
w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html'));
await once(w.webContents, 'did-attach-webview') as [any, WebContents];
w.webContents.openDevTools();
await once(w.webContents, 'devtools-opened');
const all = webContents.getAllWebContents().sort((a, b) => {
return a.id - b.id;
});
expect(all).to.have.length(3);
expect(all[0].getType()).to.equal('window');
expect(all[all.length - 2].getType()).to.equal('webview');
expect(all[all.length - 1].getType()).to.equal('remote');
});
});
describe('fromId()', () => {
it('returns undefined for an unknown id', () => {
expect(webContents.fromId(12345)).to.be.undefined();
});
});
describe('fromFrame()', () => {
it('returns WebContents for mainFrame', () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create();
expect(webContents.fromFrame(contents.mainFrame)).to.equal(contents);
});
it('returns undefined for disposed frame', async () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create();
const { mainFrame } = contents;
contents.destroy();
await waitUntil(() => typeof webContents.fromFrame(mainFrame) === 'undefined');
});
it('throws when passing invalid argument', async () => {
let errored = false;
try {
webContents.fromFrame({} as any);
} catch {
errored = true;
}
expect(errored).to.be.true();
});
});
describe('fromDevToolsTargetId()', () => {
it('returns WebContents for attached DevTools target', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
try {
await w.webContents.debugger.attach('1.3');
const { targetInfo } = await w.webContents.debugger.sendCommand('Target.getTargetInfo');
expect(webContents.fromDevToolsTargetId(targetInfo.targetId)).to.equal(w.webContents);
} finally {
await w.webContents.debugger.detach();
}
});
it('returns undefined for an unknown id', () => {
expect(webContents.fromDevToolsTargetId('nope')).to.be.undefined();
});
});
describe('will-prevent-unload event', function () {
afterEach(closeAllWindows);
it('does not emit if beforeunload returns undefined in a BrowserWindow', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.once('will-prevent-unload', () => {
expect.fail('should not have fired');
});
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
it('does not emit if beforeunload returns undefined in a BrowserView', async () => {
const w = new BrowserWindow({ show: false });
const view = new BrowserView();
w.setBrowserView(view);
view.setBounds(w.getBounds());
view.webContents.once('will-prevent-unload', () => {
expect.fail('should not have fired');
});
await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
it('emits if beforeunload returns false in a BrowserWindow', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
await once(w.webContents, 'will-prevent-unload');
});
it('emits if beforeunload returns false in a BrowserView', async () => {
const w = new BrowserWindow({ show: false });
const view = new BrowserView();
w.setBrowserView(view);
view.setBounds(w.getBounds());
await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
await once(view.webContents, 'will-prevent-unload');
});
it('supports calling preventDefault on will-prevent-unload events in a BrowserWindow', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.once('will-prevent-unload', event => event.preventDefault());
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
});
describe('webContents.send(channel, args...)', () => {
afterEach(closeAllWindows);
it('throws an error when the channel is missing', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
(w.webContents.send as any)();
}).to.throw('Missing required channel argument');
expect(() => {
w.webContents.send(null as any);
}).to.throw('Missing required channel argument');
});
it('does not block node async APIs when sent before document is ready', (done) => {
// Please reference https://github.com/electron/electron/issues/19368 if
// this test fails.
ipcMain.once('async-node-api-done', () => {
done();
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
sandbox: false,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html'));
setTimeout(50).then(() => {
w.webContents.send('test');
});
});
});
ifdescribe(features.isPrintingEnabled())('webContents.print()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
it('throws when invalid settings are passed', () => {
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print(true);
}).to.throw('webContents.print(): Invalid print settings specified.');
});
it('throws when an invalid pageSize is passed', () => {
const badSize = 5;
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print({ pageSize: badSize });
}).to.throw(`Unsupported pageSize: ${badSize}`);
});
it('throws when an invalid callback is passed', () => {
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print({}, true);
}).to.throw('webContents.print(): Invalid optional callback provided.');
});
it('fails when an invalid deviceName is passed', (done) => {
w.webContents.print({ deviceName: 'i-am-a-nonexistent-printer' }, (success, reason) => {
expect(success).to.equal(false);
expect(reason).to.match(/Invalid deviceName provided/);
done();
});
});
it('throws when an invalid pageSize is passed', () => {
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print({ pageSize: 'i-am-a-bad-pagesize' }, () => {});
}).to.throw('Unsupported pageSize: i-am-a-bad-pagesize');
});
it('throws when an invalid custom pageSize is passed', () => {
expect(() => {
w.webContents.print({
pageSize: {
width: 100,
height: 200
}
});
}).to.throw('height and width properties must be minimum 352 microns.');
});
it('does not crash with custom margins', () => {
expect(() => {
w.webContents.print({
silent: true,
margins: {
marginType: 'custom',
top: 1,
bottom: 1,
left: 1,
right: 1
}
});
}).to.not.throw();
});
});
describe('webContents.executeJavaScript', () => {
describe('in about:blank', () => {
const expected = 'hello, world!';
const expectedErrorMsg = 'woops!';
const code = `(() => "${expected}")()`;
const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`;
const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`;
const errorTypes = new Set([
Error,
ReferenceError,
EvalError,
RangeError,
SyntaxError,
TypeError,
URIError
]);
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false } });
await w.loadURL('about:blank');
});
after(closeAllWindows);
it('resolves the returned promise with the result', async () => {
const result = await w.webContents.executeJavaScript(code);
expect(result).to.equal(expected);
});
it('resolves the returned promise with the result if the code returns an asynchronous promise', async () => {
const result = await w.webContents.executeJavaScript(asyncCode);
expect(result).to.equal(expected);
});
it('rejects the returned promise if an async error is thrown', async () => {
await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg);
});
it('rejects the returned promise with an error if an Error.prototype is thrown', async () => {
for (const error of errorTypes) {
await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`))
.to.eventually.be.rejectedWith(error);
}
});
});
describe('on a real page', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((request, response) => {
response.end();
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('works after page load and during subframe load', async () => {
await w.loadURL(serverUrl);
// initiate a sub-frame load, then try and execute script during it
await w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe')
iframe.src = '${serverUrl}/slow'
document.body.appendChild(iframe)
null // don't return the iframe
`);
await w.webContents.executeJavaScript('console.log(\'hello\')');
});
it('executes after page load', async () => {
const executeJavaScript = w.webContents.executeJavaScript('(() => "test")()');
w.loadURL(serverUrl);
const result = await executeJavaScript;
expect(result).to.equal('test');
});
});
});
describe('webContents.executeJavaScriptInIsolatedWorld', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } });
await w.loadURL('about:blank');
});
it('resolves the returned promise with the result', async () => {
await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X = 123' }]);
const isolatedResult = await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X' }]);
const mainWorldResult = await w.webContents.executeJavaScript('window.X');
expect(isolatedResult).to.equal(123);
expect(mainWorldResult).to.equal(undefined);
});
});
describe('loadURL() promise API', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
it('resolves when done loading', async () => {
await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled();
});
it('resolves when done loading a file URL', async () => {
await expect(w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'))).to.eventually.be.fulfilled();
});
it('resolves when navigating within the page', async () => {
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
await setTimeout();
await expect(w.loadURL(w.getURL() + '#foo')).to.eventually.be.fulfilled();
});
it('resolves after browser initiated navigation', async () => {
let finishedLoading = false;
w.webContents.on('did-finish-load', function () {
finishedLoading = true;
});
await w.loadFile(path.join(fixturesPath, 'pages', 'navigate_in_page_and_wait.html'));
expect(finishedLoading).to.be.true();
});
it('rejects when failing to load a file URL', async () => {
await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected()
.and.have.property('code', 'ERR_FILE_NOT_FOUND');
});
// FIXME: Temporarily disable on WOA until
// https://github.com/electron/electron/issues/20008 is resolved
ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('rejects when loading fails due to DNS not resolved', async () => {
await expect(w.loadURL('https://err.name.not.resolved')).to.eventually.be.rejected()
.and.have.property('code', 'ERR_NAME_NOT_RESOLVED');
});
it('rejects when navigation is cancelled due to a bad scheme', async () => {
await expect(w.loadURL('bad-scheme://foo')).to.eventually.be.rejected()
.and.have.property('code', 'ERR_FAILED');
});
it('does not crash when loading a new URL with emulation settings set', async () => {
const setEmulation = async () => {
if (w.webContents) {
w.webContents.debugger.attach('1.3');
const deviceMetrics = {
width: 700,
height: 600,
deviceScaleFactor: 2,
mobile: true,
dontSetVisibleSize: true
};
await w.webContents.debugger.sendCommand(
'Emulation.setDeviceMetricsOverride',
deviceMetrics
);
}
};
try {
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
await setEmulation();
await w.loadURL('data:text/html,<h1>HELLO</h1>');
await setEmulation();
} catch (e) {
expect((e as Error).message).to.match(/Debugger is already attached to the target/);
}
});
it('sets appropriate error information on rejection', async () => {
let err: any;
try {
await w.loadURL('file:non-existent');
} catch (e) {
err = e;
}
expect(err).not.to.be.null();
expect(err.code).to.eql('ERR_FILE_NOT_FOUND');
expect(err.errno).to.eql(-6);
expect(err.url).to.eql(process.platform === 'win32' ? 'file://non-existent/' : 'file:///non-existent');
});
it('rejects if the load is aborted', async () => {
const s = http.createServer(() => { /* never complete the request */ });
const { port } = await listen(s);
const p = expect(w.loadURL(`http://127.0.0.1:${port}`)).to.eventually.be.rejectedWith(Error, /ERR_ABORTED/);
// load a different file before the first load completes, causing the
// first load to be aborted.
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
await p;
s.close();
});
it("doesn't reject when a subframe fails to load", async () => {
let resp = null as unknown as http.ServerResponse;
const s = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<iframe src="http://err.name.not.resolved"></iframe>');
resp = res;
// don't end the response yet
});
const { port } = await listen(s);
const p = new Promise<void>(resolve => {
w.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => {
if (!isMainFrame) {
resolve();
}
});
});
const main = w.loadURL(`http://127.0.0.1:${port}`);
await p;
resp.end();
await main;
s.close();
});
it("doesn't resolve when a subframe loads", async () => {
let resp = null as unknown as http.ServerResponse;
const s = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<iframe src="about:blank"></iframe>');
resp = res;
// don't end the response yet
});
const { port } = await listen(s);
const p = new Promise<void>(resolve => {
w.webContents.on('did-frame-finish-load', (event, isMainFrame) => {
if (!isMainFrame) {
resolve();
}
});
});
const main = w.loadURL(`http://127.0.0.1:${port}`);
await p;
resp.destroy(); // cause the main request to fail
await expect(main).to.eventually.be.rejected()
.and.have.property('errno', -355); // ERR_INCOMPLETE_CHUNKED_ENCODING
s.close();
});
});
describe('getFocusedWebContents() API', () => {
afterEach(closeAllWindows);
// FIXME
ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('returns the focused web contents', async () => {
const w = new BrowserWindow({ show: true });
await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id);
const devToolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools();
await devToolsOpened;
expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.devToolsWebContents!.id);
const devToolsClosed = once(w.webContents, 'devtools-closed');
w.webContents.closeDevTools();
await devToolsClosed;
expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id);
});
it('does not crash when called on a detached dev tools window', async () => {
const w = new BrowserWindow({ show: true });
w.webContents.openDevTools({ mode: 'detach' });
w.webContents.inspectElement(100, 100);
// For some reason we have to wait for two focused events...?
await once(w.webContents, 'devtools-focused');
expect(() => { webContents.getFocusedWebContents(); }).to.not.throw();
// Work around https://github.com/electron/electron/issues/19985
await setTimeout();
const devToolsClosed = once(w.webContents, 'devtools-closed');
w.webContents.closeDevTools();
await devToolsClosed;
expect(() => { webContents.getFocusedWebContents(); }).to.not.throw();
});
});
describe('setDevToolsWebContents() API', () => {
afterEach(closeAllWindows);
it('sets arbitrary webContents as devtools', async () => {
const w = new BrowserWindow({ show: false });
const devtools = new BrowserWindow({ show: false });
const promise = once(devtools.webContents, 'dom-ready');
w.webContents.setDevToolsWebContents(devtools.webContents);
w.webContents.openDevTools();
await promise;
expect(devtools.webContents.getURL().startsWith('devtools://devtools')).to.be.true();
const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name');
expect(result).to.equal('InspectorFrontendHostImpl');
devtools.destroy();
});
});
describe('isFocused() API', () => {
it('returns false when the window is hidden', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(w.isVisible()).to.be.false();
expect(w.webContents.isFocused()).to.be.false();
});
});
describe('isCurrentlyAudible() API', () => {
afterEach(closeAllWindows);
it('returns whether audio is playing', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
await w.webContents.executeJavaScript(`
window.context = new AudioContext
// Start in suspended state, because of the
// new web audio api policy.
context.suspend()
window.oscillator = context.createOscillator()
oscillator.connect(context.destination)
oscillator.start()
`);
let p = once(w.webContents, 'audio-state-changed');
w.webContents.executeJavaScript('context.resume()');
await p;
expect(w.webContents.isCurrentlyAudible()).to.be.true();
p = once(w.webContents, 'audio-state-changed');
w.webContents.executeJavaScript('oscillator.stop()');
await p;
expect(w.webContents.isCurrentlyAudible()).to.be.false();
});
});
describe('openDevTools() API', () => {
afterEach(closeAllWindows);
it('can show window with activation', async () => {
const w = new BrowserWindow({ show: false });
const focused = once(w, 'focus');
w.show();
await focused;
expect(w.isFocused()).to.be.true();
const blurred = once(w, 'blur');
w.webContents.openDevTools({ mode: 'detach', activate: true });
await Promise.all([
once(w.webContents, 'devtools-opened'),
once(w.webContents, 'devtools-focused')
]);
await blurred;
expect(w.isFocused()).to.be.false();
});
it('can show window without activation', async () => {
const w = new BrowserWindow({ show: false });
const devtoolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools({ mode: 'detach', activate: false });
await devtoolsOpened;
expect(w.webContents.isDevToolsOpened()).to.be.true();
});
it('can show a DevTools window with custom title', async () => {
const w = new BrowserWindow({ show: false });
const devtoolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools({ mode: 'detach', activate: false, title: 'myTitle' });
await devtoolsOpened;
expect(w.webContents.getDevToolsTitle()).to.equal('myTitle');
});
});
describe('setDevToolsTitle() API', () => {
afterEach(closeAllWindows);
it('can set devtools title with function', async () => {
const w = new BrowserWindow({ show: false });
const devtoolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools({ mode: 'detach', activate: false });
await devtoolsOpened;
expect(w.webContents.isDevToolsOpened()).to.be.true();
w.webContents.setDevToolsTitle('newTitle');
expect(w.webContents.getDevToolsTitle()).to.equal('newTitle');
});
});
describe('before-input-event event', () => {
afterEach(closeAllWindows);
it('can prevent document keyboard events', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html'));
const keyDown = new Promise(resolve => {
ipcMain.once('keydown', (event, key) => resolve(key));
});
w.webContents.once('before-input-event', (event, input) => {
if (input.key === 'a') event.preventDefault();
});
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' });
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' });
expect(await keyDown).to.equal('b');
});
it('has the correct properties', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const testBeforeInput = async (opts: any) => {
const modifiers = [];
if (opts.shift) modifiers.push('shift');
if (opts.control) modifiers.push('control');
if (opts.alt) modifiers.push('alt');
if (opts.meta) modifiers.push('meta');
if (opts.isAutoRepeat) modifiers.push('isAutoRepeat');
const p = once(w.webContents, 'before-input-event') as Promise<[any, Electron.Input]>;
w.webContents.sendInputEvent({
type: opts.type,
keyCode: opts.keyCode,
modifiers: modifiers as any
});
const [, input] = await p;
expect(input.type).to.equal(opts.type);
expect(input.key).to.equal(opts.key);
expect(input.code).to.equal(opts.code);
expect(input.isAutoRepeat).to.equal(opts.isAutoRepeat);
expect(input.shift).to.equal(opts.shift);
expect(input.control).to.equal(opts.control);
expect(input.alt).to.equal(opts.alt);
expect(input.meta).to.equal(opts.meta);
};
await testBeforeInput({
type: 'keyDown',
key: 'A',
code: 'KeyA',
keyCode: 'a',
shift: true,
control: true,
alt: true,
meta: true,
isAutoRepeat: true
});
await testBeforeInput({
type: 'keyUp',
key: '.',
code: 'Period',
keyCode: '.',
shift: false,
control: true,
alt: true,
meta: false,
isAutoRepeat: false
});
await testBeforeInput({
type: 'keyUp',
key: '!',
code: 'Digit1',
keyCode: '1',
shift: true,
control: false,
alt: false,
meta: true,
isAutoRepeat: false
});
await testBeforeInput({
type: 'keyUp',
key: 'Tab',
code: 'Tab',
keyCode: 'Tab',
shift: false,
control: true,
alt: false,
meta: false,
isAutoRepeat: true
});
});
});
// On Mac, zooming isn't done with the mouse wheel.
ifdescribe(process.platform !== 'darwin')('zoom-changed', () => {
afterEach(closeAllWindows);
it('is emitted with the correct zoom-in info', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const testZoomChanged = async () => {
w.webContents.sendInputEvent({
type: 'mouseWheel',
x: 300,
y: 300,
deltaX: 0,
deltaY: 1,
wheelTicksX: 0,
wheelTicksY: 1,
modifiers: ['control', 'meta']
});
const [, zoomDirection] = await once(w.webContents, 'zoom-changed') as [any, string];
expect(zoomDirection).to.equal('in');
};
await testZoomChanged();
});
it('is emitted with the correct zoom-out info', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const testZoomChanged = async () => {
w.webContents.sendInputEvent({
type: 'mouseWheel',
x: 300,
y: 300,
deltaX: 0,
deltaY: -1,
wheelTicksX: 0,
wheelTicksY: -1,
modifiers: ['control', 'meta']
});
const [, zoomDirection] = await once(w.webContents, 'zoom-changed') as [any, string];
expect(zoomDirection).to.equal('out');
};
await testZoomChanged();
});
});
describe('sendInputEvent(event)', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html'));
});
afterEach(closeAllWindows);
it('can send keydown events', async () => {
const keydown = once(ipcMain, 'keydown');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
expect(key).to.equal('a');
expect(code).to.equal('KeyA');
expect(keyCode).to.equal(65);
expect(shiftKey).to.be.false();
expect(ctrlKey).to.be.false();
expect(altKey).to.be.false();
});
it('can send keydown events with modifiers', async () => {
const keydown = once(ipcMain, 'keydown');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z', modifiers: ['shift', 'ctrl'] });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
expect(key).to.equal('Z');
expect(code).to.equal('KeyZ');
expect(keyCode).to.equal(90);
expect(shiftKey).to.be.true();
expect(ctrlKey).to.be.true();
expect(altKey).to.be.false();
});
it('can send keydown events with special keys', async () => {
const keydown = once(ipcMain, 'keydown');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab', modifiers: ['alt'] });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
expect(key).to.equal('Tab');
expect(code).to.equal('Tab');
expect(keyCode).to.equal(9);
expect(shiftKey).to.be.false();
expect(ctrlKey).to.be.false();
expect(altKey).to.be.true();
});
it('can send char events', async () => {
const keypress = once(ipcMain, 'keypress');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' });
w.webContents.sendInputEvent({ type: 'char', keyCode: 'A' });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress;
expect(key).to.equal('a');
expect(code).to.equal('KeyA');
expect(keyCode).to.equal(65);
expect(shiftKey).to.be.false();
expect(ctrlKey).to.be.false();
expect(altKey).to.be.false();
});
it('can correctly convert accelerators to key codes', async () => {
const keyup = once(ipcMain, 'keyup');
w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' });
w.webContents.sendInputEvent({ keyCode: 'Space', type: 'char' });
w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' });
w.webContents.sendInputEvent({ keyCode: 'Space', type: 'char' });
w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' });
w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'keyUp' });
await keyup;
const inputText = await w.webContents.executeJavaScript('document.getElementById("input").value');
expect(inputText).to.equal('+ + +');
});
it('can send char events with modifiers', async () => {
const keypress = once(ipcMain, 'keypress');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' });
w.webContents.sendInputEvent({ type: 'char', keyCode: 'Z', modifiers: ['shift', 'ctrl'] });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress;
expect(key).to.equal('Z');
expect(code).to.equal('KeyZ');
expect(keyCode).to.equal(90);
expect(shiftKey).to.be.true();
expect(ctrlKey).to.be.true();
expect(altKey).to.be.false();
});
});
describe('insertCSS', () => {
afterEach(closeAllWindows);
it('supports inserting CSS', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await w.webContents.insertCSS('body { background-repeat: round; }');
const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
expect(result).to.equal('round');
});
it('supports removing inserted CSS', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
const key = await w.webContents.insertCSS('body { background-repeat: round; }');
await w.webContents.removeInsertedCSS(key);
const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
expect(result).to.equal('repeat');
});
});
describe('inspectElement()', () => {
afterEach(closeAllWindows);
it('supports inspecting an element in the devtools', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
const event = once(w.webContents, 'devtools-opened');
w.webContents.inspectElement(10, 10);
await event;
});
});
describe('startDrag({file, icon})', () => {
it('throws errors for a missing file or a missing/empty icon', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.webContents.startDrag({ icon: path.join(fixturesPath, 'assets', 'logo.png') } as any);
}).to.throw('Must specify either \'file\' or \'files\' option');
expect(() => {
w.webContents.startDrag({ file: __filename } as any);
}).to.throw('\'icon\' parameter is required');
expect(() => {
w.webContents.startDrag({ file: __filename, icon: path.join(mainFixturesPath, 'blank.png') });
}).to.throw(/Failed to load image from path (.+)/);
});
});
describe('focus APIs', () => {
describe('focus()', () => {
afterEach(closeAllWindows);
it('does not blur the focused window when the web contents is hidden', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
w.show();
await w.loadURL('about:blank');
w.focus();
const child = new BrowserWindow({ show: false });
child.loadURL('about:blank');
child.webContents.focus();
const currentFocused = w.isFocused();
const childFocused = child.isFocused();
child.close();
expect(currentFocused).to.be.true();
expect(childFocused).to.be.false();
});
});
const moveFocusToDevTools = async (win: BrowserWindow) => {
const devToolsOpened = once(win.webContents, 'devtools-opened');
win.webContents.openDevTools({ mode: 'right' });
await devToolsOpened;
win.webContents.devToolsWebContents!.focus();
};
describe('focus event', () => {
afterEach(closeAllWindows);
it('is triggered when web contents is focused', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
await moveFocusToDevTools(w);
const focusPromise = once(w.webContents, 'focus');
w.webContents.focus();
await expect(focusPromise).to.eventually.be.fulfilled();
});
});
describe('blur event', () => {
afterEach(closeAllWindows);
it('is triggered when web contents is blurred', async () => {
const w = new BrowserWindow({ show: true });
await w.loadURL('about:blank');
w.webContents.focus();
const blurPromise = once(w.webContents, 'blur');
await moveFocusToDevTools(w);
await expect(blurPromise).to.eventually.be.fulfilled();
});
});
});
describe('getOSProcessId()', () => {
afterEach(closeAllWindows);
it('returns a valid process id', async () => {
const w = new BrowserWindow({ show: false });
expect(w.webContents.getOSProcessId()).to.equal(0);
await w.loadURL('about:blank');
expect(w.webContents.getOSProcessId()).to.be.above(0);
});
});
describe('getMediaSourceId()', () => {
afterEach(closeAllWindows);
it('returns a valid stream id', () => {
const w = new BrowserWindow({ show: false });
expect(w.webContents.getMediaSourceId(w.webContents)).to.be.a('string').that.is.not.empty();
});
});
describe('userAgent APIs', () => {
it('is not empty by default', () => {
const w = new BrowserWindow({ show: false });
const userAgent = w.webContents.getUserAgent();
expect(userAgent).to.be.a('string').that.is.not.empty();
});
it('can set the user agent (functions)', () => {
const w = new BrowserWindow({ show: false });
const userAgent = w.webContents.getUserAgent();
w.webContents.setUserAgent('my-user-agent');
expect(w.webContents.getUserAgent()).to.equal('my-user-agent');
w.webContents.setUserAgent(userAgent);
expect(w.webContents.getUserAgent()).to.equal(userAgent);
});
it('can set the user agent (properties)', () => {
const w = new BrowserWindow({ show: false });
const userAgent = w.webContents.userAgent;
w.webContents.userAgent = 'my-user-agent';
expect(w.webContents.userAgent).to.equal('my-user-agent');
w.webContents.userAgent = userAgent;
expect(w.webContents.userAgent).to.equal(userAgent);
});
});
describe('audioMuted APIs', () => {
it('can set the audio mute level (functions)', () => {
const w = new BrowserWindow({ show: false });
w.webContents.setAudioMuted(true);
expect(w.webContents.isAudioMuted()).to.be.true();
w.webContents.setAudioMuted(false);
expect(w.webContents.isAudioMuted()).to.be.false();
});
it('can set the audio mute level (functions)', () => {
const w = new BrowserWindow({ show: false });
w.webContents.audioMuted = true;
expect(w.webContents.audioMuted).to.be.true();
w.webContents.audioMuted = false;
expect(w.webContents.audioMuted).to.be.false();
});
});
describe('zoom api', () => {
const hostZoomMap: Record<string, number> = {
host1: 0.3,
host2: 0.7,
host3: 0.2
};
before(() => {
const protocol = session.defaultSession.protocol;
protocol.registerStringProtocol(standardScheme, (request, callback) => {
const response = `<script>
const {ipcRenderer} = require('electron')
ipcRenderer.send('set-zoom', window.location.hostname)
ipcRenderer.on(window.location.hostname + '-zoom-set', () => {
ipcRenderer.send(window.location.hostname + '-zoom-level')
})
</script>`;
callback({ data: response, mimeType: 'text/html' });
});
});
after(() => {
const protocol = session.defaultSession.protocol;
protocol.unregisterProtocol(standardScheme);
});
afterEach(closeAllWindows);
it('throws on an invalid zoomFactor', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(() => {
w.webContents.setZoomFactor(0.0);
}).to.throw(/'zoomFactor' must be a double greater than 0.0/);
expect(() => {
w.webContents.setZoomFactor(-2.0);
}).to.throw(/'zoomFactor' must be a double greater than 0.0/);
});
it('can set the correct zoom level (functions)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomLevel = w.webContents.getZoomLevel();
expect(zoomLevel).to.eql(0.0);
w.webContents.setZoomLevel(0.5);
const newZoomLevel = w.webContents.getZoomLevel();
expect(newZoomLevel).to.eql(0.5);
} finally {
w.webContents.setZoomLevel(0);
}
});
it('can set the correct zoom level (properties)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomLevel = w.webContents.zoomLevel;
expect(zoomLevel).to.eql(0.0);
w.webContents.zoomLevel = 0.5;
const newZoomLevel = w.webContents.zoomLevel;
expect(newZoomLevel).to.eql(0.5);
} finally {
w.webContents.zoomLevel = 0;
}
});
it('can set the correct zoom factor (functions)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomFactor = w.webContents.getZoomFactor();
expect(zoomFactor).to.eql(1.0);
w.webContents.setZoomFactor(0.5);
const newZoomFactor = w.webContents.getZoomFactor();
expect(newZoomFactor).to.eql(0.5);
} finally {
w.webContents.setZoomFactor(1.0);
}
});
it('can set the correct zoom factor (properties)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomFactor = w.webContents.zoomFactor;
expect(zoomFactor).to.eql(1.0);
w.webContents.zoomFactor = 0.5;
const newZoomFactor = w.webContents.zoomFactor;
expect(newZoomFactor).to.eql(0.5);
} finally {
w.webContents.zoomFactor = 1.0;
}
});
it('can persist zoom level across navigation', (done) => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
let finalNavigation = false;
ipcMain.on('set-zoom', (e, host) => {
const zoomLevel = hostZoomMap[host];
if (!finalNavigation) w.webContents.zoomLevel = zoomLevel;
e.sender.send(`${host}-zoom-set`);
});
ipcMain.on('host1-zoom-level', (e) => {
try {
const zoomLevel = e.sender.getZoomLevel();
const expectedZoomLevel = hostZoomMap.host1;
expect(zoomLevel).to.equal(expectedZoomLevel);
if (finalNavigation) {
done();
} else {
w.loadURL(`${standardScheme}://host2`);
}
} catch (e) {
done(e);
}
});
ipcMain.once('host2-zoom-level', (e) => {
try {
const zoomLevel = e.sender.getZoomLevel();
const expectedZoomLevel = hostZoomMap.host2;
expect(zoomLevel).to.equal(expectedZoomLevel);
finalNavigation = true;
w.webContents.goBack();
} catch (e) {
done(e);
}
});
w.loadURL(`${standardScheme}://host1`);
});
it('can propagate zoom level across same session', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
const w2 = new BrowserWindow({ show: false });
defer(() => {
w2.setClosable(true);
w2.close();
});
await w.loadURL(`${standardScheme}://host3`);
w.webContents.zoomLevel = hostZoomMap.host3;
await w2.loadURL(`${standardScheme}://host3`);
const zoomLevel1 = w.webContents.zoomLevel;
expect(zoomLevel1).to.equal(hostZoomMap.host3);
const zoomLevel2 = w2.webContents.zoomLevel;
expect(zoomLevel1).to.equal(zoomLevel2);
});
it('cannot propagate zoom level across different session', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
const w2 = new BrowserWindow({
show: false,
webPreferences: {
partition: 'temp'
}
});
const protocol = w2.webContents.session.protocol;
protocol.registerStringProtocol(standardScheme, (request, callback) => {
callback('hello');
});
defer(() => {
w2.setClosable(true);
w2.close();
protocol.unregisterProtocol(standardScheme);
});
await w.loadURL(`${standardScheme}://host3`);
w.webContents.zoomLevel = hostZoomMap.host3;
await w2.loadURL(`${standardScheme}://host3`);
const zoomLevel1 = w.webContents.zoomLevel;
expect(zoomLevel1).to.equal(hostZoomMap.host3);
const zoomLevel2 = w2.webContents.zoomLevel;
expect(zoomLevel2).to.equal(0);
expect(zoomLevel1).to.not.equal(zoomLevel2);
});
it('can persist when it contains iframe', (done) => {
const w = new BrowserWindow({ show: false });
const server = http.createServer((req, res) => {
setTimeout(200).then(() => {
res.end();
});
});
listen(server).then(({ url }) => {
const content = `<iframe src=${url}></iframe>`;
w.webContents.on('did-frame-finish-load', (e, isMainFrame) => {
if (!isMainFrame) {
try {
const zoomLevel = w.webContents.zoomLevel;
expect(zoomLevel).to.equal(2.0);
w.webContents.zoomLevel = 0;
done();
} catch (e) {
done(e);
} finally {
server.close();
}
}
});
w.webContents.on('dom-ready', () => {
w.webContents.zoomLevel = 2.0;
});
w.loadURL(`data:text/html,${content}`);
});
});
it('cannot propagate when used with webframe', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const w2 = new BrowserWindow({ show: false });
const temporaryZoomSet = once(ipcMain, 'temporary-zoom-set');
w.loadFile(path.join(fixturesPath, 'pages', 'webframe-zoom.html'));
await temporaryZoomSet;
const finalZoomLevel = w.webContents.getZoomLevel();
await w2.loadFile(path.join(fixturesPath, 'pages', 'c.html'));
const zoomLevel1 = w.webContents.zoomLevel;
const zoomLevel2 = w2.webContents.zoomLevel;
w2.setClosable(true);
w2.close();
expect(zoomLevel1).to.equal(finalZoomLevel);
expect(zoomLevel2).to.equal(0);
expect(zoomLevel1).to.not.equal(zoomLevel2);
});
describe('with unique domains', () => {
let server: http.Server;
let serverUrl: string;
let crossSiteUrl: string;
before(async () => {
server = http.createServer((req, res) => {
setTimeout().then(() => res.end('hey'));
});
serverUrl = (await listen(server)).url;
crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
});
after(() => {
server.close();
});
it('cannot persist zoom level after navigation with webFrame', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const source = `
const {ipcRenderer, webFrame} = require('electron')
webFrame.setZoomLevel(0.6)
ipcRenderer.send('zoom-level-set', webFrame.getZoomLevel())
`;
const zoomLevelPromise = once(ipcMain, 'zoom-level-set');
await w.loadURL(serverUrl);
await w.webContents.executeJavaScript(source);
let [, zoomLevel] = await zoomLevelPromise;
expect(zoomLevel).to.equal(0.6);
const loadPromise = once(w.webContents, 'did-finish-load');
await w.loadURL(crossSiteUrl);
await loadPromise;
zoomLevel = w.webContents.zoomLevel;
expect(zoomLevel).to.equal(0);
});
});
});
describe('webrtc ip policy api', () => {
afterEach(closeAllWindows);
it('can set and get webrtc ip policies', () => {
const w = new BrowserWindow({ show: false });
const policies = [
'default',
'default_public_interface_only',
'default_public_and_private_interfaces',
'disable_non_proxied_udp'
] as const;
for (const policy of policies) {
w.webContents.setWebRTCIPHandlingPolicy(policy);
expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy);
}
});
});
describe('webrtc udp port range policy api', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
it('check default webrtc udp port range is { min: 0, max: 0 }', () => {
const settings = w.webContents.getWebRTCUDPPortRange();
expect(settings).to.deep.equal({ min: 0, max: 0 });
});
it('can set and get webrtc udp port range policy with correct arguments', () => {
w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65535 });
const settings = w.webContents.getWebRTCUDPPortRange();
expect(settings).to.deep.equal({ min: 1, max: 65535 });
});
it('can not set webrtc udp port range policy with invalid arguments', () => {
expect(() => {
w.webContents.setWebRTCUDPPortRange({ min: 0, max: 65535 });
}).to.throw("'min' and 'max' must be in the (0, 65535] range or [0, 0]");
expect(() => {
w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65536 });
}).to.throw("'min' and 'max' must be in the (0, 65535] range or [0, 0]");
expect(() => {
w.webContents.setWebRTCUDPPortRange({ min: 60000, max: 56789 });
}).to.throw("'max' must be greater than or equal to 'min'");
});
it('can reset webrtc udp port range policy to default with { min: 0, max: 0 }', () => {
w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65535 });
const settings = w.webContents.getWebRTCUDPPortRange();
expect(settings).to.deep.equal({ min: 1, max: 65535 });
w.webContents.setWebRTCUDPPortRange({ min: 0, max: 0 });
const defaultSetting = w.webContents.getWebRTCUDPPortRange();
expect(defaultSetting).to.deep.equal({ min: 0, max: 0 });
});
});
describe('opener api', () => {
afterEach(closeAllWindows);
it('can get opener with window.open()', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>;
w.webContents.executeJavaScript('window.open("about:blank")', true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame);
});
it('has no opener when using "noopener"', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>;
w.webContents.executeJavaScript('window.open("about:blank", undefined, "noopener")', true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.be.null();
});
it('can get opener with a[target=_blank][rel=opener]', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>;
w.webContents.executeJavaScript(`(function() {
const a = document.createElement('a');
a.target = '_blank';
a.rel = 'opener';
a.href = 'about:blank';
a.click();
}())`, true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame);
});
it('has no opener with a[target=_blank][rel=noopener]', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>;
w.webContents.executeJavaScript(`(function() {
const a = document.createElement('a');
a.target = '_blank';
a.rel = 'noopener';
a.href = 'about:blank';
a.click();
}())`, true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.be.null();
});
});
describe('render view deleted events', () => {
let server: http.Server;
let serverUrl: string;
let crossSiteUrl: string;
before(async () => {
server = http.createServer((req, res) => {
const respond = () => {
if (req.url === '/redirect-cross-site') {
res.setHeader('Location', `${crossSiteUrl}/redirected`);
res.statusCode = 302;
res.end();
} else if (req.url === '/redirected') {
res.end('<html><script>window.localStorage</script></html>');
} else if (req.url === '/first-window-open') {
res.end(`<html><script>window.open('${serverUrl}/second-window-open', 'first child');</script></html>`);
} else if (req.url === '/second-window-open') {
res.end('<html><script>window.open(\'wrong://url\', \'second child\');</script></html>');
} else {
res.end();
}
};
setTimeout().then(respond);
});
serverUrl = (await listen(server)).url;
crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
});
after(() => {
server.close();
});
afterEach(closeAllWindows);
it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => {
const w = new BrowserWindow({ show: false });
let currentRenderViewDeletedEmitted = false;
const renderViewDeletedHandler = () => {
currentRenderViewDeletedEmitted = true;
};
w.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler);
w.webContents.on('did-finish-load', () => {
w.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler);
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.loadURL(`${serverUrl}/redirect-cross-site`);
await destroyed;
expect(currentRenderViewDeletedEmitted).to.be.false('current-render-view-deleted was emitted');
});
it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => {
const parentWindow = new BrowserWindow({ show: false });
let currentRenderViewDeletedEmitted = false;
let childWindow: BrowserWindow | null = null;
const destroyed = once(parentWindow.webContents, 'destroyed');
const renderViewDeletedHandler = () => {
currentRenderViewDeletedEmitted = true;
};
const childWindowCreated = new Promise<void>((resolve) => {
app.once('browser-window-created', (event, window) => {
childWindow = window;
window.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler);
resolve();
});
});
parentWindow.loadURL(`${serverUrl}/first-window-open`);
await childWindowCreated;
childWindow!.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler);
parentWindow.close();
await destroyed;
expect(currentRenderViewDeletedEmitted).to.be.false('child window was destroyed');
});
it('emits current-render-view-deleted if the current RVHs are deleted', async () => {
const w = new BrowserWindow({ show: false });
let currentRenderViewDeletedEmitted = false;
w.webContents.on('current-render-view-deleted' as any, () => {
currentRenderViewDeletedEmitted = true;
});
w.webContents.on('did-finish-load', () => {
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.loadURL(`${serverUrl}/redirect-cross-site`);
await destroyed;
expect(currentRenderViewDeletedEmitted).to.be.true('current-render-view-deleted wasn\'t emitted');
});
it('emits render-view-deleted if any RVHs are deleted', async () => {
const w = new BrowserWindow({ show: false });
let rvhDeletedCount = 0;
w.webContents.on('render-view-deleted' as any, () => {
rvhDeletedCount++;
});
w.webContents.on('did-finish-load', () => {
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.loadURL(`${serverUrl}/redirect-cross-site`);
await destroyed;
const expectedRenderViewDeletedEventCount = 1;
expect(rvhDeletedCount).to.equal(expectedRenderViewDeletedEventCount, 'render-view-deleted wasn\'t emitted the expected nr. of times');
});
});
describe('setIgnoreMenuShortcuts(ignore)', () => {
afterEach(closeAllWindows);
it('does not throw', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.webContents.setIgnoreMenuShortcuts(true);
w.webContents.setIgnoreMenuShortcuts(false);
}).to.not.throw();
});
});
const crashPrefs = [
{
nodeIntegration: true
},
{
sandbox: true
}
];
const nicePrefs = (o: any) => {
let s = '';
for (const key of Object.keys(o)) {
s += `${key}=${o[key]}, `;
}
return `(${s.slice(0, s.length - 2)})`;
};
for (const prefs of crashPrefs) {
describe(`crash with webPreferences ${nicePrefs(prefs)}`, () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
it('isCrashed() is false by default', () => {
expect(w.webContents.isCrashed()).to.equal(false);
});
it('forcefullyCrashRenderer() crashes the process with reason=killed||crashed', async () => {
expect(w.webContents.isCrashed()).to.equal(false);
const crashEvent = once(w.webContents, 'render-process-gone') as Promise<[any, Electron.RenderProcessGoneDetails]>;
w.webContents.forcefullyCrashRenderer();
const [, details] = await crashEvent;
expect(details.reason === 'killed' || details.reason === 'crashed').to.equal(true, 'reason should be killed || crashed');
expect(w.webContents.isCrashed()).to.equal(true);
});
it('a crashed process is recoverable with reload()', async () => {
expect(w.webContents.isCrashed()).to.equal(false);
w.webContents.forcefullyCrashRenderer();
w.webContents.reload();
expect(w.webContents.isCrashed()).to.equal(false);
});
});
}
// Destroying webContents in its event listener is going to crash when
// Electron is built in Debug mode.
describe('destroy()', () => {
let server: http.Server;
let serverUrl: string;
before((done) => {
server = http.createServer((request, response) => {
switch (request.url) {
case '/net-error':
response.destroy();
break;
case '/200':
response.end();
break;
default:
done('unsupported endpoint');
}
});
listen(server).then(({ url }) => {
serverUrl = url;
done();
});
});
after(() => {
server.close();
});
const events = [
{ name: 'did-start-loading', url: '/200' },
{ name: 'dom-ready', url: '/200' },
{ name: 'did-stop-loading', url: '/200' },
{ name: 'did-finish-load', url: '/200' },
// FIXME: Multiple Emit calls inside an observer assume that object
// will be alive till end of the observer. Synchronous `destroy` api
// violates this contract and crashes.
{ name: 'did-frame-finish-load', url: '/200' },
{ name: 'did-fail-load', url: '/net-error' }
];
for (const e of events) {
it(`should not crash when invoked synchronously inside ${e.name} handler`, async function () {
// This test is flaky on Windows CI and we don't know why, but the
// purpose of this test is to make sure Electron does not crash so it
// is fine to retry this test for a few times.
this.retries(3);
const contents = (webContents as typeof ElectronInternal.WebContents).create();
const originalEmit = contents.emit.bind(contents);
contents.emit = (...args) => { return originalEmit(...args); };
contents.once(e.name as any, () => contents.destroy());
const destroyed = once(contents, 'destroyed');
contents.loadURL(serverUrl + e.url);
await destroyed;
});
}
});
describe('did-change-theme-color event', () => {
afterEach(closeAllWindows);
it('is triggered with correct theme color', (done) => {
const w = new BrowserWindow({ show: true });
let count = 0;
w.webContents.on('did-change-theme-color', (e, color) => {
try {
if (count === 0) {
count += 1;
expect(color).to.equal('#FFEEDD');
w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
} else if (count === 1) {
expect(color).to.be.null();
done();
}
} catch (e) {
done(e);
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'theme-color.html'));
});
});
describe('console-message event', () => {
afterEach(closeAllWindows);
it('is triggered with correct log message', (done) => {
const w = new BrowserWindow({ show: true });
w.webContents.on('console-message', (e, level, message) => {
// Don't just assert as Chromium might emit other logs that we should ignore.
if (message === 'a') {
done();
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'a.html'));
});
});
describe('ipc-message event', () => {
afterEach(closeAllWindows);
it('emits when the renderer process sends an asynchronous message', async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.webContents.loadURL('about:blank');
w.webContents.executeJavaScript(`
require('electron').ipcRenderer.send('message', 'Hello World!')
`);
const [, channel, message] = await once(w.webContents, 'ipc-message');
expect(channel).to.equal('message');
expect(message).to.equal('Hello World!');
});
});
describe('ipc-message-sync event', () => {
afterEach(closeAllWindows);
it('emits when the renderer process sends a synchronous message', async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.webContents.loadURL('about:blank');
const promise: Promise<[string, string]> = new Promise(resolve => {
w.webContents.once('ipc-message-sync', (event, channel, arg) => {
event.returnValue = 'foobar';
resolve([channel, arg]);
});
});
const result = await w.webContents.executeJavaScript(`
require('electron').ipcRenderer.sendSync('message', 'Hello World!')
`);
const [channel, message] = await promise;
expect(channel).to.equal('message');
expect(message).to.equal('Hello World!');
expect(result).to.equal('foobar');
});
});
describe('referrer', () => {
afterEach(closeAllWindows);
it('propagates referrer information to new target=_blank windows', (done) => {
const w = new BrowserWindow({ show: false });
const server = http.createServer((req, res) => {
if (req.url === '/should_have_referrer') {
try {
expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`);
return done();
} catch (e) {
return done(e);
} finally {
server.close();
}
}
res.end('<a id="a" href="/should_have_referrer" target="_blank">link</a>');
});
listen(server).then(({ url }) => {
w.webContents.once('did-finish-load', () => {
w.webContents.setWindowOpenHandler(details => {
expect(details.referrer.url).to.equal(url + '/');
expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin');
return { action: 'allow' };
});
w.webContents.executeJavaScript('a.click()');
});
w.loadURL(url);
});
});
it('propagates referrer information to windows opened with window.open', (done) => {
const w = new BrowserWindow({ show: false });
const server = http.createServer((req, res) => {
if (req.url === '/should_have_referrer') {
try {
expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`);
return done();
} catch (e) {
return done(e);
}
}
res.end('');
});
listen(server).then(({ url }) => {
w.webContents.once('did-finish-load', () => {
w.webContents.setWindowOpenHandler(details => {
expect(details.referrer.url).to.equal(url + '/');
expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin');
return { action: 'allow' };
});
w.webContents.executeJavaScript('window.open(location.href + "should_have_referrer")');
});
w.loadURL(url);
});
});
});
describe('webframe messages in sandboxed contents', () => {
afterEach(closeAllWindows);
it('responds to executeJavaScript', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const result = await w.webContents.executeJavaScript('37 + 5');
expect(result).to.equal(42);
});
});
describe('preload-error event', () => {
afterEach(closeAllWindows);
const generateSpecs = (description: string, sandbox: boolean) => {
describe(description, () => {
it('is triggered when unhandled exception is thrown', async () => {
const preload = path.join(fixturesPath, 'module', 'preload-error-exception.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload
}
});
const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>;
w.loadURL('about:blank');
const [, preloadPath, error] = await promise;
expect(preloadPath).to.equal(preload);
expect(error.message).to.equal('Hello World!');
});
it('is triggered on syntax errors', async () => {
const preload = path.join(fixturesPath, 'module', 'preload-error-syntax.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload
}
});
const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>;
w.loadURL('about:blank');
const [, preloadPath, error] = await promise;
expect(preloadPath).to.equal(preload);
expect(error.message).to.equal('foobar is not defined');
});
it('is triggered when preload script loading fails', async () => {
const preload = path.join(fixturesPath, 'module', 'preload-invalid.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload
}
});
const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>;
w.loadURL('about:blank');
const [, preloadPath, error] = await promise;
expect(preloadPath).to.equal(preload);
expect(error.message).to.contain('preload-invalid.js');
});
});
};
generateSpecs('without sandbox', false);
generateSpecs('with sandbox', true);
});
describe('takeHeapSnapshot()', () => {
afterEach(closeAllWindows);
it('works with sandboxed renderers', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
await w.loadURL('about:blank');
const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot');
const cleanup = () => {
try {
fs.unlinkSync(filePath);
} catch {
// ignore error
}
};
try {
await w.webContents.takeHeapSnapshot(filePath);
const stats = fs.statSync(filePath);
expect(stats.size).not.to.be.equal(0);
} finally {
cleanup();
}
});
it('fails with invalid file path', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
await w.loadURL('about:blank');
const badPath = path.join('i', 'am', 'a', 'super', 'bad', 'path');
const promise = w.webContents.takeHeapSnapshot(badPath);
return expect(promise).to.be.eventually.rejectedWith(Error, `Failed to take heap snapshot with invalid file path ${badPath}`);
});
it('fails with invalid render process', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot');
w.webContents.destroy();
const promise = w.webContents.takeHeapSnapshot(filePath);
return expect(promise).to.be.eventually.rejectedWith(Error, 'Failed to take heap snapshot with nonexistent render frame');
});
});
describe('setBackgroundThrottling()', () => {
afterEach(closeAllWindows);
it('does not crash when allowing', () => {
const w = new BrowserWindow({ show: false });
w.webContents.setBackgroundThrottling(true);
});
it('does not crash when called via BrowserWindow', () => {
const w = new BrowserWindow({ show: false });
w.setBackgroundThrottling(true);
});
it('does not crash when disallowing', () => {
const w = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: true } });
w.webContents.setBackgroundThrottling(false);
});
});
describe('getBackgroundThrottling()', () => {
afterEach(closeAllWindows);
it('works via getter', () => {
const w = new BrowserWindow({ show: false });
w.webContents.setBackgroundThrottling(false);
expect(w.webContents.getBackgroundThrottling()).to.equal(false);
w.webContents.setBackgroundThrottling(true);
expect(w.webContents.getBackgroundThrottling()).to.equal(true);
});
it('works via property', () => {
const w = new BrowserWindow({ show: false });
w.webContents.backgroundThrottling = false;
expect(w.webContents.backgroundThrottling).to.equal(false);
w.webContents.backgroundThrottling = true;
expect(w.webContents.backgroundThrottling).to.equal(true);
});
it('works via BrowserWindow', () => {
const w = new BrowserWindow({ show: false });
w.setBackgroundThrottling(false);
expect(w.getBackgroundThrottling()).to.equal(false);
w.setBackgroundThrottling(true);
expect(w.getBackgroundThrottling()).to.equal(true);
});
});
ifdescribe(features.isPrintingEnabled())('getPrintersAsync()', () => {
afterEach(closeAllWindows);
it('can get printer list', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const printers = await w.webContents.getPrintersAsync();
expect(printers).to.be.an('array');
});
});
ifdescribe(features.isPrintingEnabled())('printToPDF()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
});
afterEach(closeAllWindows);
it('rejects on incorrectly typed parameters', async () => {
const badTypes = {
landscape: [],
displayHeaderFooter: '123',
printBackground: 2,
scale: 'not-a-number',
pageSize: 'IAmAPageSize',
margins: 'terrible',
pageRanges: { oops: 'im-not-the-right-key' },
headerTemplate: [1, 2, 3],
footerTemplate: [4, 5, 6],
preferCSSPageSize: 'no'
};
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
// These will hard crash in Chromium unless we type-check
for (const [key, value] of Object.entries(badTypes)) {
const param = { [key]: value };
await expect(w.webContents.printToPDF(param)).to.eventually.be.rejected();
}
});
it('does not crash when called multiple times in parallel', async () => {
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
const promises = [];
for (let i = 0; i < 3; i++) {
promises.push(w.webContents.printToPDF({}));
}
const results = await Promise.all(promises);
for (const data of results) {
expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
}
});
it('does not crash when called multiple times in sequence', async () => {
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
const results = [];
for (let i = 0; i < 3; i++) {
const result = await w.webContents.printToPDF({});
results.push(result);
}
for (const data of results) {
expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
}
});
it('can print a PDF with default settings', async () => {
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
const data = await w.webContents.printToPDF({});
expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
});
type PageSizeString = Exclude<Required<Electron.PrintToPDFOptions>['pageSize'], Electron.Size>;
it('with custom page sizes', async () => {
const paperFormats: Record<PageSizeString, ElectronInternal.PageSize> = {
Letter: { width: 8.5, height: 11 },
Legal: { width: 8.5, height: 14 },
Tabloid: { width: 11, height: 17 },
Ledger: { width: 17, height: 11 },
A0: { width: 33.1, height: 46.8 },
A1: { width: 23.4, height: 33.1 },
A2: { width: 16.54, height: 23.4 },
A3: { width: 11.7, height: 16.54 },
A4: { width: 8.27, height: 11.7 },
A5: { width: 5.83, height: 8.27 },
A6: { width: 4.13, height: 5.83 }
};
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
for (const format of Object.keys(paperFormats) as PageSizeString[]) {
const data = await w.webContents.printToPDF({ pageSize: format });
const doc = await pdfjs.getDocument(data).promise;
const page = await doc.getPage(1);
// page.view is [top, left, width, height].
const width = page.view[2] / 72;
const height = page.view[3] / 72;
const approxEq = (a: number, b: number, epsilon = 0.01) => Math.abs(a - b) <= epsilon;
expect(approxEq(width, paperFormats[format].width)).to.be.true();
expect(approxEq(height, paperFormats[format].height)).to.be.true();
}
});
it('with custom header and footer', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
const data = await w.webContents.printToPDF({
displayHeaderFooter: true,
headerTemplate: '<div>I\'m a PDF header</div>',
footerTemplate: '<div>I\'m a PDF footer</div>'
});
const doc = await pdfjs.getDocument(data).promise;
const page = await doc.getPage(1);
const { items } = await page.getTextContent();
// Check that generated PDF contains a header.
const containsText = (text: RegExp) => items.some(({ str }: { str: string }) => str.match(text));
expect(containsText(/I'm a PDF header/)).to.be.true();
expect(containsText(/I'm a PDF footer/)).to.be.true();
});
it('in landscape mode', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
const data = await w.webContents.printToPDF({ landscape: true });
const doc = await pdfjs.getDocument(data).promise;
const page = await doc.getPage(1);
// page.view is [top, left, width, height].
const width = page.view[2];
const height = page.view[3];
expect(width).to.be.greaterThan(height);
});
it('with custom page ranges', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-large.html'));
const data = await w.webContents.printToPDF({
pageRanges: '1-3',
landscape: true
});
const doc = await pdfjs.getDocument(data).promise;
// Check that correct # of pages are rendered.
expect(doc.numPages).to.equal(3);
});
it('does not tag PDFs by default', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
const data = await w.webContents.printToPDF({});
const doc = await pdfjs.getDocument(data).promise;
const markInfo = await doc.getMarkInfo();
expect(markInfo).to.be.null();
});
it('can generate tag data for PDFs', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
const data = await w.webContents.printToPDF({ generateTaggedPDF: true });
const doc = await pdfjs.getDocument(data).promise;
const markInfo = await doc.getMarkInfo();
expect(markInfo).to.deep.equal({
Marked: true,
UserProperties: false,
Suspects: false
});
});
});
describe('PictureInPicture video', () => {
afterEach(closeAllWindows);
it('works as expected', async function () {
const w = new BrowserWindow({ webPreferences: { sandbox: true } });
// TODO(codebytere): figure out why this workaround is needed and remove.
// It is not germane to the actual test.
await w.loadFile(path.join(fixturesPath, 'blank.html'));
await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html'));
await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')', true);
const result = await w.webContents.executeJavaScript('runTest(true)', true);
expect(result).to.be.true();
});
});
describe('Shared Workers', () => {
afterEach(closeAllWindows);
it('can get multiple shared workers', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const ready = once(ipcMain, 'ready');
w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html'));
await ready;
const sharedWorkers = w.webContents.getAllSharedWorkers();
expect(sharedWorkers).to.have.lengthOf(2);
expect(sharedWorkers[0].url).to.contain('shared-worker');
expect(sharedWorkers[1].url).to.contain('shared-worker');
});
it('can inspect a specific shared worker', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const ready = once(ipcMain, 'ready');
w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html'));
await ready;
const sharedWorkers = w.webContents.getAllSharedWorkers();
const devtoolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.inspectSharedWorkerById(sharedWorkers[0].id);
await devtoolsOpened;
const devtoolsClosed = once(w.webContents, 'devtools-closed');
w.webContents.closeDevTools();
await devtoolsClosed;
});
});
describe('login event', () => {
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
let serverPort: number;
let proxyServer: http.Server;
let proxyServerPort: number;
before(async () => {
server = http.createServer((request, response) => {
if (request.url === '/no-auth') {
return response.end('ok');
}
if (request.headers.authorization) {
response.writeHead(200, { 'Content-type': 'text/plain' });
return response.end(request.headers.authorization);
}
response
.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' })
.end('401');
});
({ port: serverPort, url: serverUrl } = await listen(server));
});
before(async () => {
proxyServer = http.createServer((request, response) => {
if (request.headers['proxy-authorization']) {
response.writeHead(200, { 'Content-type': 'text/plain' });
return response.end(request.headers['proxy-authorization']);
}
response
.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' })
.end();
});
proxyServerPort = (await listen(proxyServer)).port;
});
afterEach(async () => {
await session.defaultSession.clearAuthCache();
});
after(() => {
server.close();
proxyServer.close();
});
it('is emitted when navigating', async () => {
const [user, pass] = ['user', 'pass'];
const w = new BrowserWindow({ show: false });
let eventRequest: any;
let eventAuthInfo: any;
w.webContents.on('login', (event, request, authInfo, cb) => {
eventRequest = request;
eventAuthInfo = authInfo;
event.preventDefault();
cb(user, pass);
});
await w.loadURL(serverUrl);
const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`);
expect(eventRequest.url).to.equal(serverUrl + '/');
expect(eventAuthInfo.isProxy).to.be.false();
expect(eventAuthInfo.scheme).to.equal('basic');
expect(eventAuthInfo.host).to.equal('127.0.0.1');
expect(eventAuthInfo.port).to.equal(serverPort);
expect(eventAuthInfo.realm).to.equal('Foo');
});
it('is emitted when a proxy requests authorization', async () => {
const customSession = session.fromPartition(`${Math.random()}`);
await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' });
const [user, pass] = ['user', 'pass'];
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
let eventRequest: any;
let eventAuthInfo: any;
w.webContents.on('login', (event, request, authInfo, cb) => {
eventRequest = request;
eventAuthInfo = authInfo;
event.preventDefault();
cb(user, pass);
});
await w.loadURL(`${serverUrl}/no-auth`);
const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`);
expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`);
expect(eventAuthInfo.isProxy).to.be.true();
expect(eventAuthInfo.scheme).to.equal('basic');
expect(eventAuthInfo.host).to.equal('127.0.0.1');
expect(eventAuthInfo.port).to.equal(proxyServerPort);
expect(eventAuthInfo.realm).to.equal('Foo');
});
it('cancels authentication when callback is called with no arguments', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.on('login', (event, request, authInfo, cb) => {
event.preventDefault();
cb();
});
await w.loadURL(serverUrl);
const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
expect(body).to.equal('401');
});
});
describe('page-title-updated event', () => {
afterEach(closeAllWindows);
it('is emitted with a full title for pages with no navigation', async () => {
const bw = new BrowserWindow({ show: false });
await bw.loadURL('about:blank');
bw.webContents.executeJavaScript('child = window.open("", "", "show=no"); null');
const [, child] = await once(app, 'web-contents-created') as [any, WebContents];
bw.webContents.executeJavaScript('child.document.title = "new title"');
const [, title] = await once(child, 'page-title-updated') as [any, string];
expect(title).to.equal('new title');
});
});
describe('crashed event', () => {
afterEach(() => deprecate.setHandler(null));
it('does not crash main process when destroying WebContents in it', (done) => {
const contents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true });
contents.once('crashed', () => {
contents.destroy();
done();
});
contents.loadURL('about:blank').then(() => contents.forcefullyCrashRenderer());
});
it('logs a warning', async () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true });
await contents.loadURL('about:blank');
const messages: string[] = [];
deprecate.setHandler(message => messages.push(message));
const crashEvent = once(contents, 'crashed');
contents.forcefullyCrashRenderer();
const [, killed] = await crashEvent;
expect(killed).to.be.a('boolean');
expect(messages).to.deep.equal(['\'crashed event\' is deprecated and will be removed. Please use \'render-process-gone event\' instead.']);
});
});
describe('context-menu event', () => {
afterEach(closeAllWindows);
it('emits when right-clicked in page', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const promise = once(w.webContents, 'context-menu') as Promise<[any, Electron.ContextMenuParams]>;
// Simulate right-click to create context-menu event.
const opts = { x: 0, y: 0, button: 'right' as const };
w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' });
w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' });
const [, params] = await promise;
expect(params.pageURL).to.equal(w.webContents.getURL());
expect(params.frame).to.be.an('object');
expect(params.x).to.be.a('number');
expect(params.y).to.be.a('number');
});
});
describe('close() method', () => {
afterEach(closeAllWindows);
it('closes when close() is called', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
const destroyed = once(w, 'destroyed');
w.close();
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
it('closes when close() is called after loading a page', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
const destroyed = once(w, 'destroyed');
w.close();
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
it('can be GCed before loading a page', async () => {
const v8Util = process._linkedBinding('electron_common_v8_util');
let registry: FinalizationRegistry<unknown> | null = null;
const cleanedUp = new Promise<number>(resolve => {
registry = new FinalizationRegistry(resolve as any);
});
(() => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
registry!.register(w, 42);
})();
const i = setInterval(() => v8Util.requestGarbageCollectionForTesting(), 100);
defer(() => clearInterval(i));
expect(await cleanedUp).to.equal(42);
});
it('causes its parent browserwindow to be closed', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const closed = once(w, 'closed');
w.webContents.close();
await closed;
expect(w.isDestroyed()).to.be.true();
});
it('ignores beforeunload if waitForBeforeUnload not specified', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
w.on('will-prevent-unload', () => { throw new Error('unexpected will-prevent-unload'); });
const destroyed = once(w, 'destroyed');
w.close();
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
it('runs beforeunload if waitForBeforeUnload is specified', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
const willPreventUnload = once(w, 'will-prevent-unload');
w.close({ waitForBeforeUnload: true });
await willPreventUnload;
expect(w.isDestroyed()).to.be.false();
});
it('overriding beforeunload prevention results in webcontents close', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
w.once('will-prevent-unload', e => e.preventDefault());
const destroyed = once(w, 'destroyed');
w.close({ waitForBeforeUnload: true });
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
});
describe('content-bounds-updated event', () => {
afterEach(closeAllWindows);
it('emits when moveTo is called', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('window.moveTo(100, 100)', true);
const [, rect] = await once(w.webContents, 'content-bounds-updated') as [any, Electron.Rectangle];
const { width, height } = w.getBounds();
expect(rect).to.deep.equal({
x: 100,
y: 100,
width,
height
});
await new Promise(setImmediate);
expect(w.getBounds().x).to.equal(100);
expect(w.getBounds().y).to.equal(100);
});
it('emits when resizeTo is called', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('window.resizeTo(100, 100)', true);
const [, rect] = await once(w.webContents, 'content-bounds-updated') as [any, Electron.Rectangle];
const { x, y } = w.getBounds();
expect(rect).to.deep.equal({
x,
y,
width: 100,
height: 100
});
await new Promise(setImmediate);
expect({
width: w.getBounds().width,
height: w.getBounds().height
}).to.deep.equal(process.platform === 'win32' ? {
// The width is reported as being larger on Windows? I'm not sure why
// this is.
width: 136,
height: 100
} : {
width: 100,
height: 100
});
});
it('does not change window bounds if cancelled', async () => {
const w = new BrowserWindow({ show: false });
const { width, height } = w.getBounds();
w.loadURL('about:blank');
w.webContents.once('content-bounds-updated', e => e.preventDefault());
await w.webContents.executeJavaScript('window.resizeTo(100, 100)', true);
await new Promise(setImmediate);
expect(w.getBounds().width).to.equal(width);
expect(w.getBounds().height).to.equal(height);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 31,992 |
[Bug]: webContents.capturePage() returns empty image for fully occluded BrowserWindow on 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 feature request that matches the one I want to file, without success.
### Electron Version
16.0.1
### What operating system are you using?
Windows
### Operating System Version
Windows 11 (10.0.22000.348)
### What arch are you using?
x64
### Last Known Working Electron version
10.4.7
### Expected Behavior
`webContents.capturePage()` should work for fully occluded BrowserWindow as the window is not minimized.
### Actual Behavior
`webContents.capturePage()` returns an empty `NativeImage` in this case.
### Testcase Gist URL
_No response_
### Additional Information
main.js for Fiddle
```js
const {app, BrowserWindow} = require('electron')
function createWindow () {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
})
setInterval(async () => {
const image = await mainWindow.capturePage();
console.log(image.getSize())
}, 1000);
mainWindow.loadFile('about:blank')
mainWindow.webContents.openDevTools({mode:'detach'})
}
app.whenReady().then(() => {
createWindow()
})
app.on('window-all-closed', function () {
app.quit()
})
```
to reproduce cover the BrowserWindow with the devtools, you'll see the image size being logged as `{ width: 0, height: 0 }`.
This is a regression from #27883, when I revert the change `webContents.capturePage()` is working correctly for occluded windows. Checking the visibility state does not seem correct to me as both occluded and minimized windows' webContents have visibilityState hidden.
The abandoned fix #27892 seems like a better option. Also according to the documentation of `CopyFromSurface`:
> // |callback| is guaranteed to be run, either synchronously or at some point
> // in the future (depending on the platform implementation and the current
> // state of the Surface). If the copy failed, the bitmap's drawsNothing()
> // method will return true.
> //
> // If the view's renderer is suspended (see WasOccluded()), this may result in
> // copying old data or failing.
> virtual void CopyFromSurface(
> const gfx::Rect& src_rect,
> const gfx::Size& output_size,
> base::OnceCallback<void(const SkBitmap&)> callback) = 0;
|
https://github.com/electron/electron/issues/31992
|
https://github.com/electron/electron/pull/39730
|
3e70692e4b3044a10e5b1e5148a97a3f62bec4cb
|
5c821d33791345446eef3a90a6bea9c920d001d8
| 2021-11-25T03:07:41Z |
c++
| 2023-10-12T07:35:23Z |
shell/browser/api/electron_api_web_contents.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_web_contents.h"
#include <limits>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/containers/contains.h"
#include "base/containers/fixed_flat_map.h"
#include "base/containers/id_map.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/current_thread.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
#include "chrome/browser/ui/views/eye_dropper/eye_dropper.h"
#include "chrome/common/pref_names.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/security_state/content/content_utils.h"
#include "components/security_state/core/security_state.h"
#include "content/browser/renderer_host/frame_tree_node.h" // nogncheck
#include "content/browser/renderer_host/navigation_controller_impl.h" // nogncheck
#include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/desktop_media_id.h"
#include "content/public/browser/desktop_streams_registry.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/service_worker_context.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/input/native_web_keyboard_event.h"
#include "content/public/common/referrer_type_converters.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/webplugininfo.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "gin/arguments.h"
#include "gin/data_object_builder.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "media/base/mime_util.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "ppapi/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "printing/print_job_constants.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/browser/api/electron_api_browser_window.h"
#include "shell/browser/api/electron_api_debugger.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/api/electron_api_web_frame_main.h"
#include "shell/browser/api/message_port.h"
#include "shell/browser/browser.h"
#include "shell/browser/child_web_contents_tracker.h"
#include "shell/browser/electron_autofill_driver_factory.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/electron_javascript_dialog_manager.h"
#include "shell/browser/electron_navigation_throttle.h"
#include "shell/browser/file_select_helper.h"
#include "shell/browser/native_window.h"
#include "shell/browser/osr/osr_render_widget_host_view.h"
#include "shell/browser/osr/osr_web_contents_view.h"
#include "shell/browser/session_preferences.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/file_dialog.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/browser/web_contents_zoom_controller.h"
#include "shell/browser/web_view_guest_delegate.h"
#include "shell/browser/web_view_manager.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/color_util.h"
#include "shell/common/electron_constants.h"
#include "shell/common/gin_converters/base_converter.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/content_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/frame_converter.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/optional_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/language_util.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "shell/common/thread_restrictions.h"
#include "shell/common/v8_value_serializer.h"
#include "storage/browser/file_system/isolated_context.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/mojom/frame/find_in_page.mojom.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h"
#include "third_party/blink/public/mojom/renderer_preferences.mojom.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
#if BUILDFLAG(IS_WIN)
#include "shell/browser/native_window_views.h"
#endif
#if !BUILDFLAG(IS_MAC)
#include "ui/aura/window.h"
#else
#include "ui/base/cocoa/defaults_utils.h"
#endif
#if BUILDFLAG(IS_LINUX)
#include "ui/linux/linux_ui.h"
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
#include "ui/gfx/font_render_params.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/script_executor.h"
#include "extensions/browser/view_type_utils.h"
#include "extensions/common/mojom/view_type.mojom.h"
#include "shell/browser/extensions/electron_extension_web_contents_observer.h"
#endif
#if BUILDFLAG(ENABLE_PRINTING)
#include "chrome/browser/printing/print_view_manager_base.h"
#include "components/printing/browser/print_manager_utils.h"
#include "components/printing/browser/print_to_pdf/pdf_print_result.h"
#include "components/printing/browser/print_to_pdf/pdf_print_utils.h"
#include "printing/backend/print_backend.h" // nogncheck
#include "printing/mojom/print.mojom.h" // nogncheck
#include "printing/page_range.h"
#include "shell/browser/printing/print_view_manager_electron.h"
#if BUILDFLAG(IS_WIN)
#include "printing/backend/win_helper.h"
#endif
#endif // BUILDFLAG(ENABLE_PRINTING)
#if BUILDFLAG(ENABLE_PDF_VIEWER)
#include "components/pdf/browser/pdf_document_helper.h" // nogncheck
#include "shell/browser/electron_pdf_document_helper_client.h"
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/public/browser/plugin_service.h"
#endif
#if !IS_MAS_BUILD()
#include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck
#endif
namespace gin {
#if BUILDFLAG(ENABLE_PRINTING)
template <>
struct Converter<printing::mojom::MarginType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::MarginType* out) {
using Val = printing::mojom::MarginType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"custom", Val::kCustomMargins},
{"default", Val::kDefaultMargins},
{"none", Val::kNoMargins},
{"printableArea", Val::kPrintableAreaMargins},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<printing::mojom::DuplexMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::DuplexMode* out) {
using Val = printing::mojom::DuplexMode;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"longEdge", Val::kLongEdge},
{"shortEdge", Val::kShortEdge},
{"simplex", Val::kSimplex},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
#endif
template <>
struct Converter<WindowOpenDisposition> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
WindowOpenDisposition val) {
std::string disposition = "other";
switch (val) {
case WindowOpenDisposition::CURRENT_TAB:
disposition = "default";
break;
case WindowOpenDisposition::NEW_FOREGROUND_TAB:
disposition = "foreground-tab";
break;
case WindowOpenDisposition::NEW_BACKGROUND_TAB:
disposition = "background-tab";
break;
case WindowOpenDisposition::NEW_POPUP:
case WindowOpenDisposition::NEW_WINDOW:
disposition = "new-window";
break;
case WindowOpenDisposition::SAVE_TO_DISK:
disposition = "save-to-disk";
break;
default:
break;
}
return gin::ConvertToV8(isolate, disposition);
}
};
template <>
struct Converter<content::SavePageType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
content::SavePageType* out) {
using Val = content::SavePageType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"htmlcomplete", Val::SAVE_PAGE_TYPE_AS_COMPLETE_HTML},
{"htmlonly", Val::SAVE_PAGE_TYPE_AS_ONLY_HTML},
{"mhtml", Val::SAVE_PAGE_TYPE_AS_MHTML},
});
return FromV8WithLowerLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<electron::api::WebContents::Type> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
electron::api::WebContents::Type val) {
using Type = electron::api::WebContents::Type;
std::string type;
switch (val) {
case Type::kBackgroundPage:
type = "backgroundPage";
break;
case Type::kBrowserWindow:
type = "window";
break;
case Type::kBrowserView:
type = "browserView";
break;
case Type::kRemote:
type = "remote";
break;
case Type::kWebView:
type = "webview";
break;
case Type::kOffScreen:
type = "offscreen";
break;
default:
break;
}
return gin::ConvertToV8(isolate, type);
}
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::api::WebContents::Type* out) {
using Val = electron::api::WebContents::Type;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"backgroundPage", Val::kBackgroundPage},
{"browserView", Val::kBrowserView},
{"offscreen", Val::kOffScreen},
{"webview", Val::kWebView},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<scoped_refptr<content::DevToolsAgentHost>> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const scoped_refptr<content::DevToolsAgentHost>& val) {
gin_helper::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("id", val->GetId());
dict.Set("url", val->GetURL().spec());
return dict.GetHandle();
}
};
} // namespace gin
namespace electron::api {
namespace {
constexpr base::StringPiece CursorTypeToString(
ui::mojom::CursorType cursor_type) {
switch (cursor_type) {
case ui::mojom::CursorType::kPointer:
return "pointer";
case ui::mojom::CursorType::kCross:
return "crosshair";
case ui::mojom::CursorType::kHand:
return "hand";
case ui::mojom::CursorType::kIBeam:
return "text";
case ui::mojom::CursorType::kWait:
return "wait";
case ui::mojom::CursorType::kHelp:
return "help";
case ui::mojom::CursorType::kEastResize:
return "e-resize";
case ui::mojom::CursorType::kNorthResize:
return "n-resize";
case ui::mojom::CursorType::kNorthEastResize:
return "ne-resize";
case ui::mojom::CursorType::kNorthWestResize:
return "nw-resize";
case ui::mojom::CursorType::kSouthResize:
return "s-resize";
case ui::mojom::CursorType::kSouthEastResize:
return "se-resize";
case ui::mojom::CursorType::kSouthWestResize:
return "sw-resize";
case ui::mojom::CursorType::kWestResize:
return "w-resize";
case ui::mojom::CursorType::kNorthSouthResize:
return "ns-resize";
case ui::mojom::CursorType::kEastWestResize:
return "ew-resize";
case ui::mojom::CursorType::kNorthEastSouthWestResize:
return "nesw-resize";
case ui::mojom::CursorType::kNorthWestSouthEastResize:
return "nwse-resize";
case ui::mojom::CursorType::kColumnResize:
return "col-resize";
case ui::mojom::CursorType::kRowResize:
return "row-resize";
case ui::mojom::CursorType::kMiddlePanning:
return "m-panning";
case ui::mojom::CursorType::kMiddlePanningVertical:
return "m-panning-vertical";
case ui::mojom::CursorType::kMiddlePanningHorizontal:
return "m-panning-horizontal";
case ui::mojom::CursorType::kEastPanning:
return "e-panning";
case ui::mojom::CursorType::kNorthPanning:
return "n-panning";
case ui::mojom::CursorType::kNorthEastPanning:
return "ne-panning";
case ui::mojom::CursorType::kNorthWestPanning:
return "nw-panning";
case ui::mojom::CursorType::kSouthPanning:
return "s-panning";
case ui::mojom::CursorType::kSouthEastPanning:
return "se-panning";
case ui::mojom::CursorType::kSouthWestPanning:
return "sw-panning";
case ui::mojom::CursorType::kWestPanning:
return "w-panning";
case ui::mojom::CursorType::kMove:
return "move";
case ui::mojom::CursorType::kVerticalText:
return "vertical-text";
case ui::mojom::CursorType::kCell:
return "cell";
case ui::mojom::CursorType::kContextMenu:
return "context-menu";
case ui::mojom::CursorType::kAlias:
return "alias";
case ui::mojom::CursorType::kProgress:
return "progress";
case ui::mojom::CursorType::kNoDrop:
return "nodrop";
case ui::mojom::CursorType::kCopy:
return "copy";
case ui::mojom::CursorType::kNone:
return "none";
case ui::mojom::CursorType::kNotAllowed:
return "not-allowed";
case ui::mojom::CursorType::kZoomIn:
return "zoom-in";
case ui::mojom::CursorType::kZoomOut:
return "zoom-out";
case ui::mojom::CursorType::kGrab:
return "grab";
case ui::mojom::CursorType::kGrabbing:
return "grabbing";
case ui::mojom::CursorType::kCustom:
return "custom";
case ui::mojom::CursorType::kNull:
return "null";
case ui::mojom::CursorType::kDndNone:
return "drag-drop-none";
case ui::mojom::CursorType::kDndMove:
return "drag-drop-move";
case ui::mojom::CursorType::kDndCopy:
return "drag-drop-copy";
case ui::mojom::CursorType::kDndLink:
return "drag-drop-link";
case ui::mojom::CursorType::kNorthSouthNoResize:
return "ns-no-resize";
case ui::mojom::CursorType::kEastWestNoResize:
return "ew-no-resize";
case ui::mojom::CursorType::kNorthEastSouthWestNoResize:
return "nesw-no-resize";
case ui::mojom::CursorType::kNorthWestSouthEastNoResize:
return "nwse-no-resize";
default:
return "default";
}
}
base::IDMap<WebContents*>& GetAllWebContents() {
static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents;
return *s_all_web_contents;
}
void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise,
base::ScopedClosureRunner capture_handle,
const SkBitmap& bitmap) {
// Hack to enable transparency in captured image
promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap));
capture_handle.RunAndReset();
}
absl::optional<base::TimeDelta> GetCursorBlinkInterval() {
#if BUILDFLAG(IS_MAC)
absl::optional<base::TimeDelta> system_value(
ui::TextInsertionCaretBlinkPeriodFromDefaults());
if (system_value)
return *system_value;
#elif BUILDFLAG(IS_LINUX)
if (auto* linux_ui = ui::LinuxUi::instance())
return linux_ui->GetCursorBlinkInterval();
#elif BUILDFLAG(IS_WIN)
const auto system_msec = ::GetCaretBlinkTime();
if (system_msec != 0) {
return (system_msec == INFINITE) ? base::TimeDelta()
: base::Milliseconds(system_msec);
}
#endif
return absl::nullopt;
}
#if BUILDFLAG(ENABLE_PRINTING)
// This will return false if no printer with the provided device_name can be
// found on the network. We need to check this because Chromium does not do
// sanity checking of device_name validity and so will crash on invalid names.
bool IsDeviceNameValid(const std::u16string& device_name) {
#if BUILDFLAG(IS_MAC)
base::apple::ScopedCFTypeRef<CFStringRef> new_printer_id(
base::SysUTF16ToCFStringRef(device_name));
PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get());
bool printer_exists = new_printer != nullptr;
PMRelease(new_printer);
return printer_exists;
#else
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name));
#endif
}
// This function returns a validated device name.
// If the user passed one to webContents.print(), we check that it's valid and
// return it or fail if the network doesn't recognize it. If the user didn't
// pass a device name, we first try to return the system default printer. If one
// isn't set, then pull all the printers and use the first one or fail if none
// exist.
std::pair<std::string, std::u16string> GetDeviceNameToUse(
const std::u16string& device_name) {
#if BUILDFLAG(IS_WIN)
// Blocking is needed here because Windows printer drivers are oftentimes
// not thread-safe and have to be accessed on the UI thread.
ScopedAllowBlockingForElectron allow_blocking;
#endif
if (!device_name.empty()) {
if (!IsDeviceNameValid(device_name))
return std::make_pair("Invalid deviceName provided", std::u16string());
return std::make_pair(std::string(), device_name);
}
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
std::string printer_name;
printing::mojom::ResultCode code =
print_backend->GetDefaultPrinterName(printer_name);
// We don't want to return if this fails since some devices won't have a
// default printer.
if (code != printing::mojom::ResultCode::kSuccess)
LOG(ERROR) << "Failed to get default printer name";
if (printer_name.empty()) {
printing::PrinterList printers;
if (print_backend->EnumeratePrinters(printers) !=
printing::mojom::ResultCode::kSuccess)
return std::make_pair("Failed to enumerate printers", std::u16string());
if (printers.empty())
return std::make_pair("No printers available on the network",
std::u16string());
printer_name = printers.front().printer_name;
}
return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name));
}
// Copied from
// chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54
scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() {
// USER_VISIBLE because the result is displayed in the print preview dialog.
#if !BUILDFLAG(IS_WIN)
static constexpr base::TaskTraits kTraits = {
base::MayBlock(), base::TaskPriority::USER_VISIBLE};
#endif
#if defined(USE_CUPS)
// CUPS is thread safe.
return base::ThreadPool::CreateTaskRunner(kTraits);
#elif BUILDFLAG(IS_WIN)
// Windows drivers are likely not thread-safe and need to be accessed on the
// UI thread.
return content::GetUIThreadTaskRunner({base::TaskPriority::USER_VISIBLE});
#else
// Be conservative on unsupported platforms.
return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits);
#endif
}
#endif
struct UserDataLink : public base::SupportsUserData::Data {
explicit UserDataLink(base::WeakPtr<WebContents> contents)
: web_contents(contents) {}
base::WeakPtr<WebContents> web_contents;
};
const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey;
const char kRootName[] = "<root>";
struct FileSystem {
FileSystem() = default;
FileSystem(const std::string& type,
const std::string& file_system_name,
const std::string& root_url,
const std::string& file_system_path)
: type(type),
file_system_name(file_system_name),
root_url(root_url),
file_system_path(file_system_path) {}
std::string type;
std::string file_system_name;
std::string root_url;
std::string file_system_path;
};
std::string RegisterFileSystem(content::WebContents* web_contents,
const base::FilePath& path) {
auto* isolated_context = storage::IsolatedContext::GetInstance();
std::string root_name(kRootName);
storage::IsolatedContext::ScopedFSHandle file_system =
isolated_context->RegisterFileSystemForPath(
storage::kFileSystemTypeLocal, std::string(), path, &root_name);
content::ChildProcessSecurityPolicy* policy =
content::ChildProcessSecurityPolicy::GetInstance();
content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
int renderer_id = render_view_host->GetProcess()->GetID();
policy->GrantReadFileSystem(renderer_id, file_system.id());
policy->GrantWriteFileSystem(renderer_id, file_system.id());
policy->GrantCreateFileForFileSystem(renderer_id, file_system.id());
policy->GrantDeleteFromFileSystem(renderer_id, file_system.id());
if (!policy->CanReadFile(renderer_id, path))
policy->GrantReadFile(renderer_id, path);
return file_system.id();
}
FileSystem CreateFileSystemStruct(content::WebContents* web_contents,
const std::string& file_system_id,
const std::string& file_system_path,
const std::string& type) {
const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL();
std::string file_system_name =
storage::GetIsolatedFileSystemName(origin, file_system_id);
std::string root_url = storage::GetIsolatedFileSystemRootURIString(
origin, file_system_id, kRootName);
return FileSystem(type, file_system_name, root_url, file_system_path);
}
base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) {
base::Value::Dict value;
value.Set("type", file_system.type);
value.Set("fileSystemName", file_system.file_system_name);
value.Set("rootURL", file_system.root_url);
value.Set("fileSystemPath", file_system.file_system_path);
return value;
}
void WriteToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::WriteFile(path, content.data(), content.size());
}
void AppendToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::AppendToFile(path, content);
}
PrefService* GetPrefService(content::WebContents* web_contents) {
auto* context = web_contents->GetBrowserContext();
return static_cast<electron::ElectronBrowserContext*>(context)->prefs();
}
std::map<std::string, std::string> GetAddedFileSystemPaths(
content::WebContents* web_contents) {
auto* pref_service = GetPrefService(web_contents);
const base::Value::Dict& file_system_paths =
pref_service->GetDict(prefs::kDevToolsFileSystemPaths);
std::map<std::string, std::string> result;
for (auto it : file_system_paths) {
std::string type =
it.second.is_string() ? it.second.GetString() : std::string();
result[it.first] = type;
}
return result;
}
bool IsDevToolsFileSystemAdded(content::WebContents* web_contents,
const std::string& file_system_path) {
return base::Contains(GetAddedFileSystemPaths(web_contents),
file_system_path);
}
void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) {
rwhv->SetBackgroundColor(color);
static_cast<content::RenderWidgetHostViewBase*>(rwhv)
->SetContentBackgroundColor(color);
}
content::RenderFrameHost* GetRenderFrameHost(
content::NavigationHandle* navigation_handle) {
int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId();
content::FrameTreeNode* frame_tree_node =
content::FrameTreeNode::GloballyFindByID(frame_tree_node_id);
content::RenderFrameHostManager* render_manager =
frame_tree_node->render_manager();
content::RenderFrameHost* frame_host = nullptr;
if (render_manager) {
frame_host = render_manager->speculative_frame_host();
if (!frame_host)
frame_host = render_manager->current_frame_host();
}
return frame_host;
}
} // namespace
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) {
switch (view_type) {
case extensions::mojom::ViewType::kExtensionBackgroundPage:
return WebContents::Type::kBackgroundPage;
case extensions::mojom::ViewType::kAppWindow:
case extensions::mojom::ViewType::kComponent:
case extensions::mojom::ViewType::kExtensionDialog:
case extensions::mojom::ViewType::kExtensionPopup:
case extensions::mojom::ViewType::kBackgroundContents:
case extensions::mojom::ViewType::kExtensionGuest:
case extensions::mojom::ViewType::kTabContents:
case extensions::mojom::ViewType::kOffscreenDocument:
case extensions::mojom::ViewType::kExtensionSidePanel:
case extensions::mojom::ViewType::kInvalid:
return WebContents::Type::kRemote;
}
}
#endif
WebContents::WebContents(v8::Isolate* isolate,
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
type_(Type::kRemote),
id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// WebContents created by extension host will have valid ViewType set.
extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents);
if (view_type != extensions::mojom::ViewType::kInvalid) {
InitWithExtensionView(isolate, web_contents, view_type);
}
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents);
script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents);
#endif
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
SetUserAgent(GetBrowserContext()->GetUserAgent());
web_contents->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type)
: content::WebContentsObserver(web_contents.get()),
type_(type),
id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
DCHECK(type != Type::kRemote)
<< "Can't take ownership of a remote WebContents";
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
InitWithSessionAndOptions(isolate, std::move(web_contents), session,
gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
const gin_helper::Dictionary& options)
: id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
// Read options.
options.Get("backgroundThrottling", &background_throttling_);
// Get type
options.Get("type", &type_);
bool b = false;
if (options.Get(options::kOffscreen, &b) && b)
type_ = Type::kOffScreen;
// Init embedder earlier
options.Get("embedder", &embedder_);
// Whether to enable DevTools.
options.Get("devTools", &enable_devtools_);
// BrowserViews are not attached to a window initially so they should start
// off as hidden. This is also important for compositor recycling. See:
// https://github.com/electron/electron/pull/21372
bool initially_shown = type_ != Type::kBrowserView;
options.Get(options::kShow, &initially_shown);
// Obtain the session.
std::string partition;
gin::Handle<api::Session> session;
if (options.Get("session", &session) && !session.IsEmpty()) {
} else if (options.Get("partition", &partition)) {
session = Session::FromPartition(isolate, partition);
} else {
// Use the default session if not specified.
session = Session::FromPartition(isolate, "");
}
session_.Reset(isolate, session.ToV8());
std::unique_ptr<content::WebContents> web_contents;
if (IsGuest()) {
scoped_refptr<content::SiteInstance> site_instance =
content::SiteInstance::CreateForURL(session->browser_context(),
GURL("chrome-guest://fake-host"));
content::WebContents::CreateParams params(session->browser_context(),
site_instance);
guest_delegate_ =
std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this);
params.guest_delegate = guest_delegate_.get();
if (embedder_ && embedder_->IsOffScreen()) {
auto* view = new OffScreenWebContentsView(
false,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
web_contents = content::WebContents::Create(params);
}
} else if (IsOffScreen()) {
// webPreferences does not have a transparent option, so if the window needs
// to be transparent, that will be set at electron_api_browser_window.cc#L57
// and we then need to pull it back out and check it here.
std::string background_color;
options.GetHidden(options::kBackgroundColor, &background_color);
bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT;
content::WebContents::CreateParams params(session->browser_context());
auto* view = new OffScreenWebContentsView(
transparent,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
content::WebContents::CreateParams params(session->browser_context());
params.initially_hidden = !initially_shown;
web_contents = content::WebContents::Create(params);
}
InitWithSessionAndOptions(isolate, std::move(web_contents), session, options);
}
void WebContents::InitZoomController(content::WebContents* web_contents,
const gin_helper::Dictionary& options) {
WebContentsZoomController::CreateForWebContents(web_contents);
zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
double zoom_factor;
if (options.Get(options::kZoomFactor, &zoom_factor))
zoom_controller_->SetDefaultZoomFactor(zoom_factor);
// Nothing to do with ZoomController, but this function gets called in all
// init cases!
content::RenderViewHost* host = web_contents->GetRenderViewHost();
if (host)
host->GetWidget()->AddInputEventObserver(this);
}
void WebContents::InitWithSessionAndOptions(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> owned_web_contents,
gin::Handle<api::Session> session,
const gin_helper::Dictionary& options) {
Observe(owned_web_contents.get());
InitWithWebContents(std::move(owned_web_contents), session->browser_context(),
IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
auto* prefs = web_contents()->GetMutableRendererPrefs();
// Collect preferred languages from OS and browser process. accept_languages
// effects HTTP header, navigator.languages, and CJK fallback font selection.
//
// Note that an application locale set to the browser process might be
// different with the one set to the preference list.
// (e.g. overridden with --lang)
std::string accept_languages =
g_browser_process->GetApplicationLocale() + ",";
for (auto const& language : electron::GetPreferredLanguages()) {
if (language == g_browser_process->GetApplicationLocale())
continue;
accept_languages += language + ",";
}
accept_languages.pop_back();
prefs->accept_languages = accept_languages;
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
// Update font settings.
static const gfx::FontRenderParams params(
gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr));
prefs->should_antialias_text = params.antialiasing;
prefs->use_subpixel_positioning = params.subpixel_positioning;
prefs->hinting = params.hinting;
prefs->use_autohinter = params.autohinter;
prefs->use_bitmaps = params.use_bitmaps;
prefs->subpixel_rendering = params.subpixel_rendering;
#endif
// Honor the system's cursor blink rate settings
if (auto interval = GetCursorBlinkInterval())
prefs->caret_blink_interval = *interval;
// Save the preferences in C++.
// If there's already a WebContentsPreferences object, we created it as part
// of the webContents.setWindowOpenHandler path, so don't overwrite it.
if (!WebContentsPreferences::From(web_contents())) {
new WebContentsPreferences(web_contents(), options);
}
// Trigger re-calculation of webkit prefs.
web_contents()->NotifyPreferencesChanged();
WebContentsPermissionHelper::CreateForWebContents(web_contents());
InitZoomController(web_contents(), options);
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents());
script_executor_ =
std::make_unique<extensions::ScriptExecutor>(web_contents());
#endif
AutofillDriverFactory::CreateForWebContents(web_contents());
SetUserAgent(GetBrowserContext()->GetUserAgent());
if (IsGuest()) {
NativeWindow* owner_window = nullptr;
if (embedder_) {
// New WebContents's owner_window is the embedder's owner_window.
auto* relay =
NativeWindowRelay::FromWebContents(embedder_->web_contents());
if (relay)
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
}
web_contents()->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
void WebContents::InitWithExtensionView(v8::Isolate* isolate,
content::WebContents* web_contents,
extensions::mojom::ViewType view_type) {
// Must reassign type prior to calling `Init`.
type_ = GetTypeFromViewType(view_type);
if (type_ == Type::kRemote)
return;
if (type_ == Type::kBackgroundPage)
// non-background-page WebContents are retained by other classes. We need
// to pin here to prevent background-page WebContents from being GC'd.
// The background page api::WebContents will live until the underlying
// content::WebContents is destroyed.
Pin(isolate);
// Allow toggling DevTools for background pages
Observe(web_contents);
InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents),
GetBrowserContext(), IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
}
#endif
void WebContents::InitWithWebContents(
std::unique_ptr<content::WebContents> web_contents,
ElectronBrowserContext* browser_context,
bool is_guest) {
browser_context_ = browser_context;
web_contents->SetDelegate(this);
#if BUILDFLAG(ENABLE_PRINTING)
PrintViewManagerElectron::CreateForWebContents(web_contents.get());
#endif
// Determine whether the WebContents is offscreen.
auto* web_preferences = WebContentsPreferences::From(web_contents.get());
offscreen_ = web_preferences && web_preferences->IsOffscreen();
// Create InspectableWebContents.
inspectable_web_contents_ = std::make_unique<InspectableWebContents>(
std::move(web_contents), browser_context->prefs(), is_guest);
inspectable_web_contents_->SetDelegate(this);
}
WebContents::~WebContents() {
if (owner_window_) {
owner_window_->RemoveBackgroundThrottlingSource(this);
}
if (web_contents()) {
content::RenderViewHost* host = web_contents()->GetRenderViewHost();
if (host)
host->GetWidget()->RemoveInputEventObserver(this);
}
if (!inspectable_web_contents_) {
WebContentsDestroyed();
return;
}
inspectable_web_contents_->GetView()->SetDelegate(nullptr);
// This event is only for internal use, which is emitted when WebContents is
// being destroyed.
Emit("will-destroy");
// For guest view based on OOPIF, the WebContents is released by the embedder
// frame, and we need to clear the reference to the memory.
bool not_owned_by_this = IsGuest() && attached_;
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// And background pages are owned by extensions::ExtensionHost.
if (type_ == Type::kBackgroundPage)
not_owned_by_this = true;
#endif
if (not_owned_by_this) {
inspectable_web_contents_->ReleaseWebContents();
WebContentsDestroyed();
}
// InspectableWebContents will be automatically destroyed.
}
void WebContents::DeleteThisIfAlive() {
// It is possible that the FirstWeakCallback has been called but the
// SecondWeakCallback has not, in this case the garbage collection of
// WebContents has already started and we should not |delete this|.
// Calling |GetWrapper| can detect this corner case.
auto* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
delete this;
}
void WebContents::Destroy() {
// The content::WebContents should be destroyed asynchronously when possible
// as user may choose to destroy WebContents during an event of it.
if (Browser::Get()->is_shutting_down() || IsGuest()) {
DeleteThisIfAlive();
} else {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&WebContents::DeleteThisIfAlive, GetWeakPtr()));
}
}
void WebContents::Close(absl::optional<gin_helper::Dictionary> options) {
bool dispatch_beforeunload = false;
if (options)
options->Get("waitForBeforeUnload", &dispatch_beforeunload);
if (dispatch_beforeunload &&
web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) {
NotifyUserActivation();
web_contents()->DispatchBeforeUnload(false /* auto_cancel */);
} else {
web_contents()->Close();
}
}
bool WebContents::DidAddMessageToConsole(
content::WebContents* source,
blink::mojom::ConsoleMessageLevel level,
const std::u16string& message,
int32_t line_no,
const std::u16string& source_id) {
return Emit("console-message", static_cast<int32_t>(level), message, line_no,
source_id);
}
void WebContents::OnCreateWindow(
const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const std::string& features,
const scoped_refptr<network::ResourceRequestBody>& body) {
Emit("-new-window", target_url, frame_name, disposition, features, referrer,
body);
}
void WebContents::WebContentsCreatedWithFullParams(
content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const content::mojom::CreateNewWindowParams& params,
content::WebContents* new_contents) {
ChildWebContentsTracker::CreateForWebContents(new_contents);
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents);
tracker->url = params.target_url;
tracker->frame_name = params.frame_name;
tracker->referrer = params.referrer.To<content::Referrer>();
tracker->raw_features = params.raw_features;
tracker->body = params.body;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary dict;
gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate),
&dict);
pending_child_web_preferences_.Reset();
// Associate the preferences passed in via `setWindowOpenHandler` with the
// content::WebContents that was just created for the child window. These
// preferences will be picked up by the RenderWidgetHost via its call to the
// delegate's OverrideWebkitPrefs.
new WebContentsPreferences(new_contents, dict);
}
bool WebContents::IsWebContentsCreationOverridden(
content::SiteInstance* source_site_instance,
content::mojom::WindowContainerType window_container_type,
const GURL& opener_url,
const content::mojom::CreateNewWindowParams& params) {
bool default_prevented = Emit(
"-will-add-new-contents", params.target_url, params.frame_name,
params.raw_features, params.disposition, *params.referrer, params.body);
// If the app prevented the default, redirect to CreateCustomWebContents,
// which always returns nullptr, which will result in the window open being
// prevented (window.open() will return null in the renderer).
return default_prevented;
}
void WebContents::SetNextChildWebPreferences(
const gin_helper::Dictionary preferences) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
// Store these prefs for when Chrome calls WebContentsCreatedWithFullParams
// with the new child contents.
pending_child_web_preferences_.Reset(isolate, preferences.GetHandle());
}
content::WebContents* WebContents::CreateCustomWebContents(
content::RenderFrameHost* opener,
content::SiteInstance* source_site_instance,
bool is_new_browsing_instance,
const GURL& opener_url,
const std::string& frame_name,
const GURL& target_url,
const content::StoragePartitionConfig& partition_config,
content::SessionStorageNamespace* session_storage_namespace) {
return nullptr;
}
void WebContents::AddNewContents(
content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) {
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get());
DCHECK(tracker);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto api_web_contents =
CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow);
// We call RenderFrameCreated here as at this point the empty "about:blank"
// render frame has already been created. If the window never navigates again
// RenderFrameCreated won't be called and certain prefs like
// "kBackgroundColor" will not be applied.
auto* frame = api_web_contents->MainFrame();
if (frame) {
api_web_contents->HandleNewRenderFrame(frame);
}
if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
window_features.bounds.x(), window_features.bounds.y(),
window_features.bounds.width(), window_features.bounds.height(),
tracker->url, tracker->frame_name, tracker->referrer,
tracker->raw_features, tracker->body)) {
api_web_contents->Destroy();
}
}
content::WebContents* WebContents::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
auto weak_this = GetWeakPtr();
if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {
Emit("-new-window", params.url, "", params.disposition, "", params.referrer,
params.post_data);
return nullptr;
}
if (!weak_this || !web_contents())
return nullptr;
content::NavigationController::LoadURLParams load_url_params(params.url);
load_url_params.referrer = params.referrer;
load_url_params.transition_type = params.transition;
load_url_params.extra_headers = params.extra_headers;
load_url_params.should_replace_current_entry =
params.should_replace_current_entry;
load_url_params.is_renderer_initiated = params.is_renderer_initiated;
load_url_params.started_from_context_menu = params.started_from_context_menu;
load_url_params.initiator_origin = params.initiator_origin;
load_url_params.source_site_instance = params.source_site_instance;
load_url_params.frame_tree_node_id = params.frame_tree_node_id;
load_url_params.redirect_chain = params.redirect_chain;
load_url_params.has_user_gesture = params.user_gesture;
load_url_params.blob_url_loader_factory = params.blob_url_loader_factory;
load_url_params.href_translate = params.href_translate;
load_url_params.reload_type = params.reload_type;
if (params.post_data) {
load_url_params.load_type =
content::NavigationController::LOAD_TYPE_HTTP_POST;
load_url_params.post_data = params.post_data;
}
source->GetController().LoadURLWithParams(load_url_params);
return source;
}
void WebContents::BeforeUnloadFired(content::WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) {
if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen ||
type_ == Type::kBrowserView)
*proceed_to_fire_unload = proceed;
else
*proceed_to_fire_unload = true;
// Note that Chromium does not emit this for navigations.
Emit("before-unload-fired", proceed);
}
void WebContents::SetContentsBounds(content::WebContents* source,
const gfx::Rect& rect) {
if (!Emit("content-bounds-updated", rect))
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnSetContentBounds(rect);
}
void WebContents::CloseContents(content::WebContents* source) {
Emit("close");
auto* autofill_driver_factory =
AutofillDriverFactory::FromWebContents(web_contents());
if (autofill_driver_factory) {
autofill_driver_factory->CloseAllPopups();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnCloseContents();
// This is handled by the embedder frame.
if (!IsGuest())
Destroy();
}
void WebContents::ActivateContents(content::WebContents* source) {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnActivateContents();
}
void WebContents::UpdateTargetURL(content::WebContents* source,
const GURL& url) {
Emit("update-target-url", url);
}
bool WebContents::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (type_ == Type::kWebView && embedder_) {
// Send the unhandled keyboard events back to the embedder.
return embedder_->HandleKeyboardEvent(source, event);
} else {
return PlatformHandleKeyboardEvent(source, event);
}
}
#if !BUILDFLAG(IS_MAC)
// NOTE: The macOS version of this function is found in
// electron_api_web_contents_mac.mm, as it requires calling into objective-C
// code.
bool WebContents::PlatformHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
// Escape exits tabbed fullscreen mode.
if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) {
ExitFullscreenModeForTab(source);
return true;
}
// Check if the webContents has preferences and to ignore shortcuts
auto* web_preferences = WebContentsPreferences::From(source);
if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts())
return false;
// Let the NativeWindow handle other parts.
if (owner_window()) {
owner_window()->HandleKeyboardEvent(source, event);
return true;
}
return false;
}
#endif
content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (exclusive_access_manager_.HandleUserKeyEvent(event))
return content::KeyboardEventProcessingResult::HANDLED;
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown ||
event.GetType() == blink::WebInputEvent::Type::kKeyUp) {
// For backwards compatibility, pretend that `kRawKeyDown` events are
// actually `kKeyDown`.
content::NativeWebKeyboardEvent tweaked_event(event);
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown)
tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown);
bool prevent_default = Emit("before-input-event", tweaked_event);
if (prevent_default) {
return content::KeyboardEventProcessingResult::HANDLED;
}
}
return content::KeyboardEventProcessingResult::NOT_HANDLED;
}
void WebContents::ContentsZoomChange(bool zoom_in) {
Emit("zoom-changed", zoom_in ? "in" : "out");
}
Profile* WebContents::GetProfile() {
return nullptr;
}
bool WebContents::IsFullscreen() const {
if (!owner_window())
return false;
return owner_window()->IsFullscreen() || is_html_fullscreen();
}
void WebContents::EnterFullscreen(const GURL& url,
ExclusiveAccessBubbleType bubble_type,
const int64_t display_id) {}
void WebContents::ExitFullscreen() {}
void WebContents::UpdateExclusiveAccessExitBubbleContent(
const GURL& url,
ExclusiveAccessBubbleType bubble_type,
ExclusiveAccessBubbleHideCallback bubble_first_hide_callback,
bool notify_download,
bool force_update) {}
void WebContents::OnExclusiveAccessUserInput() {}
content::WebContents* WebContents::GetActiveWebContents() {
return web_contents();
}
bool WebContents::CanUserExitFullscreen() const {
return true;
}
bool WebContents::IsExclusiveAccessBubbleDisplayed() const {
return false;
}
void WebContents::EnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options) {
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(source);
auto callback =
base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab,
base::Unretained(this), requesting_frame, options);
permission_helper->RequestFullscreenPermission(requesting_frame, callback);
}
void WebContents::OnEnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options,
bool allowed) {
if (!allowed || !owner_window())
return;
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
if (IsFullscreenForTabOrPending(source)) {
DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame());
return;
}
owner_window()->set_fullscreen_transition_type(
NativeWindow::FullScreenTransitionType::kHTML);
exclusive_access_manager_.fullscreen_controller()->EnterFullscreenModeForTab(
requesting_frame, options.display_id);
SetHtmlApiFullscreen(true);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
if (!owner_window())
return;
// This needs to be called before we exit fullscreen on the native window,
// or the controller will incorrectly think we weren't fullscreen and bail.
exclusive_access_manager_.fullscreen_controller()->ExitFullscreenModeForTab(
source);
SetHtmlApiFullscreen(false);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too. Chrome does this indirectly from
// `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::RendererUnresponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host,
base::RepeatingClosure hang_monitor_restarter) {
Emit("unresponsive");
}
void WebContents::RendererResponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host) {
Emit("responsive");
}
bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) {
Emit("context-menu", std::make_pair(params, &render_frame_host));
return true;
}
void WebContents::FindReply(content::WebContents* web_contents,
int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update) {
if (!final_update)
return;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto result = gin_helper::Dictionary::CreateEmpty(isolate);
result.Set("requestId", request_id);
result.Set("matches", number_of_matches);
result.Set("selectionArea", selection_rect);
result.Set("activeMatchOrdinal", active_match_ordinal);
result.Set("finalUpdate", final_update); // Deprecate after 2.0
Emit("found-in-page", result.GetHandle());
}
void WebContents::RequestExclusivePointerAccess(
content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target,
bool allowed) {
if (allowed) {
exclusive_access_manager_.mouse_lock_controller()->RequestToLockMouse(
web_contents, user_gesture, last_unlocked_by_target);
} else {
web_contents->GotResponseToLockMouseRequest(
blink::mojom::PointerLockResult::kPermissionDenied);
}
}
void WebContents::RequestToLockMouse(content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestPointerLockPermission(
user_gesture, last_unlocked_by_target,
base::BindOnce(&WebContents::RequestExclusivePointerAccess,
base::Unretained(this)));
}
void WebContents::LostMouseLock() {
exclusive_access_manager_.mouse_lock_controller()->LostMouseLock();
}
void WebContents::RequestKeyboardLock(content::WebContents* web_contents,
bool esc_key_locked) {
exclusive_access_manager_.keyboard_lock_controller()->RequestKeyboardLock(
web_contents, esc_key_locked);
}
void WebContents::CancelKeyboardLockRequest(
content::WebContents* web_contents) {
exclusive_access_manager_.keyboard_lock_controller()
->CancelKeyboardLockRequest(web_contents);
}
bool WebContents::CheckMediaAccessPermission(
content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::mojom::MediaStreamType type) {
auto* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
return permission_helper->CheckMediaAccessPermission(security_origin, type);
}
void WebContents::RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestMediaAccessPermission(request, std::move(callback));
}
content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager(
content::WebContents* source) {
if (!dialog_manager_)
dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>();
return dialog_manager_.get();
}
void WebContents::OnAudioStateChanged(bool audible) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
gin::Dictionary dict(isolate, event_object);
dict.Set("audible", audible);
EmitWithoutEvent("audio-state-changed", event);
}
void WebContents::BeforeUnloadFired(bool proceed) {
// Do nothing, we override this method just to avoid compilation error since
// there are two virtual functions named BeforeUnloadFired.
}
void WebContents::HandleNewRenderFrame(
content::RenderFrameHost* render_frame_host) {
auto* rwhv = render_frame_host->GetView();
if (!rwhv)
return;
// Set the background color of RenderWidgetHostView.
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences) {
auto maybe_color = web_preferences->GetBackgroundColor();
bool guest = IsGuest() || type_ == Type::kBrowserView;
// If webPreferences has no color stored we need to explicitly set guest
// webContents background color to transparent.
auto bg_color =
maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE);
web_contents()->SetPageBaseBackgroundColor(bg_color);
SetBackgroundColor(rwhv, bg_color);
}
if (!background_throttling_)
render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false);
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (rwh_impl)
rwh_impl->disable_hidden_ = !background_throttling_;
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->MaybeSetupMojoConnection();
}
void WebContents::OnBackgroundColorChanged() {
absl::optional<SkColor> color = web_contents()->GetBackgroundColor();
if (color.has_value()) {
auto* const view = web_contents()->GetRenderWidgetHostView();
static_cast<content::RenderWidgetHostViewBase*>(view)
->SetContentBackgroundColor(color.value());
}
}
void WebContents::RenderFrameCreated(
content::RenderFrameHost* render_frame_host) {
HandleNewRenderFrame(render_frame_host);
// RenderFrameCreated is called for speculative frames which may not be
// used in certain cross-origin navigations. Invoking
// RenderFrameHost::GetLifecycleState currently crashes when called for
// speculative frames so we need to filter it out for now. Check
// https://crbug.com/1183639 for details on when this can be removed.
auto* rfh_impl =
static_cast<content::RenderFrameHostImpl*>(render_frame_host);
if (rfh_impl->lifecycle_state() ==
content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) {
return;
}
content::RenderFrameHost::LifecycleState lifecycle_state =
render_frame_host->GetLifecycleState();
if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.SetGetter("frame", render_frame_host);
Emit("frame-created", details);
}
}
void WebContents::RenderFrameDeleted(
content::RenderFrameHost* render_frame_host) {
// A RenderFrameHost can be deleted when:
// - A WebContents is removed and its containing frames are disposed.
// - An <iframe> is removed from the DOM.
// - Cross-origin navigation creates a new RFH in a separate process which
// is swapped by content::RenderFrameHostManager.
//
// WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID
// to find an existing instance of WebFrameMain. During a cross-origin
// navigation, the deleted RFH will be the old host which was swapped out. In
// this special case, we need to also ensure that WebFrameMain's internal RFH
// matches before marking it as disposed.
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame && web_frame->render_frame_host() == render_frame_host)
web_frame->MarkRenderFrameDisposed();
}
void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) {
if (new_host->IsInPrimaryMainFrame()) {
if (old_host)
old_host->GetRenderWidgetHost()->RemoveInputEventObserver(this);
if (new_host)
new_host->GetRenderWidgetHost()->AddInputEventObserver(this);
}
// During cross-origin navigation, a FrameTreeNode will swap out its RFH.
// If an instance of WebFrameMain exists, it will need to have its RFH
// swapped as well.
//
// |old_host| can be a nullptr so we use |new_host| for looking up the
// WebFrameMain instance.
auto* web_frame = WebFrameMain::FromRenderFrameHost(new_host);
if (web_frame) {
web_frame->UpdateRenderFrameHost(new_host);
}
}
void WebContents::FrameDeleted(int frame_tree_node_id) {
auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id);
if (web_frame)
web_frame->Destroyed();
}
void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
// This event is necessary for tracking any states with respect to
// intermediate render view hosts aka speculative render view hosts. Currently
// used by object-registry.js to ref count remote objects.
Emit("render-view-deleted", render_view_host->GetProcess()->GetID());
if (web_contents()->GetRenderViewHost() == render_view_host) {
// When the RVH that has been deleted is the current RVH it means that the
// the web contents are being closed. This is communicated by this event.
// Currently tracked by guest-window-manager.ts to destroy the
// BrowserWindow.
Emit("current-render-view-deleted",
render_view_host->GetProcess()->GetID());
}
}
void WebContents::PrimaryMainFrameRenderProcessGone(
base::TerminationStatus status) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("reason", status);
details.Set("exitCode", web_contents()->GetCrashedErrorCode());
Emit("render-process-gone", details);
}
void WebContents::PluginCrashed(const base::FilePath& plugin_path,
base::ProcessId plugin_pid) {
#if BUILDFLAG(ENABLE_PLUGINS)
content::WebPluginInfo info;
auto* plugin_service = content::PluginService::GetInstance();
plugin_service->GetPluginInfoByPath(plugin_path, &info);
Emit("plugin-crashed", info.name, info.version);
#endif // BUILDFLAG(ENABLE_PLUGINS)
}
void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id) {
Emit("media-started-playing");
}
void WebContents::MediaStoppedPlaying(
const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id,
content::WebContentsObserver::MediaStoppedReason reason) {
Emit("media-paused");
}
void WebContents::DidChangeThemeColor() {
auto theme_color = web_contents()->GetThemeColor();
if (theme_color) {
Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value()));
} else {
Emit("did-change-theme-color", nullptr);
}
}
void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) {
set_fullscreen_frame(rfh);
}
void WebContents::OnWebContentsFocused(
content::RenderWidgetHost* render_widget_host) {
Emit("focus");
}
void WebContents::OnWebContentsLostFocus(
content::RenderWidgetHost* render_widget_host) {
Emit("blur");
}
void WebContents::DOMContentLoaded(
content::RenderFrameHost* render_frame_host) {
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->DOMContentLoaded();
if (!render_frame_host->GetParent())
Emit("dom-ready");
}
void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url) {
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
auto weak_this = GetWeakPtr();
Emit("did-frame-finish-load", is_main_frame, frame_process_id,
frame_routing_id);
// β οΈWARNING!β οΈ
// Emit() triggers JS which can call destroy() on |this|. It's not safe to
// assume that |this| points to valid memory at this point.
if (is_main_frame && weak_this && web_contents())
Emit("did-finish-load");
}
void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
const GURL& url,
int error_code) {
// See DocumentLoader::StartLoadingResponse() - when we navigate to a media
// resource the original request for the media resource, which resulted in a
// committed navigation, is simply discarded. The media element created
// inside the MediaDocument then makes *another new* request for the same
// media resource.
bool is_media_document =
media::IsSupportedMediaMimeType(web_contents()->GetContentsMimeType());
if (error_code == net::ERR_ABORTED && is_media_document)
return;
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id,
frame_routing_id);
}
void WebContents::DidStartLoading() {
Emit("did-start-loading");
}
void WebContents::DidStopLoading() {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences && web_preferences->ShouldUsePreferredSizeMode())
web_contents()->GetRenderViewHost()->EnablePreferredSizeMode();
Emit("did-stop-loading");
}
bool WebContents::EmitNavigationEvent(
const std::string& event_name,
content::NavigationHandle* navigation_handle) {
bool is_main_frame = navigation_handle->IsInMainFrame();
int frame_process_id = -1, frame_routing_id = -1;
content::RenderFrameHost* frame_host = GetRenderFrameHost(navigation_handle);
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
bool is_same_document = navigation_handle->IsSameDocument();
auto url = navigation_handle->GetURL();
content::RenderFrameHost* initiator_frame_host =
navigation_handle->GetInitiatorFrameToken().has_value()
? content::RenderFrameHost::FromFrameToken(
navigation_handle->GetInitiatorProcessId(),
navigation_handle->GetInitiatorFrameToken().value())
: nullptr;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
gin_helper::Dictionary dict(isolate, event_object);
dict.Set("url", url);
dict.Set("isSameDocument", is_same_document);
dict.Set("isMainFrame", is_main_frame);
dict.Set("frame", frame_host);
dict.SetGetter("initiator", initiator_frame_host);
EmitWithoutEvent(event_name, event, url, is_same_document, is_main_frame,
frame_process_id, frame_routing_id);
return event->GetDefaultPrevented();
}
void WebContents::Message(bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Message", "channel", channel);
// webContents.emit('-ipc-message', new Event(), internal, channel,
// arguments);
EmitWithSender("-ipc-message", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), internal,
channel, std::move(arguments));
}
void WebContents::Invoke(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::InvokeCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel);
// webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments);
EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::OnFirstNonEmptyLayout(
content::RenderFrameHost* render_frame_host) {
if (render_frame_host == web_contents()->GetPrimaryMainFrame()) {
Emit("ready-to-show");
}
}
// This object wraps the InvokeCallback so that if it gets GC'd by V8, we can
// still call the callback and send an error. Not doing so causes a Mojo DCHECK,
// since Mojo requires callbacks to be called before they are destroyed.
class ReplyChannel : public gin::Wrappable<ReplyChannel> {
public:
using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback;
static gin::Handle<ReplyChannel> Create(v8::Isolate* isolate,
InvokeCallback callback) {
return gin::CreateHandle(isolate, new ReplyChannel(std::move(callback)));
}
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override {
return gin::Wrappable<ReplyChannel>::GetObjectTemplateBuilder(isolate)
.SetMethod("sendReply", &ReplyChannel::SendReply);
}
const char* GetTypeName() override { return "ReplyChannel"; }
void SendError(const std::string& msg) {
v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
// If there's no current context, it means we're shutting down, so we
// don't need to send an event.
if (!isolate->GetCurrentContext().IsEmpty()) {
v8::HandleScope scope(isolate);
auto message = gin::DataObjectBuilder(isolate).Set("error", msg).Build();
SendReply(isolate, message);
}
}
private:
explicit ReplyChannel(InvokeCallback callback)
: callback_(std::move(callback)) {}
~ReplyChannel() override {
if (callback_)
SendError("reply was never sent");
}
bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> arg) {
if (!callback_)
return false;
blink::CloneableMessage message;
if (!gin::ConvertFromV8(isolate, arg, &message)) {
return false;
}
std::move(callback_).Run(std::move(message));
return true;
}
InvokeCallback callback_;
};
gin::WrapperInfo ReplyChannel::kWrapperInfo = {gin::kEmbedderNativeGin};
gin::Handle<gin_helper::internal::Event> WebContents::MakeEventWithSender(
v8::Isolate* isolate,
content::RenderFrameHost* frame,
electron::mojom::ElectronApiIPC::InvokeCallback callback) {
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper)) {
if (callback) {
// We must always invoke the callback if present.
ReplyChannel::Create(isolate, std::move(callback))
->SendError("WebContents was destroyed");
}
return gin::Handle<gin_helper::internal::Event>();
}
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
gin_helper::Dictionary dict(isolate, event.ToV8().As<v8::Object>());
if (callback)
dict.Set("_replyChannel",
ReplyChannel::Create(isolate, std::move(callback)));
if (frame) {
dict.Set("frameId", frame->GetRoutingID());
dict.Set("processId", frame->GetProcess()->GetID());
}
return event;
}
void WebContents::ReceivePostMessage(
const std::string& channel,
blink::TransferableMessage message,
content::RenderFrameHost* render_frame_host) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto wrapped_ports =
MessagePort::EntanglePorts(isolate, std::move(message.ports));
v8::Local<v8::Value> message_value =
electron::DeserializeV8Value(isolate, message);
EmitWithSender("-ipc-ports", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), false,
channel, message_value, std::move(wrapped_ports));
}
void WebContents::MessageSync(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::MessageSyncCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel);
// webContents.emit('-ipc-message-sync', new Event(sender, message), internal,
// channel, arguments);
EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::MessageHost(const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel);
// webContents.emit('ipc-message-host', new Event(), channel, args);
EmitWithSender("ipc-message-host", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), channel,
std::move(arguments));
}
void WebContents::UpdateDraggableRegions(
std::vector<mojom::DraggableRegionPtr> regions) {
if (owner_window() && owner_window()->has_frame())
return;
draggable_region_ = DraggableRegionsToSkRegion(regions);
}
void WebContents::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-start-navigation", navigation_handle);
}
void WebContents::DidRedirectNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-redirect-navigation", navigation_handle);
}
void WebContents::ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) {
// Don't focus content in an inactive window.
if (!owner_window())
return;
#if BUILDFLAG(IS_MAC)
if (!owner_window()->IsActive())
return;
#else
if (!owner_window()->widget()->IsActive())
return;
#endif
// Don't focus content after subframe navigations.
if (!navigation_handle->IsInMainFrame())
return;
// Only focus for top-level contents.
if (type_ != Type::kBrowserWindow)
return;
web_contents()->SetInitialFocus();
}
void WebContents::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (owner_window_) {
owner_window_->NotifyLayoutWindowControlsOverlay();
}
if (!navigation_handle->HasCommitted())
return;
bool is_main_frame = navigation_handle->IsInMainFrame();
content::RenderFrameHost* frame_host =
navigation_handle->GetRenderFrameHost();
int frame_process_id = -1, frame_routing_id = -1;
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
if (!navigation_handle->IsErrorPage()) {
// FIXME: All the Emit() calls below could potentially result in |this|
// being destroyed (by JS listening for the event and calling
// webContents.destroy()).
auto url = navigation_handle->GetURL();
bool is_same_document = navigation_handle->IsSameDocument();
if (is_same_document) {
Emit("did-navigate-in-page", url, is_main_frame, frame_process_id,
frame_routing_id);
} else {
const net::HttpResponseHeaders* http_response =
navigation_handle->GetResponseHeaders();
std::string http_status_text;
int http_response_code = -1;
if (http_response) {
http_status_text = http_response->GetStatusText();
http_response_code = http_response->response_code();
}
Emit("did-frame-navigate", url, http_response_code, http_status_text,
is_main_frame, frame_process_id, frame_routing_id);
if (is_main_frame) {
Emit("did-navigate", url, http_response_code, http_status_text);
}
}
if (IsGuest())
Emit("load-commit", url, is_main_frame);
} else {
auto url = navigation_handle->GetURL();
int code = navigation_handle->GetNetErrorCode();
auto description = net::ErrorToShortString(code);
Emit("did-fail-provisional-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
// Do not emit "did-fail-load" for canceled requests.
if (code != net::ERR_ABORTED) {
EmitWarning(
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()),
"Failed to load URL: " + url.possibly_invalid_spec() +
" with error: " + description,
"electron");
Emit("did-fail-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
}
}
content::NavigationEntry* entry = navigation_handle->GetNavigationEntry();
// This check is needed due to an issue in Chromium
// Check the Chromium issue to keep updated:
// https://bugs.chromium.org/p/chromium/issues/detail?id=1178663
// If a history entry has been made and the forward/back call has been made,
// proceed with setting the new title
if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK))
WebContents::TitleWasSet(entry);
}
void WebContents::TitleWasSet(content::NavigationEntry* entry) {
std::u16string final_title;
bool explicit_set = true;
if (entry) {
auto title = entry->GetTitle();
auto url = entry->GetURL();
if (url.SchemeIsFile() && title.empty()) {
final_title = base::UTF8ToUTF16(url.ExtractFileName());
explicit_set = false;
} else {
final_title = title;
}
} else {
final_title = web_contents()->GetTitle();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnPageTitleUpdated(final_title, explicit_set);
Emit("page-title-updated", final_title, explicit_set);
}
void WebContents::DidUpdateFaviconURL(
content::RenderFrameHost* render_frame_host,
const std::vector<blink::mojom::FaviconURLPtr>& urls) {
std::set<GURL> unique_urls;
for (const auto& iter : urls) {
if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon)
continue;
const GURL& url = iter->icon_url;
if (url.is_valid())
unique_urls.insert(url);
}
Emit("page-favicon-updated", unique_urls);
}
void WebContents::DevToolsReloadPage() {
Emit("devtools-reload-page");
}
void WebContents::DevToolsFocused() {
Emit("devtools-focused");
}
void WebContents::DevToolsOpened() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
DCHECK(inspectable_web_contents_);
DCHECK(inspectable_web_contents_->GetDevToolsWebContents());
auto handle = FromOrCreate(
isolate, inspectable_web_contents_->GetDevToolsWebContents());
devtools_web_contents_.Reset(isolate, handle.ToV8());
// Set inspected tabID.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "setInspectedTabId", base::Value(ID()));
// Inherit owner window in devtools when it doesn't have one.
auto* devtools = inspectable_web_contents_->GetDevToolsWebContents();
bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey());
if (owner_window() && !has_window)
handle->SetOwnerWindow(devtools, owner_window());
Emit("devtools-opened");
}
void WebContents::DevToolsClosed() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
devtools_web_contents_.Reset();
Emit("devtools-closed");
}
void WebContents::DevToolsResized() {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnDevToolsResized();
}
void WebContents::SetOwnerWindow(NativeWindow* owner_window) {
SetOwnerWindow(GetWebContents(), owner_window);
}
void WebContents::SetOwnerWindow(content::WebContents* web_contents,
NativeWindow* owner_window) {
if (owner_window_) {
owner_window_->RemoveBackgroundThrottlingSource(this);
}
if (owner_window) {
owner_window_ = owner_window->GetWeakPtr();
NativeWindowRelay::CreateForWebContents(web_contents,
owner_window->GetWeakPtr());
owner_window_->AddBackgroundThrottlingSource(this);
} else {
owner_window_ = nullptr;
web_contents->RemoveUserData(NativeWindowRelay::UserDataKey());
}
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetNativeWindow(owner_window);
}
content::WebContents* WebContents::GetWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetWebContents();
}
content::WebContents* WebContents::GetDevToolsWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetDevToolsWebContents();
}
void WebContents::WebContentsDestroyed() {
// Clear the pointer stored in wrapper.
if (GetAllWebContents().Lookup(id_))
GetAllWebContents().Remove(id_);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
wrapper->SetAlignedPointerInInternalField(0, nullptr);
// Tell WebViewGuestDelegate that the WebContents has been destroyed.
if (guest_delegate_)
guest_delegate_->WillDestroy();
Observe(nullptr);
Emit("destroyed");
}
void WebContents::NavigationEntryCommitted(
const content::LoadCommittedDetails& details) {
Emit("navigation-entry-committed", details.entry->GetURL(),
details.is_same_document, details.did_replace_entry);
}
bool WebContents::GetBackgroundThrottling() const {
return background_throttling_;
}
void WebContents::SetBackgroundThrottling(bool allowed) {
background_throttling_ = allowed;
if (owner_window_) {
owner_window_->UpdateBackgroundThrottlingState();
}
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (!rfh)
return;
auto* rwhv = rfh->GetView();
if (!rwhv)
return;
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (!rwh_impl)
return;
rwh_impl->disable_hidden_ = !background_throttling_;
web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed);
if (rwh_impl->is_hidden()) {
rwh_impl->WasShown({});
}
}
int WebContents::GetProcessID() const {
return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
}
base::ProcessId WebContents::GetOSProcessID() const {
base::ProcessHandle process_handle = web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->GetProcess()
.Handle();
return base::GetProcId(process_handle);
}
WebContents::Type WebContents::GetType() const {
return type_;
}
bool WebContents::Equal(const WebContents* web_contents) const {
return ID() == web_contents->ID();
}
GURL WebContents::GetURL() const {
return web_contents()->GetLastCommittedURL();
}
void WebContents::LoadURL(const GURL& url,
const gin_helper::Dictionary& options) {
if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL),
net::ErrorToShortString(net::ERR_INVALID_URL),
url.possibly_invalid_spec(), true);
return;
}
content::NavigationController::LoadURLParams params(url);
if (!options.Get("httpReferrer", ¶ms.referrer)) {
GURL http_referrer;
if (options.Get("httpReferrer", &http_referrer))
params.referrer =
content::Referrer(http_referrer.GetAsReferrer(),
network::mojom::ReferrerPolicy::kDefault);
}
std::string user_agent;
if (options.Get("userAgent", &user_agent))
SetUserAgent(user_agent);
std::string extra_headers;
if (options.Get("extraHeaders", &extra_headers))
params.extra_headers = extra_headers;
scoped_refptr<network::ResourceRequestBody> body;
if (options.Get("postData", &body)) {
params.post_data = body;
params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
}
GURL base_url_for_data_url;
if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
params.base_url_for_data_url = base_url_for_data_url;
params.load_type = content::NavigationController::LOAD_TYPE_DATA;
}
bool reload_ignoring_cache = false;
if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) &&
reload_ignoring_cache) {
params.reload_type = content::ReloadType::BYPASSING_CACHE;
}
// Calling LoadURLWithParams() can trigger JS which destroys |this|.
auto weak_this = GetWeakPtr();
params.transition_type = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
// It's not safe to start a new navigation or otherwise discard the current
// one while the call that started it is still on the stack. See
// http://crbug.com/347742.
auto& ctrl_impl = static_cast<content::NavigationControllerImpl&>(
web_contents()->GetController());
if (ctrl_impl.in_navigate_to_pending_entry()) {
Emit("did-fail-load", static_cast<int>(net::ERR_FAILED),
net::ErrorToShortString(net::ERR_FAILED), url.possibly_invalid_spec(),
true);
return;
}
// Discard non-committed entries to ensure we don't re-use a pending entry.
web_contents()->GetController().DiscardNonCommittedEntries();
web_contents()->GetController().LoadURLWithParams(params);
// β οΈWARNING!β οΈ
// LoadURLWithParams() triggers JS events which can call destroy() on |this|.
// It's not safe to assume that |this| points to valid memory at this point.
if (!weak_this || !web_contents())
return;
// Required to make beforeunload handler work.
NotifyUserActivation();
}
// TODO(MarshallOfSound): Figure out what we need to do with post data here, I
// believe the default behavior when we pass "true" is to phone out to the
// delegate and then the controller expects this method to be called again with
// "false" if the user approves the reload. For now this would result in
// ".reload()" calls on POST data domains failing silently. Passing false would
// result in them succeeding, but reposting which although more correct could be
// considering a breaking change.
void WebContents::Reload() {
web_contents()->GetController().Reload(content::ReloadType::NORMAL,
/* check_for_repost */ true);
}
void WebContents::ReloadIgnoringCache() {
web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE,
/* check_for_repost */ true);
}
void WebContents::DownloadURL(const GURL& url, gin::Arguments* args) {
std::map<std::string, std::string> headers;
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
if (options.Has("headers") && !options.Get("headers", &headers)) {
args->ThrowTypeError("Invalid value for headers - must be an object");
return;
}
}
std::unique_ptr<download::DownloadUrlParameters> download_params(
content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
web_contents(), url, MISSING_TRAFFIC_ANNOTATION));
for (const auto& [name, value] : headers) {
download_params->add_request_header(name, value);
}
auto* download_manager =
web_contents()->GetBrowserContext()->GetDownloadManager();
download_manager->DownloadUrl(std::move(download_params));
}
std::u16string WebContents::GetTitle() const {
return web_contents()->GetTitle();
}
bool WebContents::IsLoading() const {
return web_contents()->IsLoading();
}
bool WebContents::IsLoadingMainFrame() const {
return web_contents()->ShouldShowLoadingUI();
}
bool WebContents::IsWaitingForResponse() const {
return web_contents()->IsWaitingForResponse();
}
void WebContents::Stop() {
web_contents()->Stop();
}
bool WebContents::CanGoBack() const {
return web_contents()->GetController().CanGoBack();
}
void WebContents::GoBack() {
if (CanGoBack())
web_contents()->GetController().GoBack();
}
bool WebContents::CanGoForward() const {
return web_contents()->GetController().CanGoForward();
}
void WebContents::GoForward() {
if (CanGoForward())
web_contents()->GetController().GoForward();
}
bool WebContents::CanGoToOffset(int offset) const {
return web_contents()->GetController().CanGoToOffset(offset);
}
void WebContents::GoToOffset(int offset) {
if (CanGoToOffset(offset))
web_contents()->GetController().GoToOffset(offset);
}
bool WebContents::CanGoToIndex(int index) const {
return index >= 0 && index < GetHistoryLength();
}
void WebContents::GoToIndex(int index) {
if (CanGoToIndex(index))
web_contents()->GetController().GoToIndex(index);
}
int WebContents::GetActiveIndex() const {
return web_contents()->GetController().GetCurrentEntryIndex();
}
void WebContents::ClearHistory() {
// In some rare cases (normally while there is no real history) we are in a
// state where we can't prune navigation entries
if (web_contents()->GetController().CanPruneAllButLastCommitted()) {
web_contents()->GetController().PruneAllButLastCommitted();
}
}
int WebContents::GetHistoryLength() const {
return web_contents()->GetController().GetEntryCount();
}
const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy;
}
void WebContents::SetWebRTCIPHandlingPolicy(
const std::string& webrtc_ip_handling_policy) {
if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
return;
web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
webrtc_ip_handling_policy;
web_contents()->SyncRendererPrefs();
}
v8::Local<v8::Value> WebContents::GetWebRTCUDPPortRange(
v8::Isolate* isolate) const {
auto* prefs = web_contents()->GetMutableRendererPrefs();
auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
dict.Set("min", static_cast<uint32_t>(prefs->webrtc_udp_min_port));
dict.Set("max", static_cast<uint32_t>(prefs->webrtc_udp_max_port));
return dict.GetHandle();
}
void WebContents::SetWebRTCUDPPortRange(gin::Arguments* args) {
uint32_t min = 0, max = 0;
gin_helper::Dictionary range;
if (!args->GetNext(&range) || !range.Get("min", &min) ||
!range.Get("max", &max)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'min' and 'max' are both required");
return;
}
if ((0 == min && 0 != max) || max > UINT16_MAX) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError(
"'min' and 'max' must be in the (0, 65535] range or [0, 0]");
return;
}
if (min > max) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'max' must be greater than or equal to 'min'");
return;
}
auto* prefs = web_contents()->GetMutableRendererPrefs();
if (prefs->webrtc_udp_min_port == static_cast<uint16_t>(min) &&
prefs->webrtc_udp_max_port == static_cast<uint16_t>(max)) {
return;
}
prefs->webrtc_udp_min_port = min;
prefs->webrtc_udp_max_port = max;
web_contents()->SyncRendererPrefs();
}
std::string WebContents::GetMediaSourceID(
content::WebContents* request_web_contents) {
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host)
return std::string();
content::DesktopMediaID media_id(
content::DesktopMediaID::TYPE_WEB_CONTENTS,
content::DesktopMediaID::kNullId,
content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(),
frame_host->GetRoutingID()));
auto* request_frame_host = request_web_contents->GetPrimaryMainFrame();
if (!request_frame_host)
return std::string();
std::string id =
content::DesktopStreamsRegistry::GetInstance()->RegisterStream(
request_frame_host->GetProcess()->GetID(),
request_frame_host->GetRoutingID(),
url::Origin::Create(request_frame_host->GetLastCommittedURL()
.DeprecatedGetOriginAsURL()),
media_id, content::kRegistryStreamTypeTab);
return id;
}
bool WebContents::IsCrashed() const {
return web_contents()->IsCrashed();
}
void WebContents::ForcefullyCrashRenderer() {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
if (!rwh)
return;
content::RenderProcessHost* rph = rwh->GetProcess();
if (rph) {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// A generic |CrashDumpHungChildProcess()| is not implemented for Linux.
// Instead we send an explicit IPC to crash on the renderer's IO thread.
rph->ForceCrash();
#else
// Try to generate a crash report for the hung process.
#if !IS_MAS_BUILD()
CrashDumpHungChildProcess(rph->GetProcess().Handle());
#endif
rph->Shutdown(content::RESULT_CODE_HUNG);
#endif
}
}
void WebContents::SetUserAgent(const std::string& user_agent) {
blink::UserAgentOverride ua_override;
ua_override.ua_string_override = user_agent;
if (!user_agent.empty())
ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata();
web_contents()->SetUserAgentOverride(ua_override, false);
}
std::string WebContents::GetUserAgent() {
return web_contents()->GetUserAgentOverride().ua_string_override;
}
v8::Local<v8::Promise> WebContents::SavePage(
const base::FilePath& full_file_path,
const content::SavePageType& save_type) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!full_file_path.IsAbsolute()) {
promise.RejectWithErrorMessage("Path must be absolute");
return handle;
}
auto* handler = new SavePageHandler(web_contents(), std::move(promise));
handler->Handle(full_file_path, save_type);
return handle;
}
void WebContents::OpenDevTools(gin::Arguments* args) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
std::string state;
if (type_ == Type::kWebView || type_ == Type::kBackgroundPage ||
!owner_window()) {
state = "detach";
}
bool activate = true;
std::string title;
if (args && args->Length() == 1) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("mode", &state);
options.Get("activate", &activate);
options.Get("title", &title);
}
}
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->SetDockState(state);
inspectable_web_contents_->SetDevToolsTitle(base::UTF8ToUTF16(title));
inspectable_web_contents_->ShowDevTools(activate);
}
void WebContents::CloseDevTools() {
if (type_ == Type::kRemote)
return;
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->CloseDevTools();
}
bool WebContents::IsDevToolsOpened() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->IsDevToolsViewShowing();
}
std::u16string WebContents::GetDevToolsTitle() {
if (type_ == Type::kRemote)
return std::u16string();
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->GetDevToolsTitle();
}
void WebContents::SetDevToolsTitle(const std::u16string& title) {
inspectable_web_contents_->SetDevToolsTitle(title);
}
bool WebContents::IsDevToolsFocused() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->GetView()->IsDevToolsViewFocused();
}
void WebContents::EnableDeviceEmulation(
const blink::DeviceEmulationParams& params) {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->EnableDeviceEmulation(params);
}
}
}
void WebContents::DisableDeviceEmulation() {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->DisableDeviceEmulation();
}
}
}
void WebContents::ToggleDevTools() {
if (IsDevToolsOpened())
CloseDevTools();
else
OpenDevTools(nullptr);
}
void WebContents::InspectElement(int x, int y) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
DCHECK(inspectable_web_contents_);
if (!inspectable_web_contents_->GetDevToolsWebContents())
OpenDevTools(nullptr);
inspectable_web_contents_->InspectElement(x, y);
}
void WebContents::InspectSharedWorkerById(const std::string& workerId) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
if (agent_host->GetId() == workerId) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
}
std::vector<scoped_refptr<content::DevToolsAgentHost>>
WebContents::GetAllSharedWorkers() {
std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers;
if (type_ == Type::kRemote)
return shared_workers;
if (!enable_devtools_)
return shared_workers;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
shared_workers.push_back(agent_host);
}
}
return shared_workers;
}
void WebContents::InspectSharedWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::InspectServiceWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeServiceWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::SetIgnoreMenuShortcuts(bool ignore) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
DCHECK(web_preferences);
web_preferences->SetIgnoreMenuShortcuts(ignore);
}
void WebContents::SetAudioMuted(bool muted) {
web_contents()->SetAudioMuted(muted);
}
bool WebContents::IsAudioMuted() {
return web_contents()->IsAudioMuted();
}
bool WebContents::IsCurrentlyAudible() {
return web_contents()->IsCurrentlyAudible();
}
#if BUILDFLAG(ENABLE_PRINTING)
void WebContents::OnGetDeviceNameToUse(
base::Value::Dict print_settings,
printing::CompletionCallback print_callback,
bool silent,
// <error, device_name>
std::pair<std::string, std::u16string> info) {
// The content::WebContents might be already deleted at this point, and the
// PrintViewManagerElectron class does not do null check.
if (!web_contents()) {
if (print_callback)
std::move(print_callback).Run(false, "failed");
return;
}
if (!info.first.empty()) {
if (print_callback)
std::move(print_callback).Run(false, info.first);
return;
}
// If the user has passed a deviceName use it, otherwise use default printer.
print_settings.Set(printing::kSettingDeviceName, info.second);
auto* print_view_manager =
PrintViewManagerElectron::FromWebContents(web_contents());
if (!print_view_manager)
return;
auto* focused_frame = web_contents()->GetFocusedFrame();
auto* rfh = focused_frame && focused_frame->HasSelection()
? focused_frame
: web_contents()->GetPrimaryMainFrame();
print_view_manager->PrintNow(rfh, silent, std::move(print_settings),
std::move(print_callback));
}
void WebContents::Print(gin::Arguments* args) {
auto options = gin_helper::Dictionary::CreateEmpty(args->isolate());
base::Value::Dict settings;
if (args->Length() >= 1 && !args->GetNext(&options)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid print settings specified.");
return;
}
printing::CompletionCallback callback;
if (args->Length() == 2 && !args->GetNext(&callback)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid optional callback provided.");
return;
}
// Set optional silent printing
bool silent = false;
options.Get("silent", &silent);
bool print_background = false;
options.Get("printBackground", &print_background);
settings.Set(printing::kSettingShouldPrintBackgrounds, print_background);
// Set custom margin settings
auto margins = gin_helper::Dictionary::CreateEmpty(args->isolate());
if (options.Get("margins", &margins)) {
printing::mojom::MarginType margin_type =
printing::mojom::MarginType::kDefaultMargins;
margins.Get("marginType", &margin_type);
settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type));
if (margin_type == printing::mojom::MarginType::kCustomMargins) {
base::Value::Dict custom_margins;
int top = 0;
margins.Get("top", &top);
custom_margins.Set(printing::kSettingMarginTop, top);
int bottom = 0;
margins.Get("bottom", &bottom);
custom_margins.Set(printing::kSettingMarginBottom, bottom);
int left = 0;
margins.Get("left", &left);
custom_margins.Set(printing::kSettingMarginLeft, left);
int right = 0;
margins.Get("right", &right);
custom_margins.Set(printing::kSettingMarginRight, right);
settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins));
}
} else {
settings.Set(
printing::kSettingMarginsType,
static_cast<int>(printing::mojom::MarginType::kDefaultMargins));
}
// Set whether to print color or greyscale
bool print_color = true;
options.Get("color", &print_color);
auto const color_model = print_color ? printing::mojom::ColorModel::kColor
: printing::mojom::ColorModel::kGray;
settings.Set(printing::kSettingColor, static_cast<int>(color_model));
// Is the orientation landscape or portrait.
bool landscape = false;
options.Get("landscape", &landscape);
settings.Set(printing::kSettingLandscape, landscape);
// We set the default to the system's default printer and only update
// if at the Chromium level if the user overrides.
// Printer device name as opened by the OS.
std::u16string device_name;
options.Get("deviceName", &device_name);
int scale_factor = 100;
options.Get("scaleFactor", &scale_factor);
settings.Set(printing::kSettingScaleFactor, scale_factor);
int pages_per_sheet = 1;
options.Get("pagesPerSheet", &pages_per_sheet);
settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet);
// True if the user wants to print with collate.
bool collate = true;
options.Get("collate", &collate);
settings.Set(printing::kSettingCollate, collate);
// The number of individual copies to print
int copies = 1;
options.Get("copies", &copies);
settings.Set(printing::kSettingCopies, copies);
// Strings to be printed as headers and footers if requested by the user.
std::string header;
options.Get("header", &header);
std::string footer;
options.Get("footer", &footer);
if (!(header.empty() && footer.empty())) {
settings.Set(printing::kSettingHeaderFooterEnabled, true);
settings.Set(printing::kSettingHeaderFooterTitle, header);
settings.Set(printing::kSettingHeaderFooterURL, footer);
} else {
settings.Set(printing::kSettingHeaderFooterEnabled, false);
}
// We don't want to allow the user to enable these settings
// but we need to set them or a CHECK is hit.
settings.Set(printing::kSettingPrinterType,
static_cast<int>(printing::mojom::PrinterType::kLocal));
settings.Set(printing::kSettingShouldPrintSelectionOnly, false);
settings.Set(printing::kSettingRasterizePdf, false);
// Set custom page ranges to print
std::vector<gin_helper::Dictionary> page_ranges;
if (options.Get("pageRanges", &page_ranges)) {
base::Value::List page_range_list;
for (auto& range : page_ranges) {
int from, to;
if (range.Get("from", &from) && range.Get("to", &to)) {
base::Value::Dict range_dict;
// Chromium uses 1-based page ranges, so increment each by 1.
range_dict.Set(printing::kSettingPageRangeFrom, from + 1);
range_dict.Set(printing::kSettingPageRangeTo, to + 1);
page_range_list.Append(std::move(range_dict));
} else {
continue;
}
}
if (!page_range_list.empty())
settings.Set(printing::kSettingPageRange, std::move(page_range_list));
}
// Duplex type user wants to use.
printing::mojom::DuplexMode duplex_mode =
printing::mojom::DuplexMode::kSimplex;
options.Get("duplexMode", &duplex_mode);
settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode));
// We've already done necessary parameter sanitization at the
// JS level, so we can simply pass this through.
base::Value media_size(base::Value::Type::DICT);
if (options.Get("mediaSize", &media_size))
settings.Set(printing::kSettingMediaSize, std::move(media_size));
// Set custom dots per inch (dpi)
gin_helper::Dictionary dpi_settings;
int dpi = 72;
if (options.Get("dpi", &dpi_settings)) {
int horizontal = 72;
dpi_settings.Get("horizontal", &horizontal);
settings.Set(printing::kSettingDpiHorizontal, horizontal);
int vertical = 72;
dpi_settings.Get("vertical", &vertical);
settings.Set(printing::kSettingDpiVertical, vertical);
} else {
settings.Set(printing::kSettingDpiHorizontal, dpi);
settings.Set(printing::kSettingDpiVertical, dpi);
}
print_task_runner_->PostTaskAndReplyWithResult(
FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name),
base::BindOnce(&WebContents::OnGetDeviceNameToUse,
weak_factory_.GetWeakPtr(), std::move(settings),
std::move(callback), silent));
}
// Partially duplicated and modified from
// headless/lib/browser/protocol/page_handler.cc;l=41
v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
// This allows us to track headless printing calls.
auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID);
auto landscape = settings.GetDict().FindBool("landscape");
auto display_header_footer =
settings.GetDict().FindBool("displayHeaderFooter");
auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds");
auto scale = settings.GetDict().FindDouble("scale");
auto paper_width = settings.GetDict().FindDouble("paperWidth");
auto paper_height = settings.GetDict().FindDouble("paperHeight");
auto margin_top = settings.GetDict().FindDouble("marginTop");
auto margin_bottom = settings.GetDict().FindDouble("marginBottom");
auto margin_left = settings.GetDict().FindDouble("marginLeft");
auto margin_right = settings.GetDict().FindDouble("marginRight");
auto page_ranges = *settings.GetDict().FindString("pageRanges");
auto header_template = *settings.GetDict().FindString("headerTemplate");
auto footer_template = *settings.GetDict().FindString("footerTemplate");
auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize");
auto generate_tagged_pdf =
settings.GetDict().FindBool("shouldGenerateTaggedPDF");
absl::variant<printing::mojom::PrintPagesParamsPtr, std::string>
print_pages_params = print_to_pdf::GetPrintPagesParams(
web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(),
landscape, display_header_footer, print_background, scale,
paper_width, paper_height, margin_top, margin_bottom, margin_left,
margin_right, absl::make_optional(header_template),
absl::make_optional(footer_template), prefer_css_page_size,
generate_tagged_pdf);
if (absl::holds_alternative<std::string>(print_pages_params)) {
auto error = absl::get<std::string>(print_pages_params);
promise.RejectWithErrorMessage("Invalid print parameters: " + error);
return handle;
}
auto* manager = PrintViewManagerElectron::FromWebContents(web_contents());
if (!manager) {
promise.RejectWithErrorMessage("Failed to find print manager");
return handle;
}
auto params = std::move(
absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params));
params->params->document_cookie = unique_id.value_or(0);
manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges,
std::move(params),
base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(),
std::move(promise)));
return handle;
}
void WebContents::OnPDFCreated(
gin_helper::Promise<v8::Local<v8::Value>> promise,
print_to_pdf::PdfPrintResult print_result,
scoped_refptr<base::RefCountedMemory> data) {
if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) {
promise.RejectWithErrorMessage(
"Failed to generate PDF: " +
print_to_pdf::PdfPrintResultToString(print_result));
return;
}
v8::Isolate* isolate = promise.isolate();
gin_helper::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate, promise.GetContext()));
v8::Local<v8::Value> buffer =
node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()),
data->size())
.ToLocalChecked();
promise.Resolve(buffer);
}
#endif
void WebContents::AddWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsAddFileSystem(std::string(), path);
}
void WebContents::RemoveWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsRemoveFileSystem(path);
}
void WebContents::Undo() {
web_contents()->Undo();
}
void WebContents::Redo() {
web_contents()->Redo();
}
void WebContents::Cut() {
web_contents()->Cut();
}
void WebContents::Copy() {
web_contents()->Copy();
}
void WebContents::CenterSelection() {
web_contents()->CenterSelection();
}
void WebContents::Paste() {
web_contents()->Paste();
}
void WebContents::PasteAndMatchStyle() {
web_contents()->PasteAndMatchStyle();
}
void WebContents::Delete() {
web_contents()->Delete();
}
void WebContents::SelectAll() {
web_contents()->SelectAll();
}
void WebContents::Unselect() {
web_contents()->CollapseSelection();
}
void WebContents::ScrollToTopOfDocument() {
web_contents()->ScrollToTopOfDocument();
}
void WebContents::ScrollToBottomOfDocument() {
web_contents()->ScrollToBottomOfDocument();
}
void WebContents::AdjustSelectionByCharacterOffset(gin::Arguments* args) {
int start_adjust = 0;
int end_adjust = 0;
gin_helper::Dictionary dict;
if (args->GetNext(&dict)) {
dict.Get("start", &start_adjust);
dict.Get("matchCase", &end_adjust);
}
// The selection menu is a Chrome-specific piece of UI.
// TODO(codebytere): maybe surface as an event in the future?
web_contents()->AdjustSelectionByCharacterOffset(
start_adjust, end_adjust, false /* show_selection_menu */);
}
void WebContents::Replace(const std::u16string& word) {
web_contents()->Replace(word);
}
void WebContents::ReplaceMisspelling(const std::u16string& word) {
web_contents()->ReplaceMisspelling(word);
}
uint32_t WebContents::FindInPage(gin::Arguments* args) {
std::u16string search_text;
if (!args->GetNext(&search_text) || search_text.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must provide a non-empty search content");
return 0;
}
uint32_t request_id = ++find_in_page_request_id_;
gin_helper::Dictionary dict;
auto options = blink::mojom::FindOptions::New();
if (args->GetNext(&dict)) {
dict.Get("forward", &options->forward);
dict.Get("matchCase", &options->match_case);
dict.Get("findNext", &options->new_session);
}
web_contents()->Find(request_id, search_text, std::move(options));
return request_id;
}
void WebContents::StopFindInPage(content::StopFindAction action) {
web_contents()->StopFinding(action);
}
void WebContents::ShowDefinitionForSelection() {
#if BUILDFLAG(IS_MAC)
auto* const view = web_contents()->GetRenderWidgetHostView();
if (view)
view->ShowDefinitionForSelection();
#endif
}
void WebContents::CopyImageAt(int x, int y) {
auto* const host = web_contents()->GetPrimaryMainFrame();
if (host)
host->CopyImageAt(x, y);
}
void WebContents::Focus() {
// Focusing on WebContents does not automatically focus the window on macOS
// and Linux, do it manually to match the behavior on Windows.
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
if (owner_window())
owner_window()->Focus(true);
#endif
web_contents()->Focus();
}
#if !BUILDFLAG(IS_MAC)
bool WebContents::IsFocused() const {
auto* view = web_contents()->GetRenderWidgetHostView();
if (!view)
return false;
if (GetType() != Type::kBackgroundPage) {
auto* window = web_contents()->GetNativeView()->GetToplevelWindow();
if (window && !window->IsVisible())
return false;
}
return view->HasFocus();
}
#endif
void WebContents::SendInputEvent(v8::Isolate* isolate,
v8::Local<v8::Value> input_event) {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
blink::WebInputEvent::Type type =
gin::GetWebInputEventType(isolate, input_event);
if (blink::WebInputEvent::IsMouseEventType(type)) {
blink::WebMouseEvent mouse_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) {
if (IsOffScreen()) {
GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event);
} else {
rwh->ForwardMouseEvent(mouse_event);
}
return;
}
} else if (blink::WebInputEvent::IsKeyboardEventType(type)) {
content::NativeWebKeyboardEvent keyboard_event(
blink::WebKeyboardEvent::Type::kRawKeyDown,
blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow());
if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) {
// For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`.
if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown)
keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown);
rwh->ForwardKeyboardEvent(keyboard_event);
return;
}
} else if (type == blink::WebInputEvent::Type::kMouseWheel) {
blink::WebMouseWheelEvent mouse_wheel_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
if (IsOffScreen()) {
GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent(
mouse_wheel_event);
} else {
// Chromium expects phase info in wheel events (and applies a
// DCHECK to verify it). See: https://crbug.com/756524.
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
// Send a synthetic wheel event with phaseEnded to finish scrolling.
mouse_wheel_event.has_synthetic_phase = true;
mouse_wheel_event.delta_x = 0;
mouse_wheel_event.delta_y = 0;
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kEventNonBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
}
return;
}
}
isolate->ThrowException(
v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object")));
}
void WebContents::BeginFrameSubscription(gin::Arguments* args) {
bool only_dirty = false;
FrameSubscriber::FrameCaptureCallback callback;
if (args->Length() > 1) {
if (!args->GetNext(&only_dirty)) {
args->ThrowError();
return;
}
}
if (!args->GetNext(&callback)) {
args->ThrowError();
return;
}
frame_subscriber_ =
std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty);
}
void WebContents::EndFrameSubscription() {
frame_subscriber_.reset();
}
void WebContents::StartDrag(const gin_helper::Dictionary& item,
gin::Arguments* args) {
base::FilePath file;
std::vector<base::FilePath> files;
if (!item.Get("files", &files) && item.Get("file", &file)) {
files.push_back(file);
}
v8::Local<v8::Value> icon_value;
if (!item.Get("icon", &icon_value)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'icon' parameter is required");
return;
}
NativeImage* icon = nullptr;
if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) ||
icon->image().IsEmpty()) {
return;
}
// Start dragging.
if (!files.empty()) {
base::CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop allow;
DragFileItems(files, icon->image(), web_contents()->GetNativeView());
} else {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must specify either 'file' or 'files' option");
}
}
v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) {
gin_helper::Promise<gfx::Image> promise(args->isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
gfx::Rect rect;
args->GetNext(&rect);
bool stay_hidden = false;
bool stay_awake = false;
if (args && args->Length() == 2) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("stayHidden", &stay_hidden);
options.Get("stayAwake", &stay_awake);
}
}
auto* const view = web_contents()->GetRenderWidgetHostView();
if (!view) {
promise.Resolve(gfx::Image());
return handle;
}
#if !BUILDFLAG(IS_MAC)
// If the view's renderer is suspended this may fail on Windows/Linux -
// bail if so. See CopyFromSurface in
// content/public/browser/render_widget_host_view.h.
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (rfh &&
rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) {
promise.Resolve(gfx::Image());
return handle;
}
#endif // BUILDFLAG(IS_MAC)
auto capture_handle = web_contents()->IncrementCapturerCount(
rect.size(), stay_hidden, stay_awake);
// Capture full page if user doesn't specify a |rect|.
const gfx::Size view_size =
rect.IsEmpty() ? view->GetViewBounds().size() : rect.size();
// By default, the requested bitmap size is the view size in screen
// coordinates. However, if there's more pixel detail available on the
// current system, increase the requested bitmap size to capture it all.
gfx::Size bitmap_size = view_size;
const gfx::NativeView native_view = view->GetNativeView();
const float scale = display::Screen::GetScreen()
->GetDisplayNearestView(native_view)
.device_scale_factor();
if (scale > 1.0f)
bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size,
base::BindOnce(&OnCapturePageDone, std::move(promise),
std::move(capture_handle)));
return handle;
}
bool WebContents::IsBeingCaptured() {
return web_contents()->IsBeingCaptured();
}
void WebContents::OnCursorChanged(const ui::Cursor& cursor) {
if (cursor.type() == ui::mojom::CursorType::kCustom) {
Emit("cursor-changed", CursorTypeToString(cursor.type()),
gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()),
cursor.image_scale_factor(),
gfx::Size(cursor.custom_bitmap().width(),
cursor.custom_bitmap().height()),
cursor.custom_hotspot());
} else {
Emit("cursor-changed", CursorTypeToString(cursor.type()));
}
}
bool WebContents::IsGuest() const {
return type_ == Type::kWebView;
}
void WebContents::AttachToIframe(content::WebContents* embedder_web_contents,
int embedder_frame_id) {
attached_ = true;
if (guest_delegate_)
guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id);
}
bool WebContents::IsOffScreen() const {
return type_ == Type::kOffScreen;
}
void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap));
}
void WebContents::StartPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(true);
}
void WebContents::StopPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(false);
}
bool WebContents::IsPainting() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv && osr_wcv->IsPainting();
}
void WebContents::SetFrameRate(int frame_rate) {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetFrameRate(frame_rate);
}
int WebContents::GetFrameRate() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv ? osr_wcv->GetFrameRate() : 0;
}
void WebContents::Invalidate() {
if (IsOffScreen()) {
auto* osr_rwhv = GetOffScreenRenderWidgetHostView();
if (osr_rwhv)
osr_rwhv->Invalidate();
} else {
auto* const window = owner_window();
if (window)
window->Invalidate();
}
}
gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) {
if (IsOffScreen() && wc == web_contents()) {
auto* relay = NativeWindowRelay::FromWebContents(web_contents());
if (relay) {
auto* owner_window = relay->GetNativeWindow();
return owner_window ? owner_window->GetSize() : gfx::Size();
}
}
return gfx::Size();
}
void WebContents::SetZoomLevel(double level) {
zoom_controller_->SetZoomLevel(level);
}
double WebContents::GetZoomLevel() const {
return zoom_controller_->GetZoomLevel();
}
void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower,
double factor) {
if (factor < std::numeric_limits<double>::epsilon()) {
thrower.ThrowError("'zoomFactor' must be a double greater than 0.0");
return;
}
auto level = blink::PageZoomFactorToZoomLevel(factor);
SetZoomLevel(level);
}
double WebContents::GetZoomFactor() const {
auto level = GetZoomLevel();
return blink::PageZoomLevelToZoomFactor(level);
}
void WebContents::SetTemporaryZoomLevel(double level) {
zoom_controller_->SetTemporaryZoomLevel(level);
}
void WebContents::DoGetZoomLevel(
electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback
callback) {
std::move(callback).Run(GetZoomLevel());
}
std::vector<base::FilePath> WebContents::GetPreloadPaths() const {
auto result = SessionPreferences::GetValidPreloads(GetBrowserContext());
if (auto* web_preferences = WebContentsPreferences::From(web_contents())) {
base::FilePath preload;
if (web_preferences->GetPreloadPath(&preload)) {
result.emplace_back(preload);
}
}
return result;
}
v8::Local<v8::Value> WebContents::GetLastWebPreferences(
v8::Isolate* isolate) const {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (!web_preferences)
return v8::Null(isolate);
return gin::ConvertToV8(isolate, *web_preferences->last_preference());
}
v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow(
v8::Isolate* isolate) const {
if (owner_window())
return BrowserWindow::From(isolate, owner_window());
else
return v8::Null(isolate);
}
v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
return v8::Local<v8::Value>::New(isolate, session_);
}
content::WebContents* WebContents::HostWebContents() const {
if (!embedder_)
return nullptr;
return embedder_->web_contents();
}
void WebContents::SetEmbedder(const WebContents* embedder) {
if (embedder) {
NativeWindow* owner_window = nullptr;
auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
if (relay) {
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
content::RenderWidgetHostView* rwhv =
web_contents()->GetRenderWidgetHostView();
if (rwhv) {
rwhv->Hide();
rwhv->Show();
}
}
}
void WebContents::SetDevToolsWebContents(const WebContents* devtools) {
if (inspectable_web_contents_)
inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents());
}
v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const {
gfx::NativeView ptr = web_contents()->GetNativeView();
auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr),
sizeof(gfx::NativeView));
if (buffer.IsEmpty())
return v8::Null(isolate);
else
return buffer.ToLocalChecked();
}
v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
if (devtools_web_contents_.IsEmpty())
return v8::Null(isolate);
else
return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
}
v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
if (debugger_.IsEmpty()) {
auto handle = electron::api::Debugger::Create(isolate, web_contents());
debugger_.Reset(isolate, handle.ToV8());
}
return v8::Local<v8::Value>::New(isolate, debugger_);
}
content::RenderFrameHost* WebContents::MainFrame() {
return web_contents()->GetPrimaryMainFrame();
}
content::RenderFrameHost* WebContents::Opener() {
return web_contents()->GetOpener();
}
void WebContents::NotifyUserActivation() {
content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame();
if (frame)
frame->NotifyUserActivation(
blink::mojom::UserActivationNotificationType::kInteraction);
}
void WebContents::SetImageAnimationPolicy(const std::string& new_policy) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
web_preferences->SetImageAnimationPolicy(new_policy);
web_contents()->OnWebPreferencesChanged();
}
void WebContents::OnInputEvent(const blink::WebInputEvent& event) {
Emit("input-event", event);
}
v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage("Failed to create memory dump");
return handle;
}
auto pid = frame_host->GetProcess()->GetProcess().Pid();
v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext());
memory_instrumentation::MemoryInstrumentation::GetInstance()
->RequestGlobalDumpForPid(
pid, std::vector<std::string>(),
base::BindOnce(&ElectronBindings::DidReceiveMemoryDump,
std::move(context), std::move(promise), pid));
return handle;
}
v8::Local<v8::Promise> WebContents::TakeHeapSnapshot(
v8::Isolate* isolate,
const base::FilePath& file_path) {
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
ScopedAllowBlockingForElectron allow_blocking;
uint32_t flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE;
// The snapshot file is passed to an untrusted process.
flags = base::File::AddFlagsForPassingToUntrustedProcess(flags);
base::File file(file_path, flags);
if (!file.IsValid()) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with invalid file path " +
#if BUILDFLAG(IS_WIN)
base::WideToUTF8(file_path.value()));
#else
file_path.value());
#endif
return handle;
}
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with invalid webContents main frame");
return handle;
}
if (!frame_host->IsRenderFrameLive()) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with nonexistent render frame");
return handle;
}
// This dance with `base::Owned` is to ensure that the interface stays alive
// until the callback is called. Otherwise it would be closed at the end of
// this function.
auto electron_renderer =
std::make_unique<mojo::Remote<mojom::ElectronRenderer>>();
frame_host->GetRemoteInterfaces()->GetInterface(
electron_renderer->BindNewPipeAndPassReceiver());
auto* raw_ptr = electron_renderer.get();
(*raw_ptr)->TakeHeapSnapshot(
mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())),
base::BindOnce(
[](mojo::Remote<mojom::ElectronRenderer>* ep,
gin_helper::Promise<void> promise, bool success) {
if (success) {
promise.Resolve();
} else {
promise.RejectWithErrorMessage("Failed to take heap snapshot");
}
},
base::Owned(std::move(electron_renderer)), std::move(promise)));
return handle;
}
void WebContents::UpdatePreferredSize(content::WebContents* web_contents,
const gfx::Size& pref_size) {
Emit("preferred-size-changed", pref_size);
}
bool WebContents::CanOverscrollContent() {
return false;
}
std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper(
content::RenderFrameHost* frame,
content::EyeDropperListener* listener) {
return ShowEyeDropper(frame, listener);
}
void WebContents::RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) {
FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener),
params);
}
void WebContents::EnumerateDirectory(
content::WebContents* web_contents,
scoped_refptr<content::FileSelectListener> listener,
const base::FilePath& path) {
FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path);
}
bool WebContents::IsFullscreenForTabOrPending(
const content::WebContents* source) {
if (!owner_window())
return is_html_fullscreen();
bool in_transition = owner_window()->fullscreen_transition_state() !=
NativeWindow::FullScreenTransitionState::kNone;
bool is_html_transition = owner_window()->fullscreen_transition_type() ==
NativeWindow::FullScreenTransitionType::kHTML;
return is_html_fullscreen() || (in_transition && is_html_transition);
}
content::FullscreenState WebContents::GetFullscreenState(
const content::WebContents* source) const {
// `const_cast` here because EAM does not have const getters
return const_cast<ExclusiveAccessManager*>(&exclusive_access_manager_)
->fullscreen_controller()
->GetFullscreenState(source);
}
bool WebContents::TakeFocus(content::WebContents* source, bool reverse) {
if (source && source->GetOutermostWebContents() == source) {
// If this is the outermost web contents and the user has tabbed or
// shift + tabbed through all the elements, reset the focus back to
// the first or last element so that it doesn't stay in the body.
source->FocusThroughTabTraversal(reverse);
return true;
}
return false;
}
content::PictureInPictureResult WebContents::EnterPictureInPicture(
content::WebContents* web_contents) {
return PictureInPictureWindowManager::GetInstance()
->EnterVideoPictureInPicture(web_contents);
}
void WebContents::ExitPictureInPicture() {
PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture();
}
void WebContents::DevToolsSaveToFile(const std::string& url,
const std::string& content,
bool save_as) {
base::FilePath path;
auto it = saved_files_.find(url);
if (it != saved_files_.end() && !save_as) {
path = it->second;
} else {
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.title = url;
settings.default_path = base::FilePath::FromUTF8Unsafe(url);
if (!file_dialog::ShowSaveDialogSync(settings, &path)) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "canceledSaveURL", base::Value(url));
return;
}
}
saved_files_[url] = path;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "savedURL", base::Value(url),
base::Value(path.AsUTF8Unsafe()));
file_task_runner_->PostTask(FROM_HERE,
base::BindOnce(&WriteToFile, path, content));
}
void WebContents::DevToolsAppendToFile(const std::string& url,
const std::string& content) {
auto it = saved_files_.find(url);
if (it == saved_files_.end())
return;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL",
base::Value(url));
file_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&AppendToFile, it->second, content));
}
void WebContents::DevToolsRequestFileSystems() {
auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents());
if (file_system_paths.empty()) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List()));
return;
}
std::vector<FileSystem> file_systems;
for (const auto& file_system_path : file_system_paths) {
base::FilePath path =
base::FilePath::FromUTF8Unsafe(file_system_path.first);
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
FileSystem file_system =
CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id,
file_system_path.first, file_system_path.second);
file_systems.push_back(file_system);
}
base::Value::List file_system_value;
for (const auto& file_system : file_systems)
file_system_value.Append(CreateFileSystemValue(file_system));
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded",
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsAddFileSystem(
const std::string& type,
const base::FilePath& file_system_path) {
base::FilePath path = file_system_path;
if (path.empty()) {
std::vector<base::FilePath> paths;
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY;
if (!file_dialog::ShowOpenDialogSync(settings, &paths))
return;
path = paths[0];
}
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe()))
return;
FileSystem file_system = CreateFileSystemStruct(
GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type);
base::Value::Dict file_system_value = CreateFileSystemValue(file_system);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Set(path.AsUTF8Unsafe(), type);
std::string error = ""; // No error
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemAdded", base::Value(error),
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsRemoveFileSystem(
const base::FilePath& file_system_path) {
if (!inspectable_web_contents_)
return;
std::string path = file_system_path.AsUTF8Unsafe();
storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath(
file_system_path);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Remove(path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemRemoved", base::Value(path));
}
void WebContents::DevToolsIndexPath(
int request_id,
const std::string& file_system_path,
const std::string& excluded_folders_message) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsIndexingDone(request_id, file_system_path);
return;
}
if (devtools_indexing_jobs_.count(request_id) != 0)
return;
std::vector<std::string> excluded_folders;
absl::optional<base::Value> parsed_excluded_folders =
base::JSONReader::Read(excluded_folders_message);
if (parsed_excluded_folders && parsed_excluded_folders->is_list()) {
for (const base::Value& folder_path : parsed_excluded_folders->GetList()) {
if (folder_path.is_string())
excluded_folders.push_back(folder_path.GetString());
}
}
devtools_indexing_jobs_[request_id] =
scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>(
devtools_file_system_indexer_->IndexPath(
file_system_path, excluded_folders,
base::BindRepeating(
&WebContents::OnDevToolsIndexingWorkCalculated,
weak_factory_.GetWeakPtr(), request_id, file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingWorked,
weak_factory_.GetWeakPtr(), request_id,
file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingDone,
weak_factory_.GetWeakPtr(), request_id,
file_system_path)));
}
void WebContents::DevToolsStopIndexing(int request_id) {
auto it = devtools_indexing_jobs_.find(request_id);
if (it == devtools_indexing_jobs_.end())
return;
it->second->Stop();
devtools_indexing_jobs_.erase(it);
}
void WebContents::DevToolsOpenInNewTab(const std::string& url) {
Emit("devtools-open-url", url);
}
void WebContents::DevToolsSearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsSearchCompleted(request_id, file_system_path,
std::vector<std::string>());
return;
}
devtools_file_system_indexer_->SearchInPath(
file_system_path, query,
base::BindRepeating(&WebContents::OnDevToolsSearchCompleted,
weak_factory_.GetWeakPtr(), request_id,
file_system_path));
}
void WebContents::DevToolsSetEyeDropperActive(bool active) {
auto* web_contents = GetWebContents();
if (!web_contents)
return;
if (active) {
eye_dropper_ = std::make_unique<DevToolsEyeDropper>(
web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper,
base::Unretained(this)));
} else {
eye_dropper_.reset();
}
}
void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) {
base::Value::Dict color;
color.Set("r", r);
color.Set("g", g);
color.Set("b", b);
color.Set("a", a);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color)));
}
#if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
ui::ImageModel WebContents::GetDevToolsWindowIcon() {
return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{};
}
#endif
#if BUILDFLAG(IS_LINUX)
void WebContents::GetDevToolsWindowWMClass(std::string* name,
std::string* class_name) {
*class_name = Browser::Get()->GetName();
*name = base::ToLowerASCII(*class_name);
}
#endif
void WebContents::OnDevToolsIndexingWorkCalculated(
int request_id,
const std::string& file_system_path,
int total_work) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id),
base::Value(file_system_path), base::Value(total_work));
}
void WebContents::OnDevToolsIndexingWorked(int request_id,
const std::string& file_system_path,
int worked) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingWorked", base::Value(request_id),
base::Value(file_system_path), base::Value(worked));
}
void WebContents::OnDevToolsIndexingDone(int request_id,
const std::string& file_system_path) {
devtools_indexing_jobs_.erase(request_id);
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone",
base::Value(request_id),
base::Value(file_system_path));
}
void WebContents::OnDevToolsSearchCompleted(
int request_id,
const std::string& file_system_path,
const std::vector<std::string>& file_paths) {
base::Value::List file_paths_value;
for (const auto& file_path : file_paths)
file_paths_value.Append(file_path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "searchCompleted", base::Value(request_id),
base::Value(file_system_path), base::Value(std::move(file_paths_value)));
}
void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) {
// Window is already in fullscreen mode, save the state.
if (enter_fullscreen && owner_window()->IsFullscreen()) {
native_fullscreen_ = true;
UpdateHtmlApiFullscreen(true);
return;
}
// Exit html fullscreen state but not window's fullscreen mode.
if (!enter_fullscreen && native_fullscreen_) {
UpdateHtmlApiFullscreen(false);
return;
}
// Set fullscreen on window if allowed.
auto* web_preferences = WebContentsPreferences::From(GetWebContents());
bool html_fullscreenable =
web_preferences
? !web_preferences->ShouldDisableHtmlFullscreenWindowResize()
: true;
if (html_fullscreenable)
owner_window_->SetFullScreen(enter_fullscreen);
UpdateHtmlApiFullscreen(enter_fullscreen);
native_fullscreen_ = false;
}
void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) {
if (fullscreen == is_html_fullscreen())
return;
html_fullscreen_ = fullscreen;
// Notify renderer of the html fullscreen change.
web_contents()
->GetRenderViewHost()
->GetWidget()
->SynchronizeVisualProperties();
// The embedder WebContents is separated from the frame tree of webview, so
// we must manually sync their fullscreen states.
if (embedder_)
embedder_->SetHtmlApiFullscreen(fullscreen);
if (fullscreen) {
Emit("enter-html-full-screen");
owner_window_->NotifyWindowEnterHtmlFullScreen();
} else {
Emit("leave-html-full-screen");
owner_window_->NotifyWindowLeaveHtmlFullScreen();
}
// Make sure all child webviews quit html fullscreen.
if (!fullscreen && !IsGuest()) {
auto* manager = WebViewManager::GetWebViewManager(web_contents());
manager->ForEachGuest(
web_contents(), base::BindRepeating([](content::WebContents* guest) {
WebContents* api_web_contents = WebContents::From(guest);
api_web_contents->SetHtmlApiFullscreen(false);
return false;
}));
}
}
// static
void WebContents::FillObjectTemplate(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin::InvokerOptions options;
options.holder_is_first_argument = true;
options.holder_type = GetClassName();
templ->Set(
gin::StringToSymbol(isolate, "isDestroyed"),
gin::CreateFunctionTemplate(
isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed),
options));
// We use gin_helper::ObjectTemplateBuilder instead of
// gin::ObjectTemplateBuilder here to handle the fact that WebContents is
// destroyable.
gin_helper::ObjectTemplateBuilder(isolate, templ)
.SetMethod("destroy", &WebContents::Destroy)
.SetMethod("close", &WebContents::Close)
.SetMethod("getBackgroundThrottling",
&WebContents::GetBackgroundThrottling)
.SetMethod("setBackgroundThrottling",
&WebContents::SetBackgroundThrottling)
.SetMethod("getProcessId", &WebContents::GetProcessID)
.SetMethod("getOSProcessId", &WebContents::GetOSProcessID)
.SetMethod("equal", &WebContents::Equal)
.SetMethod("_loadURL", &WebContents::LoadURL)
.SetMethod("reload", &WebContents::Reload)
.SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache)
.SetMethod("downloadURL", &WebContents::DownloadURL)
.SetMethod("getURL", &WebContents::GetURL)
.SetMethod("getTitle", &WebContents::GetTitle)
.SetMethod("isLoading", &WebContents::IsLoading)
.SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
.SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
.SetMethod("stop", &WebContents::Stop)
.SetMethod("canGoBack", &WebContents::CanGoBack)
.SetMethod("goBack", &WebContents::GoBack)
.SetMethod("canGoForward", &WebContents::CanGoForward)
.SetMethod("goForward", &WebContents::GoForward)
.SetMethod("canGoToOffset", &WebContents::CanGoToOffset)
.SetMethod("goToOffset", &WebContents::GoToOffset)
.SetMethod("canGoToIndex", &WebContents::CanGoToIndex)
.SetMethod("goToIndex", &WebContents::GoToIndex)
.SetMethod("getActiveIndex", &WebContents::GetActiveIndex)
.SetMethod("clearHistory", &WebContents::ClearHistory)
.SetMethod("length", &WebContents::GetHistoryLength)
.SetMethod("isCrashed", &WebContents::IsCrashed)
.SetMethod("forcefullyCrashRenderer",
&WebContents::ForcefullyCrashRenderer)
.SetMethod("setUserAgent", &WebContents::SetUserAgent)
.SetMethod("getUserAgent", &WebContents::GetUserAgent)
.SetMethod("savePage", &WebContents::SavePage)
.SetMethod("openDevTools", &WebContents::OpenDevTools)
.SetMethod("closeDevTools", &WebContents::CloseDevTools)
.SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
.SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
.SetMethod("getDevToolsTitle", &WebContents::GetDevToolsTitle)
.SetMethod("setDevToolsTitle", &WebContents::SetDevToolsTitle)
.SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation)
.SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation)
.SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
.SetMethod("inspectElement", &WebContents::InspectElement)
.SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts)
.SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
.SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
.SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible)
.SetMethod("undo", &WebContents::Undo)
.SetMethod("redo", &WebContents::Redo)
.SetMethod("cut", &WebContents::Cut)
.SetMethod("copy", &WebContents::Copy)
.SetMethod("centerSelection", &WebContents::CenterSelection)
.SetMethod("paste", &WebContents::Paste)
.SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
.SetMethod("delete", &WebContents::Delete)
.SetMethod("selectAll", &WebContents::SelectAll)
.SetMethod("unselect", &WebContents::Unselect)
.SetMethod("scrollToTop", &WebContents::ScrollToTopOfDocument)
.SetMethod("scrollToBottom", &WebContents::ScrollToBottomOfDocument)
.SetMethod("adjustSelection",
&WebContents::AdjustSelectionByCharacterOffset)
.SetMethod("replace", &WebContents::Replace)
.SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
.SetMethod("findInPage", &WebContents::FindInPage)
.SetMethod("stopFindInPage", &WebContents::StopFindInPage)
.SetMethod("focus", &WebContents::Focus)
.SetMethod("isFocused", &WebContents::IsFocused)
.SetMethod("sendInputEvent", &WebContents::SendInputEvent)
.SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription)
.SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
.SetMethod("startDrag", &WebContents::StartDrag)
.SetMethod("attachToIframe", &WebContents::AttachToIframe)
.SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame)
.SetMethod("isOffscreen", &WebContents::IsOffScreen)
.SetMethod("startPainting", &WebContents::StartPainting)
.SetMethod("stopPainting", &WebContents::StopPainting)
.SetMethod("isPainting", &WebContents::IsPainting)
.SetMethod("setFrameRate", &WebContents::SetFrameRate)
.SetMethod("getFrameRate", &WebContents::GetFrameRate)
.SetMethod("invalidate", &WebContents::Invalidate)
.SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
.SetMethod("getZoomLevel", &WebContents::GetZoomLevel)
.SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
.SetMethod("getZoomFactor", &WebContents::GetZoomFactor)
.SetMethod("getType", &WebContents::GetType)
.SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths)
.SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences)
.SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
.SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
.SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker)
.SetMethod("inspectSharedWorkerById",
&WebContents::InspectSharedWorkerById)
.SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers)
#if BUILDFLAG(ENABLE_PRINTING)
.SetMethod("_print", &WebContents::Print)
.SetMethod("_printToPDF", &WebContents::PrintToPDF)
#endif
.SetMethod("_setNextChildWebPreferences",
&WebContents::SetNextChildWebPreferences)
.SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
.SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
.SetMethod("showDefinitionForSelection",
&WebContents::ShowDefinitionForSelection)
.SetMethod("copyImageAt", &WebContents::CopyImageAt)
.SetMethod("capturePage", &WebContents::CapturePage)
.SetMethod("setEmbedder", &WebContents::SetEmbedder)
.SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents)
.SetMethod("getNativeView", &WebContents::GetNativeView)
.SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured)
.SetMethod("setWebRTCIPHandlingPolicy",
&WebContents::SetWebRTCIPHandlingPolicy)
.SetMethod("setWebRTCUDPPortRange", &WebContents::SetWebRTCUDPPortRange)
.SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID)
.SetMethod("getWebRTCIPHandlingPolicy",
&WebContents::GetWebRTCIPHandlingPolicy)
.SetMethod("getWebRTCUDPPortRange", &WebContents::GetWebRTCUDPPortRange)
.SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot)
.SetMethod("setImageAnimationPolicy",
&WebContents::SetImageAnimationPolicy)
.SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo)
.SetProperty("id", &WebContents::ID)
.SetProperty("session", &WebContents::Session)
.SetProperty("hostWebContents", &WebContents::HostWebContents)
.SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
.SetProperty("debugger", &WebContents::Debugger)
.SetProperty("mainFrame", &WebContents::MainFrame)
.SetProperty("opener", &WebContents::Opener)
.Build();
}
const char* WebContents::GetTypeName() {
return GetClassName();
}
ElectronBrowserContext* WebContents::GetBrowserContext() const {
return static_cast<ElectronBrowserContext*>(
web_contents()->GetBrowserContext());
}
// static
gin::Handle<WebContents> WebContents::New(
v8::Isolate* isolate,
const gin_helper::Dictionary& options) {
gin::Handle<WebContents> handle =
gin::CreateHandle(isolate, new WebContents(isolate, options));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
gin::Handle<WebContents> WebContents::CreateAndTake(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type) {
gin::Handle<WebContents> handle = gin::CreateHandle(
isolate, new WebContents(isolate, std::move(web_contents), type));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
WebContents* WebContents::From(content::WebContents* web_contents) {
if (!web_contents)
return nullptr;
auto* data = static_cast<UserDataLink*>(
web_contents->GetUserData(kElectronApiWebContentsKey));
return data ? data->web_contents.get() : nullptr;
}
// static
gin::Handle<WebContents> WebContents::FromOrCreate(
v8::Isolate* isolate,
content::WebContents* web_contents) {
WebContents* api_web_contents = From(web_contents);
if (!api_web_contents) {
api_web_contents = new WebContents(isolate, web_contents);
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, api_web_contents, "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
}
return gin::CreateHandle(isolate, api_web_contents);
}
// static
gin::Handle<WebContents> WebContents::CreateFromWebPreferences(
v8::Isolate* isolate,
const gin_helper::Dictionary& web_preferences) {
// Check if webPreferences has |webContents| option.
gin::Handle<WebContents> web_contents;
if (web_preferences.GetHidden("webContents", &web_contents) &&
!web_contents.IsEmpty()) {
// Set webPreferences from options if using an existing webContents.
// These preferences will be used when the webContent launches new
// render processes.
auto* existing_preferences =
WebContentsPreferences::From(web_contents->web_contents());
gin_helper::Dictionary web_preferences_dict;
if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(),
&web_preferences_dict)) {
existing_preferences->SetFromDictionary(web_preferences_dict);
absl::optional<SkColor> color =
existing_preferences->GetBackgroundColor();
web_contents->web_contents()->SetPageBaseBackgroundColor(color);
// Because web preferences don't recognize transparency,
// only set rwhv background color if a color exists
auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView();
if (rwhv && color.has_value())
SetBackgroundColor(rwhv, color.value());
}
} else {
// Create one if not.
web_contents = WebContents::New(isolate, web_preferences);
}
return web_contents;
}
// static
WebContents* WebContents::FromID(int32_t id) {
return GetAllWebContents().Lookup(id);
}
// static
std::list<WebContents*> WebContents::GetWebContentsList() {
std::list<WebContents*> list;
for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
!iter.IsAtEnd(); iter.Advance()) {
list.push_back(iter.GetCurrentValue());
}
return list;
}
// static
gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin};
} // namespace electron::api
namespace {
using electron::api::GetAllWebContents;
using electron::api::WebContents;
using electron::api::WebFrameMain;
gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) {
WebContents* contents = WebContents::FromID(id);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromFrame(v8::Isolate* isolate,
WebFrameMain* web_frame) {
content::RenderFrameHost* rfh = web_frame->render_frame_host();
content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh);
WebContents* contents = WebContents::From(source);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromDevToolsTargetID(
v8::Isolate* isolate,
std::string target_id) {
auto agent_host = content::DevToolsAgentHost::GetForId(target_id);
WebContents* contents =
agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr;
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8(
v8::Isolate* isolate) {
std::vector<gin::Handle<WebContents>> list;
for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
!iter.IsAtEnd(); iter.Advance()) {
list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue()));
}
return list;
}
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("WebContents", WebContents::GetConstructor(context));
dict.SetMethod("fromId", &WebContentsFromID);
dict.SetMethod("fromFrame", &WebContentsFromFrame);
dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID);
dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8);
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 31,992 |
[Bug]: webContents.capturePage() returns empty image for fully occluded BrowserWindow on 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 feature request that matches the one I want to file, without success.
### Electron Version
16.0.1
### What operating system are you using?
Windows
### Operating System Version
Windows 11 (10.0.22000.348)
### What arch are you using?
x64
### Last Known Working Electron version
10.4.7
### Expected Behavior
`webContents.capturePage()` should work for fully occluded BrowserWindow as the window is not minimized.
### Actual Behavior
`webContents.capturePage()` returns an empty `NativeImage` in this case.
### Testcase Gist URL
_No response_
### Additional Information
main.js for Fiddle
```js
const {app, BrowserWindow} = require('electron')
function createWindow () {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
})
setInterval(async () => {
const image = await mainWindow.capturePage();
console.log(image.getSize())
}, 1000);
mainWindow.loadFile('about:blank')
mainWindow.webContents.openDevTools({mode:'detach'})
}
app.whenReady().then(() => {
createWindow()
})
app.on('window-all-closed', function () {
app.quit()
})
```
to reproduce cover the BrowserWindow with the devtools, you'll see the image size being logged as `{ width: 0, height: 0 }`.
This is a regression from #27883, when I revert the change `webContents.capturePage()` is working correctly for occluded windows. Checking the visibility state does not seem correct to me as both occluded and minimized windows' webContents have visibilityState hidden.
The abandoned fix #27892 seems like a better option. Also according to the documentation of `CopyFromSurface`:
> // |callback| is guaranteed to be run, either synchronously or at some point
> // in the future (depending on the platform implementation and the current
> // state of the Surface). If the copy failed, the bitmap's drawsNothing()
> // method will return true.
> //
> // If the view's renderer is suspended (see WasOccluded()), this may result in
> // copying old data or failing.
> virtual void CopyFromSurface(
> const gfx::Rect& src_rect,
> const gfx::Size& output_size,
> base::OnceCallback<void(const SkBitmap&)> callback) = 0;
|
https://github.com/electron/electron/issues/31992
|
https://github.com/electron/electron/pull/39730
|
3e70692e4b3044a10e5b1e5148a97a3f62bec4cb
|
5c821d33791345446eef3a90a6bea9c920d001d8
| 2021-11-25T03:07:41Z |
c++
| 2023-10-12T07:35:23Z |
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));
for (const win of windows) win.show();
for (const win of windows) win.focus();
for (const win of windows) 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(async () => {
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('');
}
});
url = (await listen(server)).url;
});
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(async () => {
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('');
}
});
url = (await listen(server)).url;
});
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()', () => {
afterEach(closeAllWindows);
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);
});
it('should not crash when called on a modal child window', async () => {
const shown = once(w, 'show');
w.show();
await shown;
const child = new BrowserWindow({ modal: true, parent: w });
expect(() => { child.moveTop(); }).to.not.throw();
});
});
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'
];
for (const sourceId of fakeSourceIds) {
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];
for (const sourceId of fakeSourceIds) {
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'];
for (const sourceId of fakeSourceIds) {
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(closeAllWindows);
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('BrowserWindow.tabbingIdentifier', () => {
it('is undefined if no tabbingIdentifier was set', () => {
const w = new BrowserWindow({ show: false });
expect(w.tabbingIdentifier).to.be.undefined('tabbingIdentifier');
});
it('returns the window tabbingIdentifier', () => {
const w = new BrowserWindow({ show: false, tabbingIdentifier: 'group1' });
expect(w.tabbingIdentifier).to.equal('group1');
});
});
});
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._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);
});
});
});
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.replaceAll('\\', '/')
: 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.replaceAll('\\', '/')
: 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 });
const errorPattern = /Failed to read a named property 'document' from 'Window': Blocked a frame with origin "(.*?)" from accessing a cross-origin frame./;
expect(popupAccessMessage).to.be.a('string',
'child\'s .document is accessible from its parent window');
expect(popupAccessMessage).to.match(errorPattern);
expect(openerAccessMessage).to.be.a('string',
'opener .document is accessible from a popup window');
expect(openerAccessMessage).to.match(errorPattern);
});
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('Failed to read a named property \'toString\' from \'Location\': 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');
});
});
// TODO(codebytere): figure out how to make these pass in CI on Windows.
ifdescribe(process.platform !== 'win32')('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');
});
it('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');
}
});
it('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');
});
it('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');
});
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');
}
});
it('visibilityState remains visible if backgroundThrottling is disabled', async () => {
const w = new BrowserWindow({
show: false,
width: 100,
height: 100,
webPreferences: {
backgroundThrottling: false,
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');
}
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')('only shows the intended window when a child with siblings is shown', async () => {
const w = new BrowserWindow({ show: false });
const childOne = new BrowserWindow({ show: false, parent: w });
const childTwo = new BrowserWindow({ show: false, parent: w });
const parentShown = once(w, 'show');
w.show();
await parentShown;
expect(childOne.isVisible()).to.be.false('childOne is visible');
expect(childTwo.isVisible()).to.be.false('childTwo is visible');
const childOneShown = once(childOne, 'show');
childOne.show();
await childOneShown;
expect(childOne.isVisible()).to.be.true('childOne is not visible');
expect(childTwo.isVisible()).to.be.false('childTwo is visible');
});
ifit(process.platform === 'darwin')('child matches parent visibility when parent 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')('parent matches child visibility when child 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', async () => {
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();
const closed = once(childWindow, 'closed');
window.close();
await closed;
expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw();
});
});
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');
});
});
it('does not open non-fullscreenable child windows in fullscreen if parent is fullscreen', async () => {
const w = new BrowserWindow();
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
const child = new BrowserWindow({ parent: w, resizable: false, fullscreenable: false });
const shown = once(child, 'show');
await shown;
expect(child.resizable).to.be.false('resizable');
expect(child.fullScreen).to.be.false('fullscreen');
expect(child.fullScreenable).to.be.false('fullscreenable');
});
it('is set correctly with different resizable values', async () => {
const w1 = new BrowserWindow({
resizable: false,
fullscreenable: false
});
const w2 = new BrowserWindow({
resizable: true,
fullscreenable: false
});
const w3 = new BrowserWindow({
fullscreenable: false
});
expect(w1.isFullScreenable()).to.be.false('isFullScreenable');
expect(w2.isFullScreenable()).to.be.false('isFullScreenable');
expect(w3.isFullScreenable()).to.be.false('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 });
const isValidWindow = require('@electron-ci/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(1000);
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(1000);
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');
await setTimeout(1000);
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
| 31,992 |
[Bug]: webContents.capturePage() returns empty image for fully occluded BrowserWindow on 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 feature request that matches the one I want to file, without success.
### Electron Version
16.0.1
### What operating system are you using?
Windows
### Operating System Version
Windows 11 (10.0.22000.348)
### What arch are you using?
x64
### Last Known Working Electron version
10.4.7
### Expected Behavior
`webContents.capturePage()` should work for fully occluded BrowserWindow as the window is not minimized.
### Actual Behavior
`webContents.capturePage()` returns an empty `NativeImage` in this case.
### Testcase Gist URL
_No response_
### Additional Information
main.js for Fiddle
```js
const {app, BrowserWindow} = require('electron')
function createWindow () {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
})
setInterval(async () => {
const image = await mainWindow.capturePage();
console.log(image.getSize())
}, 1000);
mainWindow.loadFile('about:blank')
mainWindow.webContents.openDevTools({mode:'detach'})
}
app.whenReady().then(() => {
createWindow()
})
app.on('window-all-closed', function () {
app.quit()
})
```
to reproduce cover the BrowserWindow with the devtools, you'll see the image size being logged as `{ width: 0, height: 0 }`.
This is a regression from #27883, when I revert the change `webContents.capturePage()` is working correctly for occluded windows. Checking the visibility state does not seem correct to me as both occluded and minimized windows' webContents have visibilityState hidden.
The abandoned fix #27892 seems like a better option. Also according to the documentation of `CopyFromSurface`:
> // |callback| is guaranteed to be run, either synchronously or at some point
> // in the future (depending on the platform implementation and the current
> // state of the Surface). If the copy failed, the bitmap's drawsNothing()
> // method will return true.
> //
> // If the view's renderer is suspended (see WasOccluded()), this may result in
> // copying old data or failing.
> virtual void CopyFromSurface(
> const gfx::Rect& src_rect,
> const gfx::Size& output_size,
> base::OnceCallback<void(const SkBitmap&)> callback) = 0;
|
https://github.com/electron/electron/issues/31992
|
https://github.com/electron/electron/pull/39730
|
3e70692e4b3044a10e5b1e5148a97a3f62bec4cb
|
5c821d33791345446eef3a90a6bea9c920d001d8
| 2021-11-25T03:07:41Z |
c++
| 2023-10-12T07:35:23Z |
shell/browser/api/electron_api_web_contents.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_web_contents.h"
#include <limits>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/containers/contains.h"
#include "base/containers/fixed_flat_map.h"
#include "base/containers/id_map.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/current_thread.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
#include "chrome/browser/ui/views/eye_dropper/eye_dropper.h"
#include "chrome/common/pref_names.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/security_state/content/content_utils.h"
#include "components/security_state/core/security_state.h"
#include "content/browser/renderer_host/frame_tree_node.h" // nogncheck
#include "content/browser/renderer_host/navigation_controller_impl.h" // nogncheck
#include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/desktop_media_id.h"
#include "content/public/browser/desktop_streams_registry.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/service_worker_context.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/input/native_web_keyboard_event.h"
#include "content/public/common/referrer_type_converters.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/webplugininfo.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "gin/arguments.h"
#include "gin/data_object_builder.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "media/base/mime_util.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "ppapi/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "printing/print_job_constants.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/browser/api/electron_api_browser_window.h"
#include "shell/browser/api/electron_api_debugger.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/api/electron_api_web_frame_main.h"
#include "shell/browser/api/message_port.h"
#include "shell/browser/browser.h"
#include "shell/browser/child_web_contents_tracker.h"
#include "shell/browser/electron_autofill_driver_factory.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/electron_javascript_dialog_manager.h"
#include "shell/browser/electron_navigation_throttle.h"
#include "shell/browser/file_select_helper.h"
#include "shell/browser/native_window.h"
#include "shell/browser/osr/osr_render_widget_host_view.h"
#include "shell/browser/osr/osr_web_contents_view.h"
#include "shell/browser/session_preferences.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/file_dialog.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/browser/web_contents_zoom_controller.h"
#include "shell/browser/web_view_guest_delegate.h"
#include "shell/browser/web_view_manager.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/color_util.h"
#include "shell/common/electron_constants.h"
#include "shell/common/gin_converters/base_converter.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/content_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/frame_converter.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/optional_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/language_util.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "shell/common/thread_restrictions.h"
#include "shell/common/v8_value_serializer.h"
#include "storage/browser/file_system/isolated_context.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/mojom/frame/find_in_page.mojom.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h"
#include "third_party/blink/public/mojom/renderer_preferences.mojom.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
#if BUILDFLAG(IS_WIN)
#include "shell/browser/native_window_views.h"
#endif
#if !BUILDFLAG(IS_MAC)
#include "ui/aura/window.h"
#else
#include "ui/base/cocoa/defaults_utils.h"
#endif
#if BUILDFLAG(IS_LINUX)
#include "ui/linux/linux_ui.h"
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
#include "ui/gfx/font_render_params.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/script_executor.h"
#include "extensions/browser/view_type_utils.h"
#include "extensions/common/mojom/view_type.mojom.h"
#include "shell/browser/extensions/electron_extension_web_contents_observer.h"
#endif
#if BUILDFLAG(ENABLE_PRINTING)
#include "chrome/browser/printing/print_view_manager_base.h"
#include "components/printing/browser/print_manager_utils.h"
#include "components/printing/browser/print_to_pdf/pdf_print_result.h"
#include "components/printing/browser/print_to_pdf/pdf_print_utils.h"
#include "printing/backend/print_backend.h" // nogncheck
#include "printing/mojom/print.mojom.h" // nogncheck
#include "printing/page_range.h"
#include "shell/browser/printing/print_view_manager_electron.h"
#if BUILDFLAG(IS_WIN)
#include "printing/backend/win_helper.h"
#endif
#endif // BUILDFLAG(ENABLE_PRINTING)
#if BUILDFLAG(ENABLE_PDF_VIEWER)
#include "components/pdf/browser/pdf_document_helper.h" // nogncheck
#include "shell/browser/electron_pdf_document_helper_client.h"
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/public/browser/plugin_service.h"
#endif
#if !IS_MAS_BUILD()
#include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck
#endif
namespace gin {
#if BUILDFLAG(ENABLE_PRINTING)
template <>
struct Converter<printing::mojom::MarginType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::MarginType* out) {
using Val = printing::mojom::MarginType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"custom", Val::kCustomMargins},
{"default", Val::kDefaultMargins},
{"none", Val::kNoMargins},
{"printableArea", Val::kPrintableAreaMargins},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<printing::mojom::DuplexMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::DuplexMode* out) {
using Val = printing::mojom::DuplexMode;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"longEdge", Val::kLongEdge},
{"shortEdge", Val::kShortEdge},
{"simplex", Val::kSimplex},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
#endif
template <>
struct Converter<WindowOpenDisposition> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
WindowOpenDisposition val) {
std::string disposition = "other";
switch (val) {
case WindowOpenDisposition::CURRENT_TAB:
disposition = "default";
break;
case WindowOpenDisposition::NEW_FOREGROUND_TAB:
disposition = "foreground-tab";
break;
case WindowOpenDisposition::NEW_BACKGROUND_TAB:
disposition = "background-tab";
break;
case WindowOpenDisposition::NEW_POPUP:
case WindowOpenDisposition::NEW_WINDOW:
disposition = "new-window";
break;
case WindowOpenDisposition::SAVE_TO_DISK:
disposition = "save-to-disk";
break;
default:
break;
}
return gin::ConvertToV8(isolate, disposition);
}
};
template <>
struct Converter<content::SavePageType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
content::SavePageType* out) {
using Val = content::SavePageType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"htmlcomplete", Val::SAVE_PAGE_TYPE_AS_COMPLETE_HTML},
{"htmlonly", Val::SAVE_PAGE_TYPE_AS_ONLY_HTML},
{"mhtml", Val::SAVE_PAGE_TYPE_AS_MHTML},
});
return FromV8WithLowerLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<electron::api::WebContents::Type> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
electron::api::WebContents::Type val) {
using Type = electron::api::WebContents::Type;
std::string type;
switch (val) {
case Type::kBackgroundPage:
type = "backgroundPage";
break;
case Type::kBrowserWindow:
type = "window";
break;
case Type::kBrowserView:
type = "browserView";
break;
case Type::kRemote:
type = "remote";
break;
case Type::kWebView:
type = "webview";
break;
case Type::kOffScreen:
type = "offscreen";
break;
default:
break;
}
return gin::ConvertToV8(isolate, type);
}
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::api::WebContents::Type* out) {
using Val = electron::api::WebContents::Type;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"backgroundPage", Val::kBackgroundPage},
{"browserView", Val::kBrowserView},
{"offscreen", Val::kOffScreen},
{"webview", Val::kWebView},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<scoped_refptr<content::DevToolsAgentHost>> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const scoped_refptr<content::DevToolsAgentHost>& val) {
gin_helper::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("id", val->GetId());
dict.Set("url", val->GetURL().spec());
return dict.GetHandle();
}
};
} // namespace gin
namespace electron::api {
namespace {
constexpr base::StringPiece CursorTypeToString(
ui::mojom::CursorType cursor_type) {
switch (cursor_type) {
case ui::mojom::CursorType::kPointer:
return "pointer";
case ui::mojom::CursorType::kCross:
return "crosshair";
case ui::mojom::CursorType::kHand:
return "hand";
case ui::mojom::CursorType::kIBeam:
return "text";
case ui::mojom::CursorType::kWait:
return "wait";
case ui::mojom::CursorType::kHelp:
return "help";
case ui::mojom::CursorType::kEastResize:
return "e-resize";
case ui::mojom::CursorType::kNorthResize:
return "n-resize";
case ui::mojom::CursorType::kNorthEastResize:
return "ne-resize";
case ui::mojom::CursorType::kNorthWestResize:
return "nw-resize";
case ui::mojom::CursorType::kSouthResize:
return "s-resize";
case ui::mojom::CursorType::kSouthEastResize:
return "se-resize";
case ui::mojom::CursorType::kSouthWestResize:
return "sw-resize";
case ui::mojom::CursorType::kWestResize:
return "w-resize";
case ui::mojom::CursorType::kNorthSouthResize:
return "ns-resize";
case ui::mojom::CursorType::kEastWestResize:
return "ew-resize";
case ui::mojom::CursorType::kNorthEastSouthWestResize:
return "nesw-resize";
case ui::mojom::CursorType::kNorthWestSouthEastResize:
return "nwse-resize";
case ui::mojom::CursorType::kColumnResize:
return "col-resize";
case ui::mojom::CursorType::kRowResize:
return "row-resize";
case ui::mojom::CursorType::kMiddlePanning:
return "m-panning";
case ui::mojom::CursorType::kMiddlePanningVertical:
return "m-panning-vertical";
case ui::mojom::CursorType::kMiddlePanningHorizontal:
return "m-panning-horizontal";
case ui::mojom::CursorType::kEastPanning:
return "e-panning";
case ui::mojom::CursorType::kNorthPanning:
return "n-panning";
case ui::mojom::CursorType::kNorthEastPanning:
return "ne-panning";
case ui::mojom::CursorType::kNorthWestPanning:
return "nw-panning";
case ui::mojom::CursorType::kSouthPanning:
return "s-panning";
case ui::mojom::CursorType::kSouthEastPanning:
return "se-panning";
case ui::mojom::CursorType::kSouthWestPanning:
return "sw-panning";
case ui::mojom::CursorType::kWestPanning:
return "w-panning";
case ui::mojom::CursorType::kMove:
return "move";
case ui::mojom::CursorType::kVerticalText:
return "vertical-text";
case ui::mojom::CursorType::kCell:
return "cell";
case ui::mojom::CursorType::kContextMenu:
return "context-menu";
case ui::mojom::CursorType::kAlias:
return "alias";
case ui::mojom::CursorType::kProgress:
return "progress";
case ui::mojom::CursorType::kNoDrop:
return "nodrop";
case ui::mojom::CursorType::kCopy:
return "copy";
case ui::mojom::CursorType::kNone:
return "none";
case ui::mojom::CursorType::kNotAllowed:
return "not-allowed";
case ui::mojom::CursorType::kZoomIn:
return "zoom-in";
case ui::mojom::CursorType::kZoomOut:
return "zoom-out";
case ui::mojom::CursorType::kGrab:
return "grab";
case ui::mojom::CursorType::kGrabbing:
return "grabbing";
case ui::mojom::CursorType::kCustom:
return "custom";
case ui::mojom::CursorType::kNull:
return "null";
case ui::mojom::CursorType::kDndNone:
return "drag-drop-none";
case ui::mojom::CursorType::kDndMove:
return "drag-drop-move";
case ui::mojom::CursorType::kDndCopy:
return "drag-drop-copy";
case ui::mojom::CursorType::kDndLink:
return "drag-drop-link";
case ui::mojom::CursorType::kNorthSouthNoResize:
return "ns-no-resize";
case ui::mojom::CursorType::kEastWestNoResize:
return "ew-no-resize";
case ui::mojom::CursorType::kNorthEastSouthWestNoResize:
return "nesw-no-resize";
case ui::mojom::CursorType::kNorthWestSouthEastNoResize:
return "nwse-no-resize";
default:
return "default";
}
}
base::IDMap<WebContents*>& GetAllWebContents() {
static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents;
return *s_all_web_contents;
}
void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise,
base::ScopedClosureRunner capture_handle,
const SkBitmap& bitmap) {
// Hack to enable transparency in captured image
promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap));
capture_handle.RunAndReset();
}
absl::optional<base::TimeDelta> GetCursorBlinkInterval() {
#if BUILDFLAG(IS_MAC)
absl::optional<base::TimeDelta> system_value(
ui::TextInsertionCaretBlinkPeriodFromDefaults());
if (system_value)
return *system_value;
#elif BUILDFLAG(IS_LINUX)
if (auto* linux_ui = ui::LinuxUi::instance())
return linux_ui->GetCursorBlinkInterval();
#elif BUILDFLAG(IS_WIN)
const auto system_msec = ::GetCaretBlinkTime();
if (system_msec != 0) {
return (system_msec == INFINITE) ? base::TimeDelta()
: base::Milliseconds(system_msec);
}
#endif
return absl::nullopt;
}
#if BUILDFLAG(ENABLE_PRINTING)
// This will return false if no printer with the provided device_name can be
// found on the network. We need to check this because Chromium does not do
// sanity checking of device_name validity and so will crash on invalid names.
bool IsDeviceNameValid(const std::u16string& device_name) {
#if BUILDFLAG(IS_MAC)
base::apple::ScopedCFTypeRef<CFStringRef> new_printer_id(
base::SysUTF16ToCFStringRef(device_name));
PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get());
bool printer_exists = new_printer != nullptr;
PMRelease(new_printer);
return printer_exists;
#else
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name));
#endif
}
// This function returns a validated device name.
// If the user passed one to webContents.print(), we check that it's valid and
// return it or fail if the network doesn't recognize it. If the user didn't
// pass a device name, we first try to return the system default printer. If one
// isn't set, then pull all the printers and use the first one or fail if none
// exist.
std::pair<std::string, std::u16string> GetDeviceNameToUse(
const std::u16string& device_name) {
#if BUILDFLAG(IS_WIN)
// Blocking is needed here because Windows printer drivers are oftentimes
// not thread-safe and have to be accessed on the UI thread.
ScopedAllowBlockingForElectron allow_blocking;
#endif
if (!device_name.empty()) {
if (!IsDeviceNameValid(device_name))
return std::make_pair("Invalid deviceName provided", std::u16string());
return std::make_pair(std::string(), device_name);
}
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
std::string printer_name;
printing::mojom::ResultCode code =
print_backend->GetDefaultPrinterName(printer_name);
// We don't want to return if this fails since some devices won't have a
// default printer.
if (code != printing::mojom::ResultCode::kSuccess)
LOG(ERROR) << "Failed to get default printer name";
if (printer_name.empty()) {
printing::PrinterList printers;
if (print_backend->EnumeratePrinters(printers) !=
printing::mojom::ResultCode::kSuccess)
return std::make_pair("Failed to enumerate printers", std::u16string());
if (printers.empty())
return std::make_pair("No printers available on the network",
std::u16string());
printer_name = printers.front().printer_name;
}
return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name));
}
// Copied from
// chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54
scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() {
// USER_VISIBLE because the result is displayed in the print preview dialog.
#if !BUILDFLAG(IS_WIN)
static constexpr base::TaskTraits kTraits = {
base::MayBlock(), base::TaskPriority::USER_VISIBLE};
#endif
#if defined(USE_CUPS)
// CUPS is thread safe.
return base::ThreadPool::CreateTaskRunner(kTraits);
#elif BUILDFLAG(IS_WIN)
// Windows drivers are likely not thread-safe and need to be accessed on the
// UI thread.
return content::GetUIThreadTaskRunner({base::TaskPriority::USER_VISIBLE});
#else
// Be conservative on unsupported platforms.
return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits);
#endif
}
#endif
struct UserDataLink : public base::SupportsUserData::Data {
explicit UserDataLink(base::WeakPtr<WebContents> contents)
: web_contents(contents) {}
base::WeakPtr<WebContents> web_contents;
};
const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey;
const char kRootName[] = "<root>";
struct FileSystem {
FileSystem() = default;
FileSystem(const std::string& type,
const std::string& file_system_name,
const std::string& root_url,
const std::string& file_system_path)
: type(type),
file_system_name(file_system_name),
root_url(root_url),
file_system_path(file_system_path) {}
std::string type;
std::string file_system_name;
std::string root_url;
std::string file_system_path;
};
std::string RegisterFileSystem(content::WebContents* web_contents,
const base::FilePath& path) {
auto* isolated_context = storage::IsolatedContext::GetInstance();
std::string root_name(kRootName);
storage::IsolatedContext::ScopedFSHandle file_system =
isolated_context->RegisterFileSystemForPath(
storage::kFileSystemTypeLocal, std::string(), path, &root_name);
content::ChildProcessSecurityPolicy* policy =
content::ChildProcessSecurityPolicy::GetInstance();
content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
int renderer_id = render_view_host->GetProcess()->GetID();
policy->GrantReadFileSystem(renderer_id, file_system.id());
policy->GrantWriteFileSystem(renderer_id, file_system.id());
policy->GrantCreateFileForFileSystem(renderer_id, file_system.id());
policy->GrantDeleteFromFileSystem(renderer_id, file_system.id());
if (!policy->CanReadFile(renderer_id, path))
policy->GrantReadFile(renderer_id, path);
return file_system.id();
}
FileSystem CreateFileSystemStruct(content::WebContents* web_contents,
const std::string& file_system_id,
const std::string& file_system_path,
const std::string& type) {
const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL();
std::string file_system_name =
storage::GetIsolatedFileSystemName(origin, file_system_id);
std::string root_url = storage::GetIsolatedFileSystemRootURIString(
origin, file_system_id, kRootName);
return FileSystem(type, file_system_name, root_url, file_system_path);
}
base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) {
base::Value::Dict value;
value.Set("type", file_system.type);
value.Set("fileSystemName", file_system.file_system_name);
value.Set("rootURL", file_system.root_url);
value.Set("fileSystemPath", file_system.file_system_path);
return value;
}
void WriteToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::WriteFile(path, content.data(), content.size());
}
void AppendToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::AppendToFile(path, content);
}
PrefService* GetPrefService(content::WebContents* web_contents) {
auto* context = web_contents->GetBrowserContext();
return static_cast<electron::ElectronBrowserContext*>(context)->prefs();
}
std::map<std::string, std::string> GetAddedFileSystemPaths(
content::WebContents* web_contents) {
auto* pref_service = GetPrefService(web_contents);
const base::Value::Dict& file_system_paths =
pref_service->GetDict(prefs::kDevToolsFileSystemPaths);
std::map<std::string, std::string> result;
for (auto it : file_system_paths) {
std::string type =
it.second.is_string() ? it.second.GetString() : std::string();
result[it.first] = type;
}
return result;
}
bool IsDevToolsFileSystemAdded(content::WebContents* web_contents,
const std::string& file_system_path) {
return base::Contains(GetAddedFileSystemPaths(web_contents),
file_system_path);
}
void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) {
rwhv->SetBackgroundColor(color);
static_cast<content::RenderWidgetHostViewBase*>(rwhv)
->SetContentBackgroundColor(color);
}
content::RenderFrameHost* GetRenderFrameHost(
content::NavigationHandle* navigation_handle) {
int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId();
content::FrameTreeNode* frame_tree_node =
content::FrameTreeNode::GloballyFindByID(frame_tree_node_id);
content::RenderFrameHostManager* render_manager =
frame_tree_node->render_manager();
content::RenderFrameHost* frame_host = nullptr;
if (render_manager) {
frame_host = render_manager->speculative_frame_host();
if (!frame_host)
frame_host = render_manager->current_frame_host();
}
return frame_host;
}
} // namespace
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) {
switch (view_type) {
case extensions::mojom::ViewType::kExtensionBackgroundPage:
return WebContents::Type::kBackgroundPage;
case extensions::mojom::ViewType::kAppWindow:
case extensions::mojom::ViewType::kComponent:
case extensions::mojom::ViewType::kExtensionDialog:
case extensions::mojom::ViewType::kExtensionPopup:
case extensions::mojom::ViewType::kBackgroundContents:
case extensions::mojom::ViewType::kExtensionGuest:
case extensions::mojom::ViewType::kTabContents:
case extensions::mojom::ViewType::kOffscreenDocument:
case extensions::mojom::ViewType::kExtensionSidePanel:
case extensions::mojom::ViewType::kInvalid:
return WebContents::Type::kRemote;
}
}
#endif
WebContents::WebContents(v8::Isolate* isolate,
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
type_(Type::kRemote),
id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// WebContents created by extension host will have valid ViewType set.
extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents);
if (view_type != extensions::mojom::ViewType::kInvalid) {
InitWithExtensionView(isolate, web_contents, view_type);
}
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents);
script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents);
#endif
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
SetUserAgent(GetBrowserContext()->GetUserAgent());
web_contents->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type)
: content::WebContentsObserver(web_contents.get()),
type_(type),
id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
DCHECK(type != Type::kRemote)
<< "Can't take ownership of a remote WebContents";
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
InitWithSessionAndOptions(isolate, std::move(web_contents), session,
gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
const gin_helper::Dictionary& options)
: id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
// Read options.
options.Get("backgroundThrottling", &background_throttling_);
// Get type
options.Get("type", &type_);
bool b = false;
if (options.Get(options::kOffscreen, &b) && b)
type_ = Type::kOffScreen;
// Init embedder earlier
options.Get("embedder", &embedder_);
// Whether to enable DevTools.
options.Get("devTools", &enable_devtools_);
// BrowserViews are not attached to a window initially so they should start
// off as hidden. This is also important for compositor recycling. See:
// https://github.com/electron/electron/pull/21372
bool initially_shown = type_ != Type::kBrowserView;
options.Get(options::kShow, &initially_shown);
// Obtain the session.
std::string partition;
gin::Handle<api::Session> session;
if (options.Get("session", &session) && !session.IsEmpty()) {
} else if (options.Get("partition", &partition)) {
session = Session::FromPartition(isolate, partition);
} else {
// Use the default session if not specified.
session = Session::FromPartition(isolate, "");
}
session_.Reset(isolate, session.ToV8());
std::unique_ptr<content::WebContents> web_contents;
if (IsGuest()) {
scoped_refptr<content::SiteInstance> site_instance =
content::SiteInstance::CreateForURL(session->browser_context(),
GURL("chrome-guest://fake-host"));
content::WebContents::CreateParams params(session->browser_context(),
site_instance);
guest_delegate_ =
std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this);
params.guest_delegate = guest_delegate_.get();
if (embedder_ && embedder_->IsOffScreen()) {
auto* view = new OffScreenWebContentsView(
false,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
web_contents = content::WebContents::Create(params);
}
} else if (IsOffScreen()) {
// webPreferences does not have a transparent option, so if the window needs
// to be transparent, that will be set at electron_api_browser_window.cc#L57
// and we then need to pull it back out and check it here.
std::string background_color;
options.GetHidden(options::kBackgroundColor, &background_color);
bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT;
content::WebContents::CreateParams params(session->browser_context());
auto* view = new OffScreenWebContentsView(
transparent,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
content::WebContents::CreateParams params(session->browser_context());
params.initially_hidden = !initially_shown;
web_contents = content::WebContents::Create(params);
}
InitWithSessionAndOptions(isolate, std::move(web_contents), session, options);
}
void WebContents::InitZoomController(content::WebContents* web_contents,
const gin_helper::Dictionary& options) {
WebContentsZoomController::CreateForWebContents(web_contents);
zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
double zoom_factor;
if (options.Get(options::kZoomFactor, &zoom_factor))
zoom_controller_->SetDefaultZoomFactor(zoom_factor);
// Nothing to do with ZoomController, but this function gets called in all
// init cases!
content::RenderViewHost* host = web_contents->GetRenderViewHost();
if (host)
host->GetWidget()->AddInputEventObserver(this);
}
void WebContents::InitWithSessionAndOptions(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> owned_web_contents,
gin::Handle<api::Session> session,
const gin_helper::Dictionary& options) {
Observe(owned_web_contents.get());
InitWithWebContents(std::move(owned_web_contents), session->browser_context(),
IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
auto* prefs = web_contents()->GetMutableRendererPrefs();
// Collect preferred languages from OS and browser process. accept_languages
// effects HTTP header, navigator.languages, and CJK fallback font selection.
//
// Note that an application locale set to the browser process might be
// different with the one set to the preference list.
// (e.g. overridden with --lang)
std::string accept_languages =
g_browser_process->GetApplicationLocale() + ",";
for (auto const& language : electron::GetPreferredLanguages()) {
if (language == g_browser_process->GetApplicationLocale())
continue;
accept_languages += language + ",";
}
accept_languages.pop_back();
prefs->accept_languages = accept_languages;
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
// Update font settings.
static const gfx::FontRenderParams params(
gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr));
prefs->should_antialias_text = params.antialiasing;
prefs->use_subpixel_positioning = params.subpixel_positioning;
prefs->hinting = params.hinting;
prefs->use_autohinter = params.autohinter;
prefs->use_bitmaps = params.use_bitmaps;
prefs->subpixel_rendering = params.subpixel_rendering;
#endif
// Honor the system's cursor blink rate settings
if (auto interval = GetCursorBlinkInterval())
prefs->caret_blink_interval = *interval;
// Save the preferences in C++.
// If there's already a WebContentsPreferences object, we created it as part
// of the webContents.setWindowOpenHandler path, so don't overwrite it.
if (!WebContentsPreferences::From(web_contents())) {
new WebContentsPreferences(web_contents(), options);
}
// Trigger re-calculation of webkit prefs.
web_contents()->NotifyPreferencesChanged();
WebContentsPermissionHelper::CreateForWebContents(web_contents());
InitZoomController(web_contents(), options);
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents());
script_executor_ =
std::make_unique<extensions::ScriptExecutor>(web_contents());
#endif
AutofillDriverFactory::CreateForWebContents(web_contents());
SetUserAgent(GetBrowserContext()->GetUserAgent());
if (IsGuest()) {
NativeWindow* owner_window = nullptr;
if (embedder_) {
// New WebContents's owner_window is the embedder's owner_window.
auto* relay =
NativeWindowRelay::FromWebContents(embedder_->web_contents());
if (relay)
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
}
web_contents()->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
void WebContents::InitWithExtensionView(v8::Isolate* isolate,
content::WebContents* web_contents,
extensions::mojom::ViewType view_type) {
// Must reassign type prior to calling `Init`.
type_ = GetTypeFromViewType(view_type);
if (type_ == Type::kRemote)
return;
if (type_ == Type::kBackgroundPage)
// non-background-page WebContents are retained by other classes. We need
// to pin here to prevent background-page WebContents from being GC'd.
// The background page api::WebContents will live until the underlying
// content::WebContents is destroyed.
Pin(isolate);
// Allow toggling DevTools for background pages
Observe(web_contents);
InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents),
GetBrowserContext(), IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
}
#endif
void WebContents::InitWithWebContents(
std::unique_ptr<content::WebContents> web_contents,
ElectronBrowserContext* browser_context,
bool is_guest) {
browser_context_ = browser_context;
web_contents->SetDelegate(this);
#if BUILDFLAG(ENABLE_PRINTING)
PrintViewManagerElectron::CreateForWebContents(web_contents.get());
#endif
// Determine whether the WebContents is offscreen.
auto* web_preferences = WebContentsPreferences::From(web_contents.get());
offscreen_ = web_preferences && web_preferences->IsOffscreen();
// Create InspectableWebContents.
inspectable_web_contents_ = std::make_unique<InspectableWebContents>(
std::move(web_contents), browser_context->prefs(), is_guest);
inspectable_web_contents_->SetDelegate(this);
}
WebContents::~WebContents() {
if (owner_window_) {
owner_window_->RemoveBackgroundThrottlingSource(this);
}
if (web_contents()) {
content::RenderViewHost* host = web_contents()->GetRenderViewHost();
if (host)
host->GetWidget()->RemoveInputEventObserver(this);
}
if (!inspectable_web_contents_) {
WebContentsDestroyed();
return;
}
inspectable_web_contents_->GetView()->SetDelegate(nullptr);
// This event is only for internal use, which is emitted when WebContents is
// being destroyed.
Emit("will-destroy");
// For guest view based on OOPIF, the WebContents is released by the embedder
// frame, and we need to clear the reference to the memory.
bool not_owned_by_this = IsGuest() && attached_;
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// And background pages are owned by extensions::ExtensionHost.
if (type_ == Type::kBackgroundPage)
not_owned_by_this = true;
#endif
if (not_owned_by_this) {
inspectable_web_contents_->ReleaseWebContents();
WebContentsDestroyed();
}
// InspectableWebContents will be automatically destroyed.
}
void WebContents::DeleteThisIfAlive() {
// It is possible that the FirstWeakCallback has been called but the
// SecondWeakCallback has not, in this case the garbage collection of
// WebContents has already started and we should not |delete this|.
// Calling |GetWrapper| can detect this corner case.
auto* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
delete this;
}
void WebContents::Destroy() {
// The content::WebContents should be destroyed asynchronously when possible
// as user may choose to destroy WebContents during an event of it.
if (Browser::Get()->is_shutting_down() || IsGuest()) {
DeleteThisIfAlive();
} else {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&WebContents::DeleteThisIfAlive, GetWeakPtr()));
}
}
void WebContents::Close(absl::optional<gin_helper::Dictionary> options) {
bool dispatch_beforeunload = false;
if (options)
options->Get("waitForBeforeUnload", &dispatch_beforeunload);
if (dispatch_beforeunload &&
web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) {
NotifyUserActivation();
web_contents()->DispatchBeforeUnload(false /* auto_cancel */);
} else {
web_contents()->Close();
}
}
bool WebContents::DidAddMessageToConsole(
content::WebContents* source,
blink::mojom::ConsoleMessageLevel level,
const std::u16string& message,
int32_t line_no,
const std::u16string& source_id) {
return Emit("console-message", static_cast<int32_t>(level), message, line_no,
source_id);
}
void WebContents::OnCreateWindow(
const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const std::string& features,
const scoped_refptr<network::ResourceRequestBody>& body) {
Emit("-new-window", target_url, frame_name, disposition, features, referrer,
body);
}
void WebContents::WebContentsCreatedWithFullParams(
content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const content::mojom::CreateNewWindowParams& params,
content::WebContents* new_contents) {
ChildWebContentsTracker::CreateForWebContents(new_contents);
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents);
tracker->url = params.target_url;
tracker->frame_name = params.frame_name;
tracker->referrer = params.referrer.To<content::Referrer>();
tracker->raw_features = params.raw_features;
tracker->body = params.body;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary dict;
gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate),
&dict);
pending_child_web_preferences_.Reset();
// Associate the preferences passed in via `setWindowOpenHandler` with the
// content::WebContents that was just created for the child window. These
// preferences will be picked up by the RenderWidgetHost via its call to the
// delegate's OverrideWebkitPrefs.
new WebContentsPreferences(new_contents, dict);
}
bool WebContents::IsWebContentsCreationOverridden(
content::SiteInstance* source_site_instance,
content::mojom::WindowContainerType window_container_type,
const GURL& opener_url,
const content::mojom::CreateNewWindowParams& params) {
bool default_prevented = Emit(
"-will-add-new-contents", params.target_url, params.frame_name,
params.raw_features, params.disposition, *params.referrer, params.body);
// If the app prevented the default, redirect to CreateCustomWebContents,
// which always returns nullptr, which will result in the window open being
// prevented (window.open() will return null in the renderer).
return default_prevented;
}
void WebContents::SetNextChildWebPreferences(
const gin_helper::Dictionary preferences) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
// Store these prefs for when Chrome calls WebContentsCreatedWithFullParams
// with the new child contents.
pending_child_web_preferences_.Reset(isolate, preferences.GetHandle());
}
content::WebContents* WebContents::CreateCustomWebContents(
content::RenderFrameHost* opener,
content::SiteInstance* source_site_instance,
bool is_new_browsing_instance,
const GURL& opener_url,
const std::string& frame_name,
const GURL& target_url,
const content::StoragePartitionConfig& partition_config,
content::SessionStorageNamespace* session_storage_namespace) {
return nullptr;
}
void WebContents::AddNewContents(
content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) {
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get());
DCHECK(tracker);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto api_web_contents =
CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow);
// We call RenderFrameCreated here as at this point the empty "about:blank"
// render frame has already been created. If the window never navigates again
// RenderFrameCreated won't be called and certain prefs like
// "kBackgroundColor" will not be applied.
auto* frame = api_web_contents->MainFrame();
if (frame) {
api_web_contents->HandleNewRenderFrame(frame);
}
if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
window_features.bounds.x(), window_features.bounds.y(),
window_features.bounds.width(), window_features.bounds.height(),
tracker->url, tracker->frame_name, tracker->referrer,
tracker->raw_features, tracker->body)) {
api_web_contents->Destroy();
}
}
content::WebContents* WebContents::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
auto weak_this = GetWeakPtr();
if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {
Emit("-new-window", params.url, "", params.disposition, "", params.referrer,
params.post_data);
return nullptr;
}
if (!weak_this || !web_contents())
return nullptr;
content::NavigationController::LoadURLParams load_url_params(params.url);
load_url_params.referrer = params.referrer;
load_url_params.transition_type = params.transition;
load_url_params.extra_headers = params.extra_headers;
load_url_params.should_replace_current_entry =
params.should_replace_current_entry;
load_url_params.is_renderer_initiated = params.is_renderer_initiated;
load_url_params.started_from_context_menu = params.started_from_context_menu;
load_url_params.initiator_origin = params.initiator_origin;
load_url_params.source_site_instance = params.source_site_instance;
load_url_params.frame_tree_node_id = params.frame_tree_node_id;
load_url_params.redirect_chain = params.redirect_chain;
load_url_params.has_user_gesture = params.user_gesture;
load_url_params.blob_url_loader_factory = params.blob_url_loader_factory;
load_url_params.href_translate = params.href_translate;
load_url_params.reload_type = params.reload_type;
if (params.post_data) {
load_url_params.load_type =
content::NavigationController::LOAD_TYPE_HTTP_POST;
load_url_params.post_data = params.post_data;
}
source->GetController().LoadURLWithParams(load_url_params);
return source;
}
void WebContents::BeforeUnloadFired(content::WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) {
if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen ||
type_ == Type::kBrowserView)
*proceed_to_fire_unload = proceed;
else
*proceed_to_fire_unload = true;
// Note that Chromium does not emit this for navigations.
Emit("before-unload-fired", proceed);
}
void WebContents::SetContentsBounds(content::WebContents* source,
const gfx::Rect& rect) {
if (!Emit("content-bounds-updated", rect))
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnSetContentBounds(rect);
}
void WebContents::CloseContents(content::WebContents* source) {
Emit("close");
auto* autofill_driver_factory =
AutofillDriverFactory::FromWebContents(web_contents());
if (autofill_driver_factory) {
autofill_driver_factory->CloseAllPopups();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnCloseContents();
// This is handled by the embedder frame.
if (!IsGuest())
Destroy();
}
void WebContents::ActivateContents(content::WebContents* source) {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnActivateContents();
}
void WebContents::UpdateTargetURL(content::WebContents* source,
const GURL& url) {
Emit("update-target-url", url);
}
bool WebContents::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (type_ == Type::kWebView && embedder_) {
// Send the unhandled keyboard events back to the embedder.
return embedder_->HandleKeyboardEvent(source, event);
} else {
return PlatformHandleKeyboardEvent(source, event);
}
}
#if !BUILDFLAG(IS_MAC)
// NOTE: The macOS version of this function is found in
// electron_api_web_contents_mac.mm, as it requires calling into objective-C
// code.
bool WebContents::PlatformHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
// Escape exits tabbed fullscreen mode.
if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) {
ExitFullscreenModeForTab(source);
return true;
}
// Check if the webContents has preferences and to ignore shortcuts
auto* web_preferences = WebContentsPreferences::From(source);
if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts())
return false;
// Let the NativeWindow handle other parts.
if (owner_window()) {
owner_window()->HandleKeyboardEvent(source, event);
return true;
}
return false;
}
#endif
content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (exclusive_access_manager_.HandleUserKeyEvent(event))
return content::KeyboardEventProcessingResult::HANDLED;
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown ||
event.GetType() == blink::WebInputEvent::Type::kKeyUp) {
// For backwards compatibility, pretend that `kRawKeyDown` events are
// actually `kKeyDown`.
content::NativeWebKeyboardEvent tweaked_event(event);
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown)
tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown);
bool prevent_default = Emit("before-input-event", tweaked_event);
if (prevent_default) {
return content::KeyboardEventProcessingResult::HANDLED;
}
}
return content::KeyboardEventProcessingResult::NOT_HANDLED;
}
void WebContents::ContentsZoomChange(bool zoom_in) {
Emit("zoom-changed", zoom_in ? "in" : "out");
}
Profile* WebContents::GetProfile() {
return nullptr;
}
bool WebContents::IsFullscreen() const {
if (!owner_window())
return false;
return owner_window()->IsFullscreen() || is_html_fullscreen();
}
void WebContents::EnterFullscreen(const GURL& url,
ExclusiveAccessBubbleType bubble_type,
const int64_t display_id) {}
void WebContents::ExitFullscreen() {}
void WebContents::UpdateExclusiveAccessExitBubbleContent(
const GURL& url,
ExclusiveAccessBubbleType bubble_type,
ExclusiveAccessBubbleHideCallback bubble_first_hide_callback,
bool notify_download,
bool force_update) {}
void WebContents::OnExclusiveAccessUserInput() {}
content::WebContents* WebContents::GetActiveWebContents() {
return web_contents();
}
bool WebContents::CanUserExitFullscreen() const {
return true;
}
bool WebContents::IsExclusiveAccessBubbleDisplayed() const {
return false;
}
void WebContents::EnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options) {
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(source);
auto callback =
base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab,
base::Unretained(this), requesting_frame, options);
permission_helper->RequestFullscreenPermission(requesting_frame, callback);
}
void WebContents::OnEnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options,
bool allowed) {
if (!allowed || !owner_window())
return;
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
if (IsFullscreenForTabOrPending(source)) {
DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame());
return;
}
owner_window()->set_fullscreen_transition_type(
NativeWindow::FullScreenTransitionType::kHTML);
exclusive_access_manager_.fullscreen_controller()->EnterFullscreenModeForTab(
requesting_frame, options.display_id);
SetHtmlApiFullscreen(true);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
if (!owner_window())
return;
// This needs to be called before we exit fullscreen on the native window,
// or the controller will incorrectly think we weren't fullscreen and bail.
exclusive_access_manager_.fullscreen_controller()->ExitFullscreenModeForTab(
source);
SetHtmlApiFullscreen(false);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too. Chrome does this indirectly from
// `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::RendererUnresponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host,
base::RepeatingClosure hang_monitor_restarter) {
Emit("unresponsive");
}
void WebContents::RendererResponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host) {
Emit("responsive");
}
bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) {
Emit("context-menu", std::make_pair(params, &render_frame_host));
return true;
}
void WebContents::FindReply(content::WebContents* web_contents,
int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update) {
if (!final_update)
return;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto result = gin_helper::Dictionary::CreateEmpty(isolate);
result.Set("requestId", request_id);
result.Set("matches", number_of_matches);
result.Set("selectionArea", selection_rect);
result.Set("activeMatchOrdinal", active_match_ordinal);
result.Set("finalUpdate", final_update); // Deprecate after 2.0
Emit("found-in-page", result.GetHandle());
}
void WebContents::RequestExclusivePointerAccess(
content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target,
bool allowed) {
if (allowed) {
exclusive_access_manager_.mouse_lock_controller()->RequestToLockMouse(
web_contents, user_gesture, last_unlocked_by_target);
} else {
web_contents->GotResponseToLockMouseRequest(
blink::mojom::PointerLockResult::kPermissionDenied);
}
}
void WebContents::RequestToLockMouse(content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestPointerLockPermission(
user_gesture, last_unlocked_by_target,
base::BindOnce(&WebContents::RequestExclusivePointerAccess,
base::Unretained(this)));
}
void WebContents::LostMouseLock() {
exclusive_access_manager_.mouse_lock_controller()->LostMouseLock();
}
void WebContents::RequestKeyboardLock(content::WebContents* web_contents,
bool esc_key_locked) {
exclusive_access_manager_.keyboard_lock_controller()->RequestKeyboardLock(
web_contents, esc_key_locked);
}
void WebContents::CancelKeyboardLockRequest(
content::WebContents* web_contents) {
exclusive_access_manager_.keyboard_lock_controller()
->CancelKeyboardLockRequest(web_contents);
}
bool WebContents::CheckMediaAccessPermission(
content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::mojom::MediaStreamType type) {
auto* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
return permission_helper->CheckMediaAccessPermission(security_origin, type);
}
void WebContents::RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestMediaAccessPermission(request, std::move(callback));
}
content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager(
content::WebContents* source) {
if (!dialog_manager_)
dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>();
return dialog_manager_.get();
}
void WebContents::OnAudioStateChanged(bool audible) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
gin::Dictionary dict(isolate, event_object);
dict.Set("audible", audible);
EmitWithoutEvent("audio-state-changed", event);
}
void WebContents::BeforeUnloadFired(bool proceed) {
// Do nothing, we override this method just to avoid compilation error since
// there are two virtual functions named BeforeUnloadFired.
}
void WebContents::HandleNewRenderFrame(
content::RenderFrameHost* render_frame_host) {
auto* rwhv = render_frame_host->GetView();
if (!rwhv)
return;
// Set the background color of RenderWidgetHostView.
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences) {
auto maybe_color = web_preferences->GetBackgroundColor();
bool guest = IsGuest() || type_ == Type::kBrowserView;
// If webPreferences has no color stored we need to explicitly set guest
// webContents background color to transparent.
auto bg_color =
maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE);
web_contents()->SetPageBaseBackgroundColor(bg_color);
SetBackgroundColor(rwhv, bg_color);
}
if (!background_throttling_)
render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false);
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (rwh_impl)
rwh_impl->disable_hidden_ = !background_throttling_;
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->MaybeSetupMojoConnection();
}
void WebContents::OnBackgroundColorChanged() {
absl::optional<SkColor> color = web_contents()->GetBackgroundColor();
if (color.has_value()) {
auto* const view = web_contents()->GetRenderWidgetHostView();
static_cast<content::RenderWidgetHostViewBase*>(view)
->SetContentBackgroundColor(color.value());
}
}
void WebContents::RenderFrameCreated(
content::RenderFrameHost* render_frame_host) {
HandleNewRenderFrame(render_frame_host);
// RenderFrameCreated is called for speculative frames which may not be
// used in certain cross-origin navigations. Invoking
// RenderFrameHost::GetLifecycleState currently crashes when called for
// speculative frames so we need to filter it out for now. Check
// https://crbug.com/1183639 for details on when this can be removed.
auto* rfh_impl =
static_cast<content::RenderFrameHostImpl*>(render_frame_host);
if (rfh_impl->lifecycle_state() ==
content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) {
return;
}
content::RenderFrameHost::LifecycleState lifecycle_state =
render_frame_host->GetLifecycleState();
if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.SetGetter("frame", render_frame_host);
Emit("frame-created", details);
}
}
void WebContents::RenderFrameDeleted(
content::RenderFrameHost* render_frame_host) {
// A RenderFrameHost can be deleted when:
// - A WebContents is removed and its containing frames are disposed.
// - An <iframe> is removed from the DOM.
// - Cross-origin navigation creates a new RFH in a separate process which
// is swapped by content::RenderFrameHostManager.
//
// WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID
// to find an existing instance of WebFrameMain. During a cross-origin
// navigation, the deleted RFH will be the old host which was swapped out. In
// this special case, we need to also ensure that WebFrameMain's internal RFH
// matches before marking it as disposed.
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame && web_frame->render_frame_host() == render_frame_host)
web_frame->MarkRenderFrameDisposed();
}
void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) {
if (new_host->IsInPrimaryMainFrame()) {
if (old_host)
old_host->GetRenderWidgetHost()->RemoveInputEventObserver(this);
if (new_host)
new_host->GetRenderWidgetHost()->AddInputEventObserver(this);
}
// During cross-origin navigation, a FrameTreeNode will swap out its RFH.
// If an instance of WebFrameMain exists, it will need to have its RFH
// swapped as well.
//
// |old_host| can be a nullptr so we use |new_host| for looking up the
// WebFrameMain instance.
auto* web_frame = WebFrameMain::FromRenderFrameHost(new_host);
if (web_frame) {
web_frame->UpdateRenderFrameHost(new_host);
}
}
void WebContents::FrameDeleted(int frame_tree_node_id) {
auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id);
if (web_frame)
web_frame->Destroyed();
}
void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
// This event is necessary for tracking any states with respect to
// intermediate render view hosts aka speculative render view hosts. Currently
// used by object-registry.js to ref count remote objects.
Emit("render-view-deleted", render_view_host->GetProcess()->GetID());
if (web_contents()->GetRenderViewHost() == render_view_host) {
// When the RVH that has been deleted is the current RVH it means that the
// the web contents are being closed. This is communicated by this event.
// Currently tracked by guest-window-manager.ts to destroy the
// BrowserWindow.
Emit("current-render-view-deleted",
render_view_host->GetProcess()->GetID());
}
}
void WebContents::PrimaryMainFrameRenderProcessGone(
base::TerminationStatus status) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("reason", status);
details.Set("exitCode", web_contents()->GetCrashedErrorCode());
Emit("render-process-gone", details);
}
void WebContents::PluginCrashed(const base::FilePath& plugin_path,
base::ProcessId plugin_pid) {
#if BUILDFLAG(ENABLE_PLUGINS)
content::WebPluginInfo info;
auto* plugin_service = content::PluginService::GetInstance();
plugin_service->GetPluginInfoByPath(plugin_path, &info);
Emit("plugin-crashed", info.name, info.version);
#endif // BUILDFLAG(ENABLE_PLUGINS)
}
void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id) {
Emit("media-started-playing");
}
void WebContents::MediaStoppedPlaying(
const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id,
content::WebContentsObserver::MediaStoppedReason reason) {
Emit("media-paused");
}
void WebContents::DidChangeThemeColor() {
auto theme_color = web_contents()->GetThemeColor();
if (theme_color) {
Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value()));
} else {
Emit("did-change-theme-color", nullptr);
}
}
void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) {
set_fullscreen_frame(rfh);
}
void WebContents::OnWebContentsFocused(
content::RenderWidgetHost* render_widget_host) {
Emit("focus");
}
void WebContents::OnWebContentsLostFocus(
content::RenderWidgetHost* render_widget_host) {
Emit("blur");
}
void WebContents::DOMContentLoaded(
content::RenderFrameHost* render_frame_host) {
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->DOMContentLoaded();
if (!render_frame_host->GetParent())
Emit("dom-ready");
}
void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url) {
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
auto weak_this = GetWeakPtr();
Emit("did-frame-finish-load", is_main_frame, frame_process_id,
frame_routing_id);
// β οΈWARNING!β οΈ
// Emit() triggers JS which can call destroy() on |this|. It's not safe to
// assume that |this| points to valid memory at this point.
if (is_main_frame && weak_this && web_contents())
Emit("did-finish-load");
}
void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
const GURL& url,
int error_code) {
// See DocumentLoader::StartLoadingResponse() - when we navigate to a media
// resource the original request for the media resource, which resulted in a
// committed navigation, is simply discarded. The media element created
// inside the MediaDocument then makes *another new* request for the same
// media resource.
bool is_media_document =
media::IsSupportedMediaMimeType(web_contents()->GetContentsMimeType());
if (error_code == net::ERR_ABORTED && is_media_document)
return;
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id,
frame_routing_id);
}
void WebContents::DidStartLoading() {
Emit("did-start-loading");
}
void WebContents::DidStopLoading() {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences && web_preferences->ShouldUsePreferredSizeMode())
web_contents()->GetRenderViewHost()->EnablePreferredSizeMode();
Emit("did-stop-loading");
}
bool WebContents::EmitNavigationEvent(
const std::string& event_name,
content::NavigationHandle* navigation_handle) {
bool is_main_frame = navigation_handle->IsInMainFrame();
int frame_process_id = -1, frame_routing_id = -1;
content::RenderFrameHost* frame_host = GetRenderFrameHost(navigation_handle);
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
bool is_same_document = navigation_handle->IsSameDocument();
auto url = navigation_handle->GetURL();
content::RenderFrameHost* initiator_frame_host =
navigation_handle->GetInitiatorFrameToken().has_value()
? content::RenderFrameHost::FromFrameToken(
navigation_handle->GetInitiatorProcessId(),
navigation_handle->GetInitiatorFrameToken().value())
: nullptr;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
gin_helper::Dictionary dict(isolate, event_object);
dict.Set("url", url);
dict.Set("isSameDocument", is_same_document);
dict.Set("isMainFrame", is_main_frame);
dict.Set("frame", frame_host);
dict.SetGetter("initiator", initiator_frame_host);
EmitWithoutEvent(event_name, event, url, is_same_document, is_main_frame,
frame_process_id, frame_routing_id);
return event->GetDefaultPrevented();
}
void WebContents::Message(bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Message", "channel", channel);
// webContents.emit('-ipc-message', new Event(), internal, channel,
// arguments);
EmitWithSender("-ipc-message", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), internal,
channel, std::move(arguments));
}
void WebContents::Invoke(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::InvokeCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel);
// webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments);
EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::OnFirstNonEmptyLayout(
content::RenderFrameHost* render_frame_host) {
if (render_frame_host == web_contents()->GetPrimaryMainFrame()) {
Emit("ready-to-show");
}
}
// This object wraps the InvokeCallback so that if it gets GC'd by V8, we can
// still call the callback and send an error. Not doing so causes a Mojo DCHECK,
// since Mojo requires callbacks to be called before they are destroyed.
class ReplyChannel : public gin::Wrappable<ReplyChannel> {
public:
using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback;
static gin::Handle<ReplyChannel> Create(v8::Isolate* isolate,
InvokeCallback callback) {
return gin::CreateHandle(isolate, new ReplyChannel(std::move(callback)));
}
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override {
return gin::Wrappable<ReplyChannel>::GetObjectTemplateBuilder(isolate)
.SetMethod("sendReply", &ReplyChannel::SendReply);
}
const char* GetTypeName() override { return "ReplyChannel"; }
void SendError(const std::string& msg) {
v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
// If there's no current context, it means we're shutting down, so we
// don't need to send an event.
if (!isolate->GetCurrentContext().IsEmpty()) {
v8::HandleScope scope(isolate);
auto message = gin::DataObjectBuilder(isolate).Set("error", msg).Build();
SendReply(isolate, message);
}
}
private:
explicit ReplyChannel(InvokeCallback callback)
: callback_(std::move(callback)) {}
~ReplyChannel() override {
if (callback_)
SendError("reply was never sent");
}
bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> arg) {
if (!callback_)
return false;
blink::CloneableMessage message;
if (!gin::ConvertFromV8(isolate, arg, &message)) {
return false;
}
std::move(callback_).Run(std::move(message));
return true;
}
InvokeCallback callback_;
};
gin::WrapperInfo ReplyChannel::kWrapperInfo = {gin::kEmbedderNativeGin};
gin::Handle<gin_helper::internal::Event> WebContents::MakeEventWithSender(
v8::Isolate* isolate,
content::RenderFrameHost* frame,
electron::mojom::ElectronApiIPC::InvokeCallback callback) {
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper)) {
if (callback) {
// We must always invoke the callback if present.
ReplyChannel::Create(isolate, std::move(callback))
->SendError("WebContents was destroyed");
}
return gin::Handle<gin_helper::internal::Event>();
}
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
gin_helper::Dictionary dict(isolate, event.ToV8().As<v8::Object>());
if (callback)
dict.Set("_replyChannel",
ReplyChannel::Create(isolate, std::move(callback)));
if (frame) {
dict.Set("frameId", frame->GetRoutingID());
dict.Set("processId", frame->GetProcess()->GetID());
}
return event;
}
void WebContents::ReceivePostMessage(
const std::string& channel,
blink::TransferableMessage message,
content::RenderFrameHost* render_frame_host) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto wrapped_ports =
MessagePort::EntanglePorts(isolate, std::move(message.ports));
v8::Local<v8::Value> message_value =
electron::DeserializeV8Value(isolate, message);
EmitWithSender("-ipc-ports", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), false,
channel, message_value, std::move(wrapped_ports));
}
void WebContents::MessageSync(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::MessageSyncCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel);
// webContents.emit('-ipc-message-sync', new Event(sender, message), internal,
// channel, arguments);
EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::MessageHost(const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel);
// webContents.emit('ipc-message-host', new Event(), channel, args);
EmitWithSender("ipc-message-host", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), channel,
std::move(arguments));
}
void WebContents::UpdateDraggableRegions(
std::vector<mojom::DraggableRegionPtr> regions) {
if (owner_window() && owner_window()->has_frame())
return;
draggable_region_ = DraggableRegionsToSkRegion(regions);
}
void WebContents::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-start-navigation", navigation_handle);
}
void WebContents::DidRedirectNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-redirect-navigation", navigation_handle);
}
void WebContents::ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) {
// Don't focus content in an inactive window.
if (!owner_window())
return;
#if BUILDFLAG(IS_MAC)
if (!owner_window()->IsActive())
return;
#else
if (!owner_window()->widget()->IsActive())
return;
#endif
// Don't focus content after subframe navigations.
if (!navigation_handle->IsInMainFrame())
return;
// Only focus for top-level contents.
if (type_ != Type::kBrowserWindow)
return;
web_contents()->SetInitialFocus();
}
void WebContents::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (owner_window_) {
owner_window_->NotifyLayoutWindowControlsOverlay();
}
if (!navigation_handle->HasCommitted())
return;
bool is_main_frame = navigation_handle->IsInMainFrame();
content::RenderFrameHost* frame_host =
navigation_handle->GetRenderFrameHost();
int frame_process_id = -1, frame_routing_id = -1;
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
if (!navigation_handle->IsErrorPage()) {
// FIXME: All the Emit() calls below could potentially result in |this|
// being destroyed (by JS listening for the event and calling
// webContents.destroy()).
auto url = navigation_handle->GetURL();
bool is_same_document = navigation_handle->IsSameDocument();
if (is_same_document) {
Emit("did-navigate-in-page", url, is_main_frame, frame_process_id,
frame_routing_id);
} else {
const net::HttpResponseHeaders* http_response =
navigation_handle->GetResponseHeaders();
std::string http_status_text;
int http_response_code = -1;
if (http_response) {
http_status_text = http_response->GetStatusText();
http_response_code = http_response->response_code();
}
Emit("did-frame-navigate", url, http_response_code, http_status_text,
is_main_frame, frame_process_id, frame_routing_id);
if (is_main_frame) {
Emit("did-navigate", url, http_response_code, http_status_text);
}
}
if (IsGuest())
Emit("load-commit", url, is_main_frame);
} else {
auto url = navigation_handle->GetURL();
int code = navigation_handle->GetNetErrorCode();
auto description = net::ErrorToShortString(code);
Emit("did-fail-provisional-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
// Do not emit "did-fail-load" for canceled requests.
if (code != net::ERR_ABORTED) {
EmitWarning(
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()),
"Failed to load URL: " + url.possibly_invalid_spec() +
" with error: " + description,
"electron");
Emit("did-fail-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
}
}
content::NavigationEntry* entry = navigation_handle->GetNavigationEntry();
// This check is needed due to an issue in Chromium
// Check the Chromium issue to keep updated:
// https://bugs.chromium.org/p/chromium/issues/detail?id=1178663
// If a history entry has been made and the forward/back call has been made,
// proceed with setting the new title
if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK))
WebContents::TitleWasSet(entry);
}
void WebContents::TitleWasSet(content::NavigationEntry* entry) {
std::u16string final_title;
bool explicit_set = true;
if (entry) {
auto title = entry->GetTitle();
auto url = entry->GetURL();
if (url.SchemeIsFile() && title.empty()) {
final_title = base::UTF8ToUTF16(url.ExtractFileName());
explicit_set = false;
} else {
final_title = title;
}
} else {
final_title = web_contents()->GetTitle();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnPageTitleUpdated(final_title, explicit_set);
Emit("page-title-updated", final_title, explicit_set);
}
void WebContents::DidUpdateFaviconURL(
content::RenderFrameHost* render_frame_host,
const std::vector<blink::mojom::FaviconURLPtr>& urls) {
std::set<GURL> unique_urls;
for (const auto& iter : urls) {
if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon)
continue;
const GURL& url = iter->icon_url;
if (url.is_valid())
unique_urls.insert(url);
}
Emit("page-favicon-updated", unique_urls);
}
void WebContents::DevToolsReloadPage() {
Emit("devtools-reload-page");
}
void WebContents::DevToolsFocused() {
Emit("devtools-focused");
}
void WebContents::DevToolsOpened() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
DCHECK(inspectable_web_contents_);
DCHECK(inspectable_web_contents_->GetDevToolsWebContents());
auto handle = FromOrCreate(
isolate, inspectable_web_contents_->GetDevToolsWebContents());
devtools_web_contents_.Reset(isolate, handle.ToV8());
// Set inspected tabID.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "setInspectedTabId", base::Value(ID()));
// Inherit owner window in devtools when it doesn't have one.
auto* devtools = inspectable_web_contents_->GetDevToolsWebContents();
bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey());
if (owner_window() && !has_window)
handle->SetOwnerWindow(devtools, owner_window());
Emit("devtools-opened");
}
void WebContents::DevToolsClosed() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
devtools_web_contents_.Reset();
Emit("devtools-closed");
}
void WebContents::DevToolsResized() {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnDevToolsResized();
}
void WebContents::SetOwnerWindow(NativeWindow* owner_window) {
SetOwnerWindow(GetWebContents(), owner_window);
}
void WebContents::SetOwnerWindow(content::WebContents* web_contents,
NativeWindow* owner_window) {
if (owner_window_) {
owner_window_->RemoveBackgroundThrottlingSource(this);
}
if (owner_window) {
owner_window_ = owner_window->GetWeakPtr();
NativeWindowRelay::CreateForWebContents(web_contents,
owner_window->GetWeakPtr());
owner_window_->AddBackgroundThrottlingSource(this);
} else {
owner_window_ = nullptr;
web_contents->RemoveUserData(NativeWindowRelay::UserDataKey());
}
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetNativeWindow(owner_window);
}
content::WebContents* WebContents::GetWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetWebContents();
}
content::WebContents* WebContents::GetDevToolsWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetDevToolsWebContents();
}
void WebContents::WebContentsDestroyed() {
// Clear the pointer stored in wrapper.
if (GetAllWebContents().Lookup(id_))
GetAllWebContents().Remove(id_);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
wrapper->SetAlignedPointerInInternalField(0, nullptr);
// Tell WebViewGuestDelegate that the WebContents has been destroyed.
if (guest_delegate_)
guest_delegate_->WillDestroy();
Observe(nullptr);
Emit("destroyed");
}
void WebContents::NavigationEntryCommitted(
const content::LoadCommittedDetails& details) {
Emit("navigation-entry-committed", details.entry->GetURL(),
details.is_same_document, details.did_replace_entry);
}
bool WebContents::GetBackgroundThrottling() const {
return background_throttling_;
}
void WebContents::SetBackgroundThrottling(bool allowed) {
background_throttling_ = allowed;
if (owner_window_) {
owner_window_->UpdateBackgroundThrottlingState();
}
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (!rfh)
return;
auto* rwhv = rfh->GetView();
if (!rwhv)
return;
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (!rwh_impl)
return;
rwh_impl->disable_hidden_ = !background_throttling_;
web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed);
if (rwh_impl->is_hidden()) {
rwh_impl->WasShown({});
}
}
int WebContents::GetProcessID() const {
return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
}
base::ProcessId WebContents::GetOSProcessID() const {
base::ProcessHandle process_handle = web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->GetProcess()
.Handle();
return base::GetProcId(process_handle);
}
WebContents::Type WebContents::GetType() const {
return type_;
}
bool WebContents::Equal(const WebContents* web_contents) const {
return ID() == web_contents->ID();
}
GURL WebContents::GetURL() const {
return web_contents()->GetLastCommittedURL();
}
void WebContents::LoadURL(const GURL& url,
const gin_helper::Dictionary& options) {
if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL),
net::ErrorToShortString(net::ERR_INVALID_URL),
url.possibly_invalid_spec(), true);
return;
}
content::NavigationController::LoadURLParams params(url);
if (!options.Get("httpReferrer", ¶ms.referrer)) {
GURL http_referrer;
if (options.Get("httpReferrer", &http_referrer))
params.referrer =
content::Referrer(http_referrer.GetAsReferrer(),
network::mojom::ReferrerPolicy::kDefault);
}
std::string user_agent;
if (options.Get("userAgent", &user_agent))
SetUserAgent(user_agent);
std::string extra_headers;
if (options.Get("extraHeaders", &extra_headers))
params.extra_headers = extra_headers;
scoped_refptr<network::ResourceRequestBody> body;
if (options.Get("postData", &body)) {
params.post_data = body;
params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
}
GURL base_url_for_data_url;
if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
params.base_url_for_data_url = base_url_for_data_url;
params.load_type = content::NavigationController::LOAD_TYPE_DATA;
}
bool reload_ignoring_cache = false;
if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) &&
reload_ignoring_cache) {
params.reload_type = content::ReloadType::BYPASSING_CACHE;
}
// Calling LoadURLWithParams() can trigger JS which destroys |this|.
auto weak_this = GetWeakPtr();
params.transition_type = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
// It's not safe to start a new navigation or otherwise discard the current
// one while the call that started it is still on the stack. See
// http://crbug.com/347742.
auto& ctrl_impl = static_cast<content::NavigationControllerImpl&>(
web_contents()->GetController());
if (ctrl_impl.in_navigate_to_pending_entry()) {
Emit("did-fail-load", static_cast<int>(net::ERR_FAILED),
net::ErrorToShortString(net::ERR_FAILED), url.possibly_invalid_spec(),
true);
return;
}
// Discard non-committed entries to ensure we don't re-use a pending entry.
web_contents()->GetController().DiscardNonCommittedEntries();
web_contents()->GetController().LoadURLWithParams(params);
// β οΈWARNING!β οΈ
// LoadURLWithParams() triggers JS events which can call destroy() on |this|.
// It's not safe to assume that |this| points to valid memory at this point.
if (!weak_this || !web_contents())
return;
// Required to make beforeunload handler work.
NotifyUserActivation();
}
// TODO(MarshallOfSound): Figure out what we need to do with post data here, I
// believe the default behavior when we pass "true" is to phone out to the
// delegate and then the controller expects this method to be called again with
// "false" if the user approves the reload. For now this would result in
// ".reload()" calls on POST data domains failing silently. Passing false would
// result in them succeeding, but reposting which although more correct could be
// considering a breaking change.
void WebContents::Reload() {
web_contents()->GetController().Reload(content::ReloadType::NORMAL,
/* check_for_repost */ true);
}
void WebContents::ReloadIgnoringCache() {
web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE,
/* check_for_repost */ true);
}
void WebContents::DownloadURL(const GURL& url, gin::Arguments* args) {
std::map<std::string, std::string> headers;
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
if (options.Has("headers") && !options.Get("headers", &headers)) {
args->ThrowTypeError("Invalid value for headers - must be an object");
return;
}
}
std::unique_ptr<download::DownloadUrlParameters> download_params(
content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
web_contents(), url, MISSING_TRAFFIC_ANNOTATION));
for (const auto& [name, value] : headers) {
download_params->add_request_header(name, value);
}
auto* download_manager =
web_contents()->GetBrowserContext()->GetDownloadManager();
download_manager->DownloadUrl(std::move(download_params));
}
std::u16string WebContents::GetTitle() const {
return web_contents()->GetTitle();
}
bool WebContents::IsLoading() const {
return web_contents()->IsLoading();
}
bool WebContents::IsLoadingMainFrame() const {
return web_contents()->ShouldShowLoadingUI();
}
bool WebContents::IsWaitingForResponse() const {
return web_contents()->IsWaitingForResponse();
}
void WebContents::Stop() {
web_contents()->Stop();
}
bool WebContents::CanGoBack() const {
return web_contents()->GetController().CanGoBack();
}
void WebContents::GoBack() {
if (CanGoBack())
web_contents()->GetController().GoBack();
}
bool WebContents::CanGoForward() const {
return web_contents()->GetController().CanGoForward();
}
void WebContents::GoForward() {
if (CanGoForward())
web_contents()->GetController().GoForward();
}
bool WebContents::CanGoToOffset(int offset) const {
return web_contents()->GetController().CanGoToOffset(offset);
}
void WebContents::GoToOffset(int offset) {
if (CanGoToOffset(offset))
web_contents()->GetController().GoToOffset(offset);
}
bool WebContents::CanGoToIndex(int index) const {
return index >= 0 && index < GetHistoryLength();
}
void WebContents::GoToIndex(int index) {
if (CanGoToIndex(index))
web_contents()->GetController().GoToIndex(index);
}
int WebContents::GetActiveIndex() const {
return web_contents()->GetController().GetCurrentEntryIndex();
}
void WebContents::ClearHistory() {
// In some rare cases (normally while there is no real history) we are in a
// state where we can't prune navigation entries
if (web_contents()->GetController().CanPruneAllButLastCommitted()) {
web_contents()->GetController().PruneAllButLastCommitted();
}
}
int WebContents::GetHistoryLength() const {
return web_contents()->GetController().GetEntryCount();
}
const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy;
}
void WebContents::SetWebRTCIPHandlingPolicy(
const std::string& webrtc_ip_handling_policy) {
if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
return;
web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
webrtc_ip_handling_policy;
web_contents()->SyncRendererPrefs();
}
v8::Local<v8::Value> WebContents::GetWebRTCUDPPortRange(
v8::Isolate* isolate) const {
auto* prefs = web_contents()->GetMutableRendererPrefs();
auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
dict.Set("min", static_cast<uint32_t>(prefs->webrtc_udp_min_port));
dict.Set("max", static_cast<uint32_t>(prefs->webrtc_udp_max_port));
return dict.GetHandle();
}
void WebContents::SetWebRTCUDPPortRange(gin::Arguments* args) {
uint32_t min = 0, max = 0;
gin_helper::Dictionary range;
if (!args->GetNext(&range) || !range.Get("min", &min) ||
!range.Get("max", &max)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'min' and 'max' are both required");
return;
}
if ((0 == min && 0 != max) || max > UINT16_MAX) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError(
"'min' and 'max' must be in the (0, 65535] range or [0, 0]");
return;
}
if (min > max) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'max' must be greater than or equal to 'min'");
return;
}
auto* prefs = web_contents()->GetMutableRendererPrefs();
if (prefs->webrtc_udp_min_port == static_cast<uint16_t>(min) &&
prefs->webrtc_udp_max_port == static_cast<uint16_t>(max)) {
return;
}
prefs->webrtc_udp_min_port = min;
prefs->webrtc_udp_max_port = max;
web_contents()->SyncRendererPrefs();
}
std::string WebContents::GetMediaSourceID(
content::WebContents* request_web_contents) {
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host)
return std::string();
content::DesktopMediaID media_id(
content::DesktopMediaID::TYPE_WEB_CONTENTS,
content::DesktopMediaID::kNullId,
content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(),
frame_host->GetRoutingID()));
auto* request_frame_host = request_web_contents->GetPrimaryMainFrame();
if (!request_frame_host)
return std::string();
std::string id =
content::DesktopStreamsRegistry::GetInstance()->RegisterStream(
request_frame_host->GetProcess()->GetID(),
request_frame_host->GetRoutingID(),
url::Origin::Create(request_frame_host->GetLastCommittedURL()
.DeprecatedGetOriginAsURL()),
media_id, content::kRegistryStreamTypeTab);
return id;
}
bool WebContents::IsCrashed() const {
return web_contents()->IsCrashed();
}
void WebContents::ForcefullyCrashRenderer() {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
if (!rwh)
return;
content::RenderProcessHost* rph = rwh->GetProcess();
if (rph) {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// A generic |CrashDumpHungChildProcess()| is not implemented for Linux.
// Instead we send an explicit IPC to crash on the renderer's IO thread.
rph->ForceCrash();
#else
// Try to generate a crash report for the hung process.
#if !IS_MAS_BUILD()
CrashDumpHungChildProcess(rph->GetProcess().Handle());
#endif
rph->Shutdown(content::RESULT_CODE_HUNG);
#endif
}
}
void WebContents::SetUserAgent(const std::string& user_agent) {
blink::UserAgentOverride ua_override;
ua_override.ua_string_override = user_agent;
if (!user_agent.empty())
ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata();
web_contents()->SetUserAgentOverride(ua_override, false);
}
std::string WebContents::GetUserAgent() {
return web_contents()->GetUserAgentOverride().ua_string_override;
}
v8::Local<v8::Promise> WebContents::SavePage(
const base::FilePath& full_file_path,
const content::SavePageType& save_type) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!full_file_path.IsAbsolute()) {
promise.RejectWithErrorMessage("Path must be absolute");
return handle;
}
auto* handler = new SavePageHandler(web_contents(), std::move(promise));
handler->Handle(full_file_path, save_type);
return handle;
}
void WebContents::OpenDevTools(gin::Arguments* args) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
std::string state;
if (type_ == Type::kWebView || type_ == Type::kBackgroundPage ||
!owner_window()) {
state = "detach";
}
bool activate = true;
std::string title;
if (args && args->Length() == 1) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("mode", &state);
options.Get("activate", &activate);
options.Get("title", &title);
}
}
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->SetDockState(state);
inspectable_web_contents_->SetDevToolsTitle(base::UTF8ToUTF16(title));
inspectable_web_contents_->ShowDevTools(activate);
}
void WebContents::CloseDevTools() {
if (type_ == Type::kRemote)
return;
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->CloseDevTools();
}
bool WebContents::IsDevToolsOpened() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->IsDevToolsViewShowing();
}
std::u16string WebContents::GetDevToolsTitle() {
if (type_ == Type::kRemote)
return std::u16string();
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->GetDevToolsTitle();
}
void WebContents::SetDevToolsTitle(const std::u16string& title) {
inspectable_web_contents_->SetDevToolsTitle(title);
}
bool WebContents::IsDevToolsFocused() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->GetView()->IsDevToolsViewFocused();
}
void WebContents::EnableDeviceEmulation(
const blink::DeviceEmulationParams& params) {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->EnableDeviceEmulation(params);
}
}
}
void WebContents::DisableDeviceEmulation() {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->DisableDeviceEmulation();
}
}
}
void WebContents::ToggleDevTools() {
if (IsDevToolsOpened())
CloseDevTools();
else
OpenDevTools(nullptr);
}
void WebContents::InspectElement(int x, int y) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
DCHECK(inspectable_web_contents_);
if (!inspectable_web_contents_->GetDevToolsWebContents())
OpenDevTools(nullptr);
inspectable_web_contents_->InspectElement(x, y);
}
void WebContents::InspectSharedWorkerById(const std::string& workerId) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
if (agent_host->GetId() == workerId) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
}
std::vector<scoped_refptr<content::DevToolsAgentHost>>
WebContents::GetAllSharedWorkers() {
std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers;
if (type_ == Type::kRemote)
return shared_workers;
if (!enable_devtools_)
return shared_workers;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
shared_workers.push_back(agent_host);
}
}
return shared_workers;
}
void WebContents::InspectSharedWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::InspectServiceWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeServiceWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::SetIgnoreMenuShortcuts(bool ignore) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
DCHECK(web_preferences);
web_preferences->SetIgnoreMenuShortcuts(ignore);
}
void WebContents::SetAudioMuted(bool muted) {
web_contents()->SetAudioMuted(muted);
}
bool WebContents::IsAudioMuted() {
return web_contents()->IsAudioMuted();
}
bool WebContents::IsCurrentlyAudible() {
return web_contents()->IsCurrentlyAudible();
}
#if BUILDFLAG(ENABLE_PRINTING)
void WebContents::OnGetDeviceNameToUse(
base::Value::Dict print_settings,
printing::CompletionCallback print_callback,
bool silent,
// <error, device_name>
std::pair<std::string, std::u16string> info) {
// The content::WebContents might be already deleted at this point, and the
// PrintViewManagerElectron class does not do null check.
if (!web_contents()) {
if (print_callback)
std::move(print_callback).Run(false, "failed");
return;
}
if (!info.first.empty()) {
if (print_callback)
std::move(print_callback).Run(false, info.first);
return;
}
// If the user has passed a deviceName use it, otherwise use default printer.
print_settings.Set(printing::kSettingDeviceName, info.second);
auto* print_view_manager =
PrintViewManagerElectron::FromWebContents(web_contents());
if (!print_view_manager)
return;
auto* focused_frame = web_contents()->GetFocusedFrame();
auto* rfh = focused_frame && focused_frame->HasSelection()
? focused_frame
: web_contents()->GetPrimaryMainFrame();
print_view_manager->PrintNow(rfh, silent, std::move(print_settings),
std::move(print_callback));
}
void WebContents::Print(gin::Arguments* args) {
auto options = gin_helper::Dictionary::CreateEmpty(args->isolate());
base::Value::Dict settings;
if (args->Length() >= 1 && !args->GetNext(&options)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid print settings specified.");
return;
}
printing::CompletionCallback callback;
if (args->Length() == 2 && !args->GetNext(&callback)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid optional callback provided.");
return;
}
// Set optional silent printing
bool silent = false;
options.Get("silent", &silent);
bool print_background = false;
options.Get("printBackground", &print_background);
settings.Set(printing::kSettingShouldPrintBackgrounds, print_background);
// Set custom margin settings
auto margins = gin_helper::Dictionary::CreateEmpty(args->isolate());
if (options.Get("margins", &margins)) {
printing::mojom::MarginType margin_type =
printing::mojom::MarginType::kDefaultMargins;
margins.Get("marginType", &margin_type);
settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type));
if (margin_type == printing::mojom::MarginType::kCustomMargins) {
base::Value::Dict custom_margins;
int top = 0;
margins.Get("top", &top);
custom_margins.Set(printing::kSettingMarginTop, top);
int bottom = 0;
margins.Get("bottom", &bottom);
custom_margins.Set(printing::kSettingMarginBottom, bottom);
int left = 0;
margins.Get("left", &left);
custom_margins.Set(printing::kSettingMarginLeft, left);
int right = 0;
margins.Get("right", &right);
custom_margins.Set(printing::kSettingMarginRight, right);
settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins));
}
} else {
settings.Set(
printing::kSettingMarginsType,
static_cast<int>(printing::mojom::MarginType::kDefaultMargins));
}
// Set whether to print color or greyscale
bool print_color = true;
options.Get("color", &print_color);
auto const color_model = print_color ? printing::mojom::ColorModel::kColor
: printing::mojom::ColorModel::kGray;
settings.Set(printing::kSettingColor, static_cast<int>(color_model));
// Is the orientation landscape or portrait.
bool landscape = false;
options.Get("landscape", &landscape);
settings.Set(printing::kSettingLandscape, landscape);
// We set the default to the system's default printer and only update
// if at the Chromium level if the user overrides.
// Printer device name as opened by the OS.
std::u16string device_name;
options.Get("deviceName", &device_name);
int scale_factor = 100;
options.Get("scaleFactor", &scale_factor);
settings.Set(printing::kSettingScaleFactor, scale_factor);
int pages_per_sheet = 1;
options.Get("pagesPerSheet", &pages_per_sheet);
settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet);
// True if the user wants to print with collate.
bool collate = true;
options.Get("collate", &collate);
settings.Set(printing::kSettingCollate, collate);
// The number of individual copies to print
int copies = 1;
options.Get("copies", &copies);
settings.Set(printing::kSettingCopies, copies);
// Strings to be printed as headers and footers if requested by the user.
std::string header;
options.Get("header", &header);
std::string footer;
options.Get("footer", &footer);
if (!(header.empty() && footer.empty())) {
settings.Set(printing::kSettingHeaderFooterEnabled, true);
settings.Set(printing::kSettingHeaderFooterTitle, header);
settings.Set(printing::kSettingHeaderFooterURL, footer);
} else {
settings.Set(printing::kSettingHeaderFooterEnabled, false);
}
// We don't want to allow the user to enable these settings
// but we need to set them or a CHECK is hit.
settings.Set(printing::kSettingPrinterType,
static_cast<int>(printing::mojom::PrinterType::kLocal));
settings.Set(printing::kSettingShouldPrintSelectionOnly, false);
settings.Set(printing::kSettingRasterizePdf, false);
// Set custom page ranges to print
std::vector<gin_helper::Dictionary> page_ranges;
if (options.Get("pageRanges", &page_ranges)) {
base::Value::List page_range_list;
for (auto& range : page_ranges) {
int from, to;
if (range.Get("from", &from) && range.Get("to", &to)) {
base::Value::Dict range_dict;
// Chromium uses 1-based page ranges, so increment each by 1.
range_dict.Set(printing::kSettingPageRangeFrom, from + 1);
range_dict.Set(printing::kSettingPageRangeTo, to + 1);
page_range_list.Append(std::move(range_dict));
} else {
continue;
}
}
if (!page_range_list.empty())
settings.Set(printing::kSettingPageRange, std::move(page_range_list));
}
// Duplex type user wants to use.
printing::mojom::DuplexMode duplex_mode =
printing::mojom::DuplexMode::kSimplex;
options.Get("duplexMode", &duplex_mode);
settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode));
// We've already done necessary parameter sanitization at the
// JS level, so we can simply pass this through.
base::Value media_size(base::Value::Type::DICT);
if (options.Get("mediaSize", &media_size))
settings.Set(printing::kSettingMediaSize, std::move(media_size));
// Set custom dots per inch (dpi)
gin_helper::Dictionary dpi_settings;
int dpi = 72;
if (options.Get("dpi", &dpi_settings)) {
int horizontal = 72;
dpi_settings.Get("horizontal", &horizontal);
settings.Set(printing::kSettingDpiHorizontal, horizontal);
int vertical = 72;
dpi_settings.Get("vertical", &vertical);
settings.Set(printing::kSettingDpiVertical, vertical);
} else {
settings.Set(printing::kSettingDpiHorizontal, dpi);
settings.Set(printing::kSettingDpiVertical, dpi);
}
print_task_runner_->PostTaskAndReplyWithResult(
FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name),
base::BindOnce(&WebContents::OnGetDeviceNameToUse,
weak_factory_.GetWeakPtr(), std::move(settings),
std::move(callback), silent));
}
// Partially duplicated and modified from
// headless/lib/browser/protocol/page_handler.cc;l=41
v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
// This allows us to track headless printing calls.
auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID);
auto landscape = settings.GetDict().FindBool("landscape");
auto display_header_footer =
settings.GetDict().FindBool("displayHeaderFooter");
auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds");
auto scale = settings.GetDict().FindDouble("scale");
auto paper_width = settings.GetDict().FindDouble("paperWidth");
auto paper_height = settings.GetDict().FindDouble("paperHeight");
auto margin_top = settings.GetDict().FindDouble("marginTop");
auto margin_bottom = settings.GetDict().FindDouble("marginBottom");
auto margin_left = settings.GetDict().FindDouble("marginLeft");
auto margin_right = settings.GetDict().FindDouble("marginRight");
auto page_ranges = *settings.GetDict().FindString("pageRanges");
auto header_template = *settings.GetDict().FindString("headerTemplate");
auto footer_template = *settings.GetDict().FindString("footerTemplate");
auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize");
auto generate_tagged_pdf =
settings.GetDict().FindBool("shouldGenerateTaggedPDF");
absl::variant<printing::mojom::PrintPagesParamsPtr, std::string>
print_pages_params = print_to_pdf::GetPrintPagesParams(
web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(),
landscape, display_header_footer, print_background, scale,
paper_width, paper_height, margin_top, margin_bottom, margin_left,
margin_right, absl::make_optional(header_template),
absl::make_optional(footer_template), prefer_css_page_size,
generate_tagged_pdf);
if (absl::holds_alternative<std::string>(print_pages_params)) {
auto error = absl::get<std::string>(print_pages_params);
promise.RejectWithErrorMessage("Invalid print parameters: " + error);
return handle;
}
auto* manager = PrintViewManagerElectron::FromWebContents(web_contents());
if (!manager) {
promise.RejectWithErrorMessage("Failed to find print manager");
return handle;
}
auto params = std::move(
absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params));
params->params->document_cookie = unique_id.value_or(0);
manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges,
std::move(params),
base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(),
std::move(promise)));
return handle;
}
void WebContents::OnPDFCreated(
gin_helper::Promise<v8::Local<v8::Value>> promise,
print_to_pdf::PdfPrintResult print_result,
scoped_refptr<base::RefCountedMemory> data) {
if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) {
promise.RejectWithErrorMessage(
"Failed to generate PDF: " +
print_to_pdf::PdfPrintResultToString(print_result));
return;
}
v8::Isolate* isolate = promise.isolate();
gin_helper::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate, promise.GetContext()));
v8::Local<v8::Value> buffer =
node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()),
data->size())
.ToLocalChecked();
promise.Resolve(buffer);
}
#endif
void WebContents::AddWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsAddFileSystem(std::string(), path);
}
void WebContents::RemoveWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsRemoveFileSystem(path);
}
void WebContents::Undo() {
web_contents()->Undo();
}
void WebContents::Redo() {
web_contents()->Redo();
}
void WebContents::Cut() {
web_contents()->Cut();
}
void WebContents::Copy() {
web_contents()->Copy();
}
void WebContents::CenterSelection() {
web_contents()->CenterSelection();
}
void WebContents::Paste() {
web_contents()->Paste();
}
void WebContents::PasteAndMatchStyle() {
web_contents()->PasteAndMatchStyle();
}
void WebContents::Delete() {
web_contents()->Delete();
}
void WebContents::SelectAll() {
web_contents()->SelectAll();
}
void WebContents::Unselect() {
web_contents()->CollapseSelection();
}
void WebContents::ScrollToTopOfDocument() {
web_contents()->ScrollToTopOfDocument();
}
void WebContents::ScrollToBottomOfDocument() {
web_contents()->ScrollToBottomOfDocument();
}
void WebContents::AdjustSelectionByCharacterOffset(gin::Arguments* args) {
int start_adjust = 0;
int end_adjust = 0;
gin_helper::Dictionary dict;
if (args->GetNext(&dict)) {
dict.Get("start", &start_adjust);
dict.Get("matchCase", &end_adjust);
}
// The selection menu is a Chrome-specific piece of UI.
// TODO(codebytere): maybe surface as an event in the future?
web_contents()->AdjustSelectionByCharacterOffset(
start_adjust, end_adjust, false /* show_selection_menu */);
}
void WebContents::Replace(const std::u16string& word) {
web_contents()->Replace(word);
}
void WebContents::ReplaceMisspelling(const std::u16string& word) {
web_contents()->ReplaceMisspelling(word);
}
uint32_t WebContents::FindInPage(gin::Arguments* args) {
std::u16string search_text;
if (!args->GetNext(&search_text) || search_text.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must provide a non-empty search content");
return 0;
}
uint32_t request_id = ++find_in_page_request_id_;
gin_helper::Dictionary dict;
auto options = blink::mojom::FindOptions::New();
if (args->GetNext(&dict)) {
dict.Get("forward", &options->forward);
dict.Get("matchCase", &options->match_case);
dict.Get("findNext", &options->new_session);
}
web_contents()->Find(request_id, search_text, std::move(options));
return request_id;
}
void WebContents::StopFindInPage(content::StopFindAction action) {
web_contents()->StopFinding(action);
}
void WebContents::ShowDefinitionForSelection() {
#if BUILDFLAG(IS_MAC)
auto* const view = web_contents()->GetRenderWidgetHostView();
if (view)
view->ShowDefinitionForSelection();
#endif
}
void WebContents::CopyImageAt(int x, int y) {
auto* const host = web_contents()->GetPrimaryMainFrame();
if (host)
host->CopyImageAt(x, y);
}
void WebContents::Focus() {
// Focusing on WebContents does not automatically focus the window on macOS
// and Linux, do it manually to match the behavior on Windows.
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
if (owner_window())
owner_window()->Focus(true);
#endif
web_contents()->Focus();
}
#if !BUILDFLAG(IS_MAC)
bool WebContents::IsFocused() const {
auto* view = web_contents()->GetRenderWidgetHostView();
if (!view)
return false;
if (GetType() != Type::kBackgroundPage) {
auto* window = web_contents()->GetNativeView()->GetToplevelWindow();
if (window && !window->IsVisible())
return false;
}
return view->HasFocus();
}
#endif
void WebContents::SendInputEvent(v8::Isolate* isolate,
v8::Local<v8::Value> input_event) {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
blink::WebInputEvent::Type type =
gin::GetWebInputEventType(isolate, input_event);
if (blink::WebInputEvent::IsMouseEventType(type)) {
blink::WebMouseEvent mouse_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) {
if (IsOffScreen()) {
GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event);
} else {
rwh->ForwardMouseEvent(mouse_event);
}
return;
}
} else if (blink::WebInputEvent::IsKeyboardEventType(type)) {
content::NativeWebKeyboardEvent keyboard_event(
blink::WebKeyboardEvent::Type::kRawKeyDown,
blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow());
if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) {
// For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`.
if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown)
keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown);
rwh->ForwardKeyboardEvent(keyboard_event);
return;
}
} else if (type == blink::WebInputEvent::Type::kMouseWheel) {
blink::WebMouseWheelEvent mouse_wheel_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
if (IsOffScreen()) {
GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent(
mouse_wheel_event);
} else {
// Chromium expects phase info in wheel events (and applies a
// DCHECK to verify it). See: https://crbug.com/756524.
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
// Send a synthetic wheel event with phaseEnded to finish scrolling.
mouse_wheel_event.has_synthetic_phase = true;
mouse_wheel_event.delta_x = 0;
mouse_wheel_event.delta_y = 0;
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kEventNonBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
}
return;
}
}
isolate->ThrowException(
v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object")));
}
void WebContents::BeginFrameSubscription(gin::Arguments* args) {
bool only_dirty = false;
FrameSubscriber::FrameCaptureCallback callback;
if (args->Length() > 1) {
if (!args->GetNext(&only_dirty)) {
args->ThrowError();
return;
}
}
if (!args->GetNext(&callback)) {
args->ThrowError();
return;
}
frame_subscriber_ =
std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty);
}
void WebContents::EndFrameSubscription() {
frame_subscriber_.reset();
}
void WebContents::StartDrag(const gin_helper::Dictionary& item,
gin::Arguments* args) {
base::FilePath file;
std::vector<base::FilePath> files;
if (!item.Get("files", &files) && item.Get("file", &file)) {
files.push_back(file);
}
v8::Local<v8::Value> icon_value;
if (!item.Get("icon", &icon_value)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'icon' parameter is required");
return;
}
NativeImage* icon = nullptr;
if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) ||
icon->image().IsEmpty()) {
return;
}
// Start dragging.
if (!files.empty()) {
base::CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop allow;
DragFileItems(files, icon->image(), web_contents()->GetNativeView());
} else {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must specify either 'file' or 'files' option");
}
}
v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) {
gin_helper::Promise<gfx::Image> promise(args->isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
gfx::Rect rect;
args->GetNext(&rect);
bool stay_hidden = false;
bool stay_awake = false;
if (args && args->Length() == 2) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("stayHidden", &stay_hidden);
options.Get("stayAwake", &stay_awake);
}
}
auto* const view = web_contents()->GetRenderWidgetHostView();
if (!view) {
promise.Resolve(gfx::Image());
return handle;
}
#if !BUILDFLAG(IS_MAC)
// If the view's renderer is suspended this may fail on Windows/Linux -
// bail if so. See CopyFromSurface in
// content/public/browser/render_widget_host_view.h.
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (rfh &&
rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) {
promise.Resolve(gfx::Image());
return handle;
}
#endif // BUILDFLAG(IS_MAC)
auto capture_handle = web_contents()->IncrementCapturerCount(
rect.size(), stay_hidden, stay_awake);
// Capture full page if user doesn't specify a |rect|.
const gfx::Size view_size =
rect.IsEmpty() ? view->GetViewBounds().size() : rect.size();
// By default, the requested bitmap size is the view size in screen
// coordinates. However, if there's more pixel detail available on the
// current system, increase the requested bitmap size to capture it all.
gfx::Size bitmap_size = view_size;
const gfx::NativeView native_view = view->GetNativeView();
const float scale = display::Screen::GetScreen()
->GetDisplayNearestView(native_view)
.device_scale_factor();
if (scale > 1.0f)
bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size,
base::BindOnce(&OnCapturePageDone, std::move(promise),
std::move(capture_handle)));
return handle;
}
bool WebContents::IsBeingCaptured() {
return web_contents()->IsBeingCaptured();
}
void WebContents::OnCursorChanged(const ui::Cursor& cursor) {
if (cursor.type() == ui::mojom::CursorType::kCustom) {
Emit("cursor-changed", CursorTypeToString(cursor.type()),
gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()),
cursor.image_scale_factor(),
gfx::Size(cursor.custom_bitmap().width(),
cursor.custom_bitmap().height()),
cursor.custom_hotspot());
} else {
Emit("cursor-changed", CursorTypeToString(cursor.type()));
}
}
bool WebContents::IsGuest() const {
return type_ == Type::kWebView;
}
void WebContents::AttachToIframe(content::WebContents* embedder_web_contents,
int embedder_frame_id) {
attached_ = true;
if (guest_delegate_)
guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id);
}
bool WebContents::IsOffScreen() const {
return type_ == Type::kOffScreen;
}
void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap));
}
void WebContents::StartPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(true);
}
void WebContents::StopPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(false);
}
bool WebContents::IsPainting() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv && osr_wcv->IsPainting();
}
void WebContents::SetFrameRate(int frame_rate) {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetFrameRate(frame_rate);
}
int WebContents::GetFrameRate() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv ? osr_wcv->GetFrameRate() : 0;
}
void WebContents::Invalidate() {
if (IsOffScreen()) {
auto* osr_rwhv = GetOffScreenRenderWidgetHostView();
if (osr_rwhv)
osr_rwhv->Invalidate();
} else {
auto* const window = owner_window();
if (window)
window->Invalidate();
}
}
gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) {
if (IsOffScreen() && wc == web_contents()) {
auto* relay = NativeWindowRelay::FromWebContents(web_contents());
if (relay) {
auto* owner_window = relay->GetNativeWindow();
return owner_window ? owner_window->GetSize() : gfx::Size();
}
}
return gfx::Size();
}
void WebContents::SetZoomLevel(double level) {
zoom_controller_->SetZoomLevel(level);
}
double WebContents::GetZoomLevel() const {
return zoom_controller_->GetZoomLevel();
}
void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower,
double factor) {
if (factor < std::numeric_limits<double>::epsilon()) {
thrower.ThrowError("'zoomFactor' must be a double greater than 0.0");
return;
}
auto level = blink::PageZoomFactorToZoomLevel(factor);
SetZoomLevel(level);
}
double WebContents::GetZoomFactor() const {
auto level = GetZoomLevel();
return blink::PageZoomLevelToZoomFactor(level);
}
void WebContents::SetTemporaryZoomLevel(double level) {
zoom_controller_->SetTemporaryZoomLevel(level);
}
void WebContents::DoGetZoomLevel(
electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback
callback) {
std::move(callback).Run(GetZoomLevel());
}
std::vector<base::FilePath> WebContents::GetPreloadPaths() const {
auto result = SessionPreferences::GetValidPreloads(GetBrowserContext());
if (auto* web_preferences = WebContentsPreferences::From(web_contents())) {
base::FilePath preload;
if (web_preferences->GetPreloadPath(&preload)) {
result.emplace_back(preload);
}
}
return result;
}
v8::Local<v8::Value> WebContents::GetLastWebPreferences(
v8::Isolate* isolate) const {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (!web_preferences)
return v8::Null(isolate);
return gin::ConvertToV8(isolate, *web_preferences->last_preference());
}
v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow(
v8::Isolate* isolate) const {
if (owner_window())
return BrowserWindow::From(isolate, owner_window());
else
return v8::Null(isolate);
}
v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
return v8::Local<v8::Value>::New(isolate, session_);
}
content::WebContents* WebContents::HostWebContents() const {
if (!embedder_)
return nullptr;
return embedder_->web_contents();
}
void WebContents::SetEmbedder(const WebContents* embedder) {
if (embedder) {
NativeWindow* owner_window = nullptr;
auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
if (relay) {
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
content::RenderWidgetHostView* rwhv =
web_contents()->GetRenderWidgetHostView();
if (rwhv) {
rwhv->Hide();
rwhv->Show();
}
}
}
void WebContents::SetDevToolsWebContents(const WebContents* devtools) {
if (inspectable_web_contents_)
inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents());
}
v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const {
gfx::NativeView ptr = web_contents()->GetNativeView();
auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr),
sizeof(gfx::NativeView));
if (buffer.IsEmpty())
return v8::Null(isolate);
else
return buffer.ToLocalChecked();
}
v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
if (devtools_web_contents_.IsEmpty())
return v8::Null(isolate);
else
return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
}
v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
if (debugger_.IsEmpty()) {
auto handle = electron::api::Debugger::Create(isolate, web_contents());
debugger_.Reset(isolate, handle.ToV8());
}
return v8::Local<v8::Value>::New(isolate, debugger_);
}
content::RenderFrameHost* WebContents::MainFrame() {
return web_contents()->GetPrimaryMainFrame();
}
content::RenderFrameHost* WebContents::Opener() {
return web_contents()->GetOpener();
}
void WebContents::NotifyUserActivation() {
content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame();
if (frame)
frame->NotifyUserActivation(
blink::mojom::UserActivationNotificationType::kInteraction);
}
void WebContents::SetImageAnimationPolicy(const std::string& new_policy) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
web_preferences->SetImageAnimationPolicy(new_policy);
web_contents()->OnWebPreferencesChanged();
}
void WebContents::OnInputEvent(const blink::WebInputEvent& event) {
Emit("input-event", event);
}
v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage("Failed to create memory dump");
return handle;
}
auto pid = frame_host->GetProcess()->GetProcess().Pid();
v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext());
memory_instrumentation::MemoryInstrumentation::GetInstance()
->RequestGlobalDumpForPid(
pid, std::vector<std::string>(),
base::BindOnce(&ElectronBindings::DidReceiveMemoryDump,
std::move(context), std::move(promise), pid));
return handle;
}
v8::Local<v8::Promise> WebContents::TakeHeapSnapshot(
v8::Isolate* isolate,
const base::FilePath& file_path) {
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
ScopedAllowBlockingForElectron allow_blocking;
uint32_t flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE;
// The snapshot file is passed to an untrusted process.
flags = base::File::AddFlagsForPassingToUntrustedProcess(flags);
base::File file(file_path, flags);
if (!file.IsValid()) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with invalid file path " +
#if BUILDFLAG(IS_WIN)
base::WideToUTF8(file_path.value()));
#else
file_path.value());
#endif
return handle;
}
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with invalid webContents main frame");
return handle;
}
if (!frame_host->IsRenderFrameLive()) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with nonexistent render frame");
return handle;
}
// This dance with `base::Owned` is to ensure that the interface stays alive
// until the callback is called. Otherwise it would be closed at the end of
// this function.
auto electron_renderer =
std::make_unique<mojo::Remote<mojom::ElectronRenderer>>();
frame_host->GetRemoteInterfaces()->GetInterface(
electron_renderer->BindNewPipeAndPassReceiver());
auto* raw_ptr = electron_renderer.get();
(*raw_ptr)->TakeHeapSnapshot(
mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())),
base::BindOnce(
[](mojo::Remote<mojom::ElectronRenderer>* ep,
gin_helper::Promise<void> promise, bool success) {
if (success) {
promise.Resolve();
} else {
promise.RejectWithErrorMessage("Failed to take heap snapshot");
}
},
base::Owned(std::move(electron_renderer)), std::move(promise)));
return handle;
}
void WebContents::UpdatePreferredSize(content::WebContents* web_contents,
const gfx::Size& pref_size) {
Emit("preferred-size-changed", pref_size);
}
bool WebContents::CanOverscrollContent() {
return false;
}
std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper(
content::RenderFrameHost* frame,
content::EyeDropperListener* listener) {
return ShowEyeDropper(frame, listener);
}
void WebContents::RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) {
FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener),
params);
}
void WebContents::EnumerateDirectory(
content::WebContents* web_contents,
scoped_refptr<content::FileSelectListener> listener,
const base::FilePath& path) {
FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path);
}
bool WebContents::IsFullscreenForTabOrPending(
const content::WebContents* source) {
if (!owner_window())
return is_html_fullscreen();
bool in_transition = owner_window()->fullscreen_transition_state() !=
NativeWindow::FullScreenTransitionState::kNone;
bool is_html_transition = owner_window()->fullscreen_transition_type() ==
NativeWindow::FullScreenTransitionType::kHTML;
return is_html_fullscreen() || (in_transition && is_html_transition);
}
content::FullscreenState WebContents::GetFullscreenState(
const content::WebContents* source) const {
// `const_cast` here because EAM does not have const getters
return const_cast<ExclusiveAccessManager*>(&exclusive_access_manager_)
->fullscreen_controller()
->GetFullscreenState(source);
}
bool WebContents::TakeFocus(content::WebContents* source, bool reverse) {
if (source && source->GetOutermostWebContents() == source) {
// If this is the outermost web contents and the user has tabbed or
// shift + tabbed through all the elements, reset the focus back to
// the first or last element so that it doesn't stay in the body.
source->FocusThroughTabTraversal(reverse);
return true;
}
return false;
}
content::PictureInPictureResult WebContents::EnterPictureInPicture(
content::WebContents* web_contents) {
return PictureInPictureWindowManager::GetInstance()
->EnterVideoPictureInPicture(web_contents);
}
void WebContents::ExitPictureInPicture() {
PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture();
}
void WebContents::DevToolsSaveToFile(const std::string& url,
const std::string& content,
bool save_as) {
base::FilePath path;
auto it = saved_files_.find(url);
if (it != saved_files_.end() && !save_as) {
path = it->second;
} else {
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.title = url;
settings.default_path = base::FilePath::FromUTF8Unsafe(url);
if (!file_dialog::ShowSaveDialogSync(settings, &path)) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "canceledSaveURL", base::Value(url));
return;
}
}
saved_files_[url] = path;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "savedURL", base::Value(url),
base::Value(path.AsUTF8Unsafe()));
file_task_runner_->PostTask(FROM_HERE,
base::BindOnce(&WriteToFile, path, content));
}
void WebContents::DevToolsAppendToFile(const std::string& url,
const std::string& content) {
auto it = saved_files_.find(url);
if (it == saved_files_.end())
return;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL",
base::Value(url));
file_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&AppendToFile, it->second, content));
}
void WebContents::DevToolsRequestFileSystems() {
auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents());
if (file_system_paths.empty()) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List()));
return;
}
std::vector<FileSystem> file_systems;
for (const auto& file_system_path : file_system_paths) {
base::FilePath path =
base::FilePath::FromUTF8Unsafe(file_system_path.first);
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
FileSystem file_system =
CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id,
file_system_path.first, file_system_path.second);
file_systems.push_back(file_system);
}
base::Value::List file_system_value;
for (const auto& file_system : file_systems)
file_system_value.Append(CreateFileSystemValue(file_system));
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded",
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsAddFileSystem(
const std::string& type,
const base::FilePath& file_system_path) {
base::FilePath path = file_system_path;
if (path.empty()) {
std::vector<base::FilePath> paths;
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY;
if (!file_dialog::ShowOpenDialogSync(settings, &paths))
return;
path = paths[0];
}
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe()))
return;
FileSystem file_system = CreateFileSystemStruct(
GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type);
base::Value::Dict file_system_value = CreateFileSystemValue(file_system);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Set(path.AsUTF8Unsafe(), type);
std::string error = ""; // No error
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemAdded", base::Value(error),
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsRemoveFileSystem(
const base::FilePath& file_system_path) {
if (!inspectable_web_contents_)
return;
std::string path = file_system_path.AsUTF8Unsafe();
storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath(
file_system_path);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Remove(path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemRemoved", base::Value(path));
}
void WebContents::DevToolsIndexPath(
int request_id,
const std::string& file_system_path,
const std::string& excluded_folders_message) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsIndexingDone(request_id, file_system_path);
return;
}
if (devtools_indexing_jobs_.count(request_id) != 0)
return;
std::vector<std::string> excluded_folders;
absl::optional<base::Value> parsed_excluded_folders =
base::JSONReader::Read(excluded_folders_message);
if (parsed_excluded_folders && parsed_excluded_folders->is_list()) {
for (const base::Value& folder_path : parsed_excluded_folders->GetList()) {
if (folder_path.is_string())
excluded_folders.push_back(folder_path.GetString());
}
}
devtools_indexing_jobs_[request_id] =
scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>(
devtools_file_system_indexer_->IndexPath(
file_system_path, excluded_folders,
base::BindRepeating(
&WebContents::OnDevToolsIndexingWorkCalculated,
weak_factory_.GetWeakPtr(), request_id, file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingWorked,
weak_factory_.GetWeakPtr(), request_id,
file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingDone,
weak_factory_.GetWeakPtr(), request_id,
file_system_path)));
}
void WebContents::DevToolsStopIndexing(int request_id) {
auto it = devtools_indexing_jobs_.find(request_id);
if (it == devtools_indexing_jobs_.end())
return;
it->second->Stop();
devtools_indexing_jobs_.erase(it);
}
void WebContents::DevToolsOpenInNewTab(const std::string& url) {
Emit("devtools-open-url", url);
}
void WebContents::DevToolsSearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsSearchCompleted(request_id, file_system_path,
std::vector<std::string>());
return;
}
devtools_file_system_indexer_->SearchInPath(
file_system_path, query,
base::BindRepeating(&WebContents::OnDevToolsSearchCompleted,
weak_factory_.GetWeakPtr(), request_id,
file_system_path));
}
void WebContents::DevToolsSetEyeDropperActive(bool active) {
auto* web_contents = GetWebContents();
if (!web_contents)
return;
if (active) {
eye_dropper_ = std::make_unique<DevToolsEyeDropper>(
web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper,
base::Unretained(this)));
} else {
eye_dropper_.reset();
}
}
void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) {
base::Value::Dict color;
color.Set("r", r);
color.Set("g", g);
color.Set("b", b);
color.Set("a", a);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color)));
}
#if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
ui::ImageModel WebContents::GetDevToolsWindowIcon() {
return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{};
}
#endif
#if BUILDFLAG(IS_LINUX)
void WebContents::GetDevToolsWindowWMClass(std::string* name,
std::string* class_name) {
*class_name = Browser::Get()->GetName();
*name = base::ToLowerASCII(*class_name);
}
#endif
void WebContents::OnDevToolsIndexingWorkCalculated(
int request_id,
const std::string& file_system_path,
int total_work) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id),
base::Value(file_system_path), base::Value(total_work));
}
void WebContents::OnDevToolsIndexingWorked(int request_id,
const std::string& file_system_path,
int worked) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingWorked", base::Value(request_id),
base::Value(file_system_path), base::Value(worked));
}
void WebContents::OnDevToolsIndexingDone(int request_id,
const std::string& file_system_path) {
devtools_indexing_jobs_.erase(request_id);
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone",
base::Value(request_id),
base::Value(file_system_path));
}
void WebContents::OnDevToolsSearchCompleted(
int request_id,
const std::string& file_system_path,
const std::vector<std::string>& file_paths) {
base::Value::List file_paths_value;
for (const auto& file_path : file_paths)
file_paths_value.Append(file_path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "searchCompleted", base::Value(request_id),
base::Value(file_system_path), base::Value(std::move(file_paths_value)));
}
void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) {
// Window is already in fullscreen mode, save the state.
if (enter_fullscreen && owner_window()->IsFullscreen()) {
native_fullscreen_ = true;
UpdateHtmlApiFullscreen(true);
return;
}
// Exit html fullscreen state but not window's fullscreen mode.
if (!enter_fullscreen && native_fullscreen_) {
UpdateHtmlApiFullscreen(false);
return;
}
// Set fullscreen on window if allowed.
auto* web_preferences = WebContentsPreferences::From(GetWebContents());
bool html_fullscreenable =
web_preferences
? !web_preferences->ShouldDisableHtmlFullscreenWindowResize()
: true;
if (html_fullscreenable)
owner_window_->SetFullScreen(enter_fullscreen);
UpdateHtmlApiFullscreen(enter_fullscreen);
native_fullscreen_ = false;
}
void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) {
if (fullscreen == is_html_fullscreen())
return;
html_fullscreen_ = fullscreen;
// Notify renderer of the html fullscreen change.
web_contents()
->GetRenderViewHost()
->GetWidget()
->SynchronizeVisualProperties();
// The embedder WebContents is separated from the frame tree of webview, so
// we must manually sync their fullscreen states.
if (embedder_)
embedder_->SetHtmlApiFullscreen(fullscreen);
if (fullscreen) {
Emit("enter-html-full-screen");
owner_window_->NotifyWindowEnterHtmlFullScreen();
} else {
Emit("leave-html-full-screen");
owner_window_->NotifyWindowLeaveHtmlFullScreen();
}
// Make sure all child webviews quit html fullscreen.
if (!fullscreen && !IsGuest()) {
auto* manager = WebViewManager::GetWebViewManager(web_contents());
manager->ForEachGuest(
web_contents(), base::BindRepeating([](content::WebContents* guest) {
WebContents* api_web_contents = WebContents::From(guest);
api_web_contents->SetHtmlApiFullscreen(false);
return false;
}));
}
}
// static
void WebContents::FillObjectTemplate(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin::InvokerOptions options;
options.holder_is_first_argument = true;
options.holder_type = GetClassName();
templ->Set(
gin::StringToSymbol(isolate, "isDestroyed"),
gin::CreateFunctionTemplate(
isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed),
options));
// We use gin_helper::ObjectTemplateBuilder instead of
// gin::ObjectTemplateBuilder here to handle the fact that WebContents is
// destroyable.
gin_helper::ObjectTemplateBuilder(isolate, templ)
.SetMethod("destroy", &WebContents::Destroy)
.SetMethod("close", &WebContents::Close)
.SetMethod("getBackgroundThrottling",
&WebContents::GetBackgroundThrottling)
.SetMethod("setBackgroundThrottling",
&WebContents::SetBackgroundThrottling)
.SetMethod("getProcessId", &WebContents::GetProcessID)
.SetMethod("getOSProcessId", &WebContents::GetOSProcessID)
.SetMethod("equal", &WebContents::Equal)
.SetMethod("_loadURL", &WebContents::LoadURL)
.SetMethod("reload", &WebContents::Reload)
.SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache)
.SetMethod("downloadURL", &WebContents::DownloadURL)
.SetMethod("getURL", &WebContents::GetURL)
.SetMethod("getTitle", &WebContents::GetTitle)
.SetMethod("isLoading", &WebContents::IsLoading)
.SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
.SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
.SetMethod("stop", &WebContents::Stop)
.SetMethod("canGoBack", &WebContents::CanGoBack)
.SetMethod("goBack", &WebContents::GoBack)
.SetMethod("canGoForward", &WebContents::CanGoForward)
.SetMethod("goForward", &WebContents::GoForward)
.SetMethod("canGoToOffset", &WebContents::CanGoToOffset)
.SetMethod("goToOffset", &WebContents::GoToOffset)
.SetMethod("canGoToIndex", &WebContents::CanGoToIndex)
.SetMethod("goToIndex", &WebContents::GoToIndex)
.SetMethod("getActiveIndex", &WebContents::GetActiveIndex)
.SetMethod("clearHistory", &WebContents::ClearHistory)
.SetMethod("length", &WebContents::GetHistoryLength)
.SetMethod("isCrashed", &WebContents::IsCrashed)
.SetMethod("forcefullyCrashRenderer",
&WebContents::ForcefullyCrashRenderer)
.SetMethod("setUserAgent", &WebContents::SetUserAgent)
.SetMethod("getUserAgent", &WebContents::GetUserAgent)
.SetMethod("savePage", &WebContents::SavePage)
.SetMethod("openDevTools", &WebContents::OpenDevTools)
.SetMethod("closeDevTools", &WebContents::CloseDevTools)
.SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
.SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
.SetMethod("getDevToolsTitle", &WebContents::GetDevToolsTitle)
.SetMethod("setDevToolsTitle", &WebContents::SetDevToolsTitle)
.SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation)
.SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation)
.SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
.SetMethod("inspectElement", &WebContents::InspectElement)
.SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts)
.SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
.SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
.SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible)
.SetMethod("undo", &WebContents::Undo)
.SetMethod("redo", &WebContents::Redo)
.SetMethod("cut", &WebContents::Cut)
.SetMethod("copy", &WebContents::Copy)
.SetMethod("centerSelection", &WebContents::CenterSelection)
.SetMethod("paste", &WebContents::Paste)
.SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
.SetMethod("delete", &WebContents::Delete)
.SetMethod("selectAll", &WebContents::SelectAll)
.SetMethod("unselect", &WebContents::Unselect)
.SetMethod("scrollToTop", &WebContents::ScrollToTopOfDocument)
.SetMethod("scrollToBottom", &WebContents::ScrollToBottomOfDocument)
.SetMethod("adjustSelection",
&WebContents::AdjustSelectionByCharacterOffset)
.SetMethod("replace", &WebContents::Replace)
.SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
.SetMethod("findInPage", &WebContents::FindInPage)
.SetMethod("stopFindInPage", &WebContents::StopFindInPage)
.SetMethod("focus", &WebContents::Focus)
.SetMethod("isFocused", &WebContents::IsFocused)
.SetMethod("sendInputEvent", &WebContents::SendInputEvent)
.SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription)
.SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
.SetMethod("startDrag", &WebContents::StartDrag)
.SetMethod("attachToIframe", &WebContents::AttachToIframe)
.SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame)
.SetMethod("isOffscreen", &WebContents::IsOffScreen)
.SetMethod("startPainting", &WebContents::StartPainting)
.SetMethod("stopPainting", &WebContents::StopPainting)
.SetMethod("isPainting", &WebContents::IsPainting)
.SetMethod("setFrameRate", &WebContents::SetFrameRate)
.SetMethod("getFrameRate", &WebContents::GetFrameRate)
.SetMethod("invalidate", &WebContents::Invalidate)
.SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
.SetMethod("getZoomLevel", &WebContents::GetZoomLevel)
.SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
.SetMethod("getZoomFactor", &WebContents::GetZoomFactor)
.SetMethod("getType", &WebContents::GetType)
.SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths)
.SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences)
.SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
.SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
.SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker)
.SetMethod("inspectSharedWorkerById",
&WebContents::InspectSharedWorkerById)
.SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers)
#if BUILDFLAG(ENABLE_PRINTING)
.SetMethod("_print", &WebContents::Print)
.SetMethod("_printToPDF", &WebContents::PrintToPDF)
#endif
.SetMethod("_setNextChildWebPreferences",
&WebContents::SetNextChildWebPreferences)
.SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
.SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
.SetMethod("showDefinitionForSelection",
&WebContents::ShowDefinitionForSelection)
.SetMethod("copyImageAt", &WebContents::CopyImageAt)
.SetMethod("capturePage", &WebContents::CapturePage)
.SetMethod("setEmbedder", &WebContents::SetEmbedder)
.SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents)
.SetMethod("getNativeView", &WebContents::GetNativeView)
.SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured)
.SetMethod("setWebRTCIPHandlingPolicy",
&WebContents::SetWebRTCIPHandlingPolicy)
.SetMethod("setWebRTCUDPPortRange", &WebContents::SetWebRTCUDPPortRange)
.SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID)
.SetMethod("getWebRTCIPHandlingPolicy",
&WebContents::GetWebRTCIPHandlingPolicy)
.SetMethod("getWebRTCUDPPortRange", &WebContents::GetWebRTCUDPPortRange)
.SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot)
.SetMethod("setImageAnimationPolicy",
&WebContents::SetImageAnimationPolicy)
.SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo)
.SetProperty("id", &WebContents::ID)
.SetProperty("session", &WebContents::Session)
.SetProperty("hostWebContents", &WebContents::HostWebContents)
.SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
.SetProperty("debugger", &WebContents::Debugger)
.SetProperty("mainFrame", &WebContents::MainFrame)
.SetProperty("opener", &WebContents::Opener)
.Build();
}
const char* WebContents::GetTypeName() {
return GetClassName();
}
ElectronBrowserContext* WebContents::GetBrowserContext() const {
return static_cast<ElectronBrowserContext*>(
web_contents()->GetBrowserContext());
}
// static
gin::Handle<WebContents> WebContents::New(
v8::Isolate* isolate,
const gin_helper::Dictionary& options) {
gin::Handle<WebContents> handle =
gin::CreateHandle(isolate, new WebContents(isolate, options));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
gin::Handle<WebContents> WebContents::CreateAndTake(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type) {
gin::Handle<WebContents> handle = gin::CreateHandle(
isolate, new WebContents(isolate, std::move(web_contents), type));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
WebContents* WebContents::From(content::WebContents* web_contents) {
if (!web_contents)
return nullptr;
auto* data = static_cast<UserDataLink*>(
web_contents->GetUserData(kElectronApiWebContentsKey));
return data ? data->web_contents.get() : nullptr;
}
// static
gin::Handle<WebContents> WebContents::FromOrCreate(
v8::Isolate* isolate,
content::WebContents* web_contents) {
WebContents* api_web_contents = From(web_contents);
if (!api_web_contents) {
api_web_contents = new WebContents(isolate, web_contents);
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, api_web_contents, "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
}
return gin::CreateHandle(isolate, api_web_contents);
}
// static
gin::Handle<WebContents> WebContents::CreateFromWebPreferences(
v8::Isolate* isolate,
const gin_helper::Dictionary& web_preferences) {
// Check if webPreferences has |webContents| option.
gin::Handle<WebContents> web_contents;
if (web_preferences.GetHidden("webContents", &web_contents) &&
!web_contents.IsEmpty()) {
// Set webPreferences from options if using an existing webContents.
// These preferences will be used when the webContent launches new
// render processes.
auto* existing_preferences =
WebContentsPreferences::From(web_contents->web_contents());
gin_helper::Dictionary web_preferences_dict;
if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(),
&web_preferences_dict)) {
existing_preferences->SetFromDictionary(web_preferences_dict);
absl::optional<SkColor> color =
existing_preferences->GetBackgroundColor();
web_contents->web_contents()->SetPageBaseBackgroundColor(color);
// Because web preferences don't recognize transparency,
// only set rwhv background color if a color exists
auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView();
if (rwhv && color.has_value())
SetBackgroundColor(rwhv, color.value());
}
} else {
// Create one if not.
web_contents = WebContents::New(isolate, web_preferences);
}
return web_contents;
}
// static
WebContents* WebContents::FromID(int32_t id) {
return GetAllWebContents().Lookup(id);
}
// static
std::list<WebContents*> WebContents::GetWebContentsList() {
std::list<WebContents*> list;
for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
!iter.IsAtEnd(); iter.Advance()) {
list.push_back(iter.GetCurrentValue());
}
return list;
}
// static
gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin};
} // namespace electron::api
namespace {
using electron::api::GetAllWebContents;
using electron::api::WebContents;
using electron::api::WebFrameMain;
gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) {
WebContents* contents = WebContents::FromID(id);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromFrame(v8::Isolate* isolate,
WebFrameMain* web_frame) {
content::RenderFrameHost* rfh = web_frame->render_frame_host();
content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh);
WebContents* contents = WebContents::From(source);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromDevToolsTargetID(
v8::Isolate* isolate,
std::string target_id) {
auto agent_host = content::DevToolsAgentHost::GetForId(target_id);
WebContents* contents =
agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr;
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8(
v8::Isolate* isolate) {
std::vector<gin::Handle<WebContents>> list;
for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
!iter.IsAtEnd(); iter.Advance()) {
list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue()));
}
return list;
}
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("WebContents", WebContents::GetConstructor(context));
dict.SetMethod("fromId", &WebContentsFromID);
dict.SetMethod("fromFrame", &WebContentsFromFrame);
dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID);
dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8);
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 31,992 |
[Bug]: webContents.capturePage() returns empty image for fully occluded BrowserWindow on 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 feature request that matches the one I want to file, without success.
### Electron Version
16.0.1
### What operating system are you using?
Windows
### Operating System Version
Windows 11 (10.0.22000.348)
### What arch are you using?
x64
### Last Known Working Electron version
10.4.7
### Expected Behavior
`webContents.capturePage()` should work for fully occluded BrowserWindow as the window is not minimized.
### Actual Behavior
`webContents.capturePage()` returns an empty `NativeImage` in this case.
### Testcase Gist URL
_No response_
### Additional Information
main.js for Fiddle
```js
const {app, BrowserWindow} = require('electron')
function createWindow () {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
})
setInterval(async () => {
const image = await mainWindow.capturePage();
console.log(image.getSize())
}, 1000);
mainWindow.loadFile('about:blank')
mainWindow.webContents.openDevTools({mode:'detach'})
}
app.whenReady().then(() => {
createWindow()
})
app.on('window-all-closed', function () {
app.quit()
})
```
to reproduce cover the BrowserWindow with the devtools, you'll see the image size being logged as `{ width: 0, height: 0 }`.
This is a regression from #27883, when I revert the change `webContents.capturePage()` is working correctly for occluded windows. Checking the visibility state does not seem correct to me as both occluded and minimized windows' webContents have visibilityState hidden.
The abandoned fix #27892 seems like a better option. Also according to the documentation of `CopyFromSurface`:
> // |callback| is guaranteed to be run, either synchronously or at some point
> // in the future (depending on the platform implementation and the current
> // state of the Surface). If the copy failed, the bitmap's drawsNothing()
> // method will return true.
> //
> // If the view's renderer is suspended (see WasOccluded()), this may result in
> // copying old data or failing.
> virtual void CopyFromSurface(
> const gfx::Rect& src_rect,
> const gfx::Size& output_size,
> base::OnceCallback<void(const SkBitmap&)> callback) = 0;
|
https://github.com/electron/electron/issues/31992
|
https://github.com/electron/electron/pull/39730
|
3e70692e4b3044a10e5b1e5148a97a3f62bec4cb
|
5c821d33791345446eef3a90a6bea9c920d001d8
| 2021-11-25T03:07:41Z |
c++
| 2023-10-12T07:35:23Z |
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));
for (const win of windows) win.show();
for (const win of windows) win.focus();
for (const win of windows) 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(async () => {
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('');
}
});
url = (await listen(server)).url;
});
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(async () => {
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('');
}
});
url = (await listen(server)).url;
});
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()', () => {
afterEach(closeAllWindows);
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);
});
it('should not crash when called on a modal child window', async () => {
const shown = once(w, 'show');
w.show();
await shown;
const child = new BrowserWindow({ modal: true, parent: w });
expect(() => { child.moveTop(); }).to.not.throw();
});
});
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'
];
for (const sourceId of fakeSourceIds) {
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];
for (const sourceId of fakeSourceIds) {
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'];
for (const sourceId of fakeSourceIds) {
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(closeAllWindows);
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('BrowserWindow.tabbingIdentifier', () => {
it('is undefined if no tabbingIdentifier was set', () => {
const w = new BrowserWindow({ show: false });
expect(w.tabbingIdentifier).to.be.undefined('tabbingIdentifier');
});
it('returns the window tabbingIdentifier', () => {
const w = new BrowserWindow({ show: false, tabbingIdentifier: 'group1' });
expect(w.tabbingIdentifier).to.equal('group1');
});
});
});
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._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);
});
});
});
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.replaceAll('\\', '/')
: 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.replaceAll('\\', '/')
: 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 });
const errorPattern = /Failed to read a named property 'document' from 'Window': Blocked a frame with origin "(.*?)" from accessing a cross-origin frame./;
expect(popupAccessMessage).to.be.a('string',
'child\'s .document is accessible from its parent window');
expect(popupAccessMessage).to.match(errorPattern);
expect(openerAccessMessage).to.be.a('string',
'opener .document is accessible from a popup window');
expect(openerAccessMessage).to.match(errorPattern);
});
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('Failed to read a named property \'toString\' from \'Location\': 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');
});
});
// TODO(codebytere): figure out how to make these pass in CI on Windows.
ifdescribe(process.platform !== 'win32')('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');
});
it('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');
}
});
it('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');
});
it('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');
});
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');
}
});
it('visibilityState remains visible if backgroundThrottling is disabled', async () => {
const w = new BrowserWindow({
show: false,
width: 100,
height: 100,
webPreferences: {
backgroundThrottling: false,
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');
}
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')('only shows the intended window when a child with siblings is shown', async () => {
const w = new BrowserWindow({ show: false });
const childOne = new BrowserWindow({ show: false, parent: w });
const childTwo = new BrowserWindow({ show: false, parent: w });
const parentShown = once(w, 'show');
w.show();
await parentShown;
expect(childOne.isVisible()).to.be.false('childOne is visible');
expect(childTwo.isVisible()).to.be.false('childTwo is visible');
const childOneShown = once(childOne, 'show');
childOne.show();
await childOneShown;
expect(childOne.isVisible()).to.be.true('childOne is not visible');
expect(childTwo.isVisible()).to.be.false('childTwo is visible');
});
ifit(process.platform === 'darwin')('child matches parent visibility when parent 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')('parent matches child visibility when child 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', async () => {
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();
const closed = once(childWindow, 'closed');
window.close();
await closed;
expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw();
});
});
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');
});
});
it('does not open non-fullscreenable child windows in fullscreen if parent is fullscreen', async () => {
const w = new BrowserWindow();
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
const child = new BrowserWindow({ parent: w, resizable: false, fullscreenable: false });
const shown = once(child, 'show');
await shown;
expect(child.resizable).to.be.false('resizable');
expect(child.fullScreen).to.be.false('fullscreen');
expect(child.fullScreenable).to.be.false('fullscreenable');
});
it('is set correctly with different resizable values', async () => {
const w1 = new BrowserWindow({
resizable: false,
fullscreenable: false
});
const w2 = new BrowserWindow({
resizable: true,
fullscreenable: false
});
const w3 = new BrowserWindow({
fullscreenable: false
});
expect(w1.isFullScreenable()).to.be.false('isFullScreenable');
expect(w2.isFullScreenable()).to.be.false('isFullScreenable');
expect(w3.isFullScreenable()).to.be.false('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 });
const isValidWindow = require('@electron-ci/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(1000);
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(1000);
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');
await setTimeout(1000);
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
| 40,097 |
[Bug]: desktopCapturer source IDs are valid for a single use on Wayland
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
27.0.0-beta.9
### What operating system are you using?
Other Linux
### Operating System Version
Fedora Workstation 39
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
1. Get a source ID from desktopCapturer
2. Display the stream using getUserMedia
3. Stop the stream
4. Display the stream again using getUserMedia
### Actual Behavior
XDG desktop portal permission dialog appears again
### Testcase Gist URL
https://gist.github.com/aiddya/cfd89d040661e0553425e4203ce4512b
### Additional Information
The fiddle has a timeout function that displays the stream after 10 seconds. So the steps to test using the fiddle boil down to: select a source, preview it, stop it and then wait 10 seconds.
|
https://github.com/electron/electron/issues/40097
|
https://github.com/electron/electron/pull/40098
|
7ab2a821669d4ce603a118b904f68e342ef3d807
|
3c31246343b3b4e9457d4672eebe46d64c673d0a
| 2023-10-05T02:22:27Z |
c++
| 2023-10-12T11:17:27Z |
patches/webrtc/.patches
|
fix_fallback_to_x11_capturer_on_wayland.patch
fix_mark_pipewire_capturer_as_failed_after_session_is_closed.patch
fix_check_pipewire_init_before_creating_generic_capturer.patch
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,097 |
[Bug]: desktopCapturer source IDs are valid for a single use on Wayland
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
27.0.0-beta.9
### What operating system are you using?
Other Linux
### Operating System Version
Fedora Workstation 39
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
1. Get a source ID from desktopCapturer
2. Display the stream using getUserMedia
3. Stop the stream
4. Display the stream again using getUserMedia
### Actual Behavior
XDG desktop portal permission dialog appears again
### Testcase Gist URL
https://gist.github.com/aiddya/cfd89d040661e0553425e4203ce4512b
### Additional Information
The fiddle has a timeout function that displays the stream after 10 seconds. So the steps to test using the fiddle boil down to: select a source, preview it, stop it and then wait 10 seconds.
|
https://github.com/electron/electron/issues/40097
|
https://github.com/electron/electron/pull/40098
|
7ab2a821669d4ce603a118b904f68e342ef3d807
|
3c31246343b3b4e9457d4672eebe46d64c673d0a
| 2023-10-05T02:22:27Z |
c++
| 2023-10-12T11:17:27Z |
patches/webrtc/pipewire_capturer_make_restore_tokens_re-usable_more_than_one_time.patch
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,097 |
[Bug]: desktopCapturer source IDs are valid for a single use on Wayland
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
27.0.0-beta.9
### What operating system are you using?
Other Linux
### Operating System Version
Fedora Workstation 39
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
1. Get a source ID from desktopCapturer
2. Display the stream using getUserMedia
3. Stop the stream
4. Display the stream again using getUserMedia
### Actual Behavior
XDG desktop portal permission dialog appears again
### Testcase Gist URL
https://gist.github.com/aiddya/cfd89d040661e0553425e4203ce4512b
### Additional Information
The fiddle has a timeout function that displays the stream after 10 seconds. So the steps to test using the fiddle boil down to: select a source, preview it, stop it and then wait 10 seconds.
|
https://github.com/electron/electron/issues/40097
|
https://github.com/electron/electron/pull/40098
|
7ab2a821669d4ce603a118b904f68e342ef3d807
|
3c31246343b3b4e9457d4672eebe46d64c673d0a
| 2023-10-05T02:22:27Z |
c++
| 2023-10-12T11:17:27Z |
patches/webrtc/.patches
|
fix_fallback_to_x11_capturer_on_wayland.patch
fix_mark_pipewire_capturer_as_failed_after_session_is_closed.patch
fix_check_pipewire_init_before_creating_generic_capturer.patch
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,097 |
[Bug]: desktopCapturer source IDs are valid for a single use on Wayland
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
27.0.0-beta.9
### What operating system are you using?
Other Linux
### Operating System Version
Fedora Workstation 39
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
1. Get a source ID from desktopCapturer
2. Display the stream using getUserMedia
3. Stop the stream
4. Display the stream again using getUserMedia
### Actual Behavior
XDG desktop portal permission dialog appears again
### Testcase Gist URL
https://gist.github.com/aiddya/cfd89d040661e0553425e4203ce4512b
### Additional Information
The fiddle has a timeout function that displays the stream after 10 seconds. So the steps to test using the fiddle boil down to: select a source, preview it, stop it and then wait 10 seconds.
|
https://github.com/electron/electron/issues/40097
|
https://github.com/electron/electron/pull/40098
|
7ab2a821669d4ce603a118b904f68e342ef3d807
|
3c31246343b3b4e9457d4672eebe46d64c673d0a
| 2023-10-05T02:22:27Z |
c++
| 2023-10-12T11:17:27Z |
patches/webrtc/pipewire_capturer_make_restore_tokens_re-usable_more_than_one_time.patch
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,041 |
[Bug]: Message ports don't close after garbage collection
|
### 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
28.0.0 / main
### What operating system are you using?
macOS
### Operating System Version
13.5
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
Prior to this CL: https://github.com/electron/electron/pull/39944
### Expected Behavior
Message ports will be automatically closed after they are garbage collected
### Actual Behavior
Message ports do not automatically closed after they are garbage collected, and won't close unless close is explicitly called
### Testcase Gist URL
https://gist.github.com/VerteDinde/8caf3292beb8cd8168e776d194f2bc64
### Additional Information
Steps to Repro:
1. Load the above gist
2. Let garbage collection occur, or simulate garbage collection with "Collect Garbage"
3. Take a heap snapshot and search for "message port".
Upstream Chromium bug filed here: https://bugs.chromium.org/p/chromium/issues/detail?id=1487835
This can also be reproduced in Chrome Canary by doing the following:
1. Load Canary, open DevTools
2. Run the following in console:
```
(function () {
const { port2 } = new MessageChannel();
port2.start();
})()
```
3. Simulate garbage collection with "Collect Garbage"
4. Take a heap snapshot and search for "message port"
|
https://github.com/electron/electron/issues/40041
|
https://github.com/electron/electron/pull/40189
|
5d6023ae0dfa289b8ce1427722b0a8c0ab24e648
|
bbd2236bdd4fda6ab702c67fa9a5cec13cc6df01
| 2023-09-29T02:54:28Z |
c++
| 2023-10-13T20:09:28Z |
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
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_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
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
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
refactor_expose_hostimportmoduledynamically_and.patch
feat_expose_documentloader_setdefersloading_on_webdocumentloader.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_disabling_background_throttling_in_compositor.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
fix_use_delegated_generic_capturer_when_available.patch
build_remove_ent_content_analysis_assert.patch
fix_activate_background_material_on_windows.patch
fix_move_autopipsettingshelper_behind_branding_buildflag.patch
revert_remove_the_allowaggressivethrottlingwithwebsocket_feature.patch
fix_handle_no_top_level_aura_window_in_webcontentsimpl.patch
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,041 |
[Bug]: Message ports don't close after garbage collection
|
### 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
28.0.0 / main
### What operating system are you using?
macOS
### Operating System Version
13.5
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
Prior to this CL: https://github.com/electron/electron/pull/39944
### Expected Behavior
Message ports will be automatically closed after they are garbage collected
### Actual Behavior
Message ports do not automatically closed after they are garbage collected, and won't close unless close is explicitly called
### Testcase Gist URL
https://gist.github.com/VerteDinde/8caf3292beb8cd8168e776d194f2bc64
### Additional Information
Steps to Repro:
1. Load the above gist
2. Let garbage collection occur, or simulate garbage collection with "Collect Garbage"
3. Take a heap snapshot and search for "message port".
Upstream Chromium bug filed here: https://bugs.chromium.org/p/chromium/issues/detail?id=1487835
This can also be reproduced in Chrome Canary by doing the following:
1. Load Canary, open DevTools
2. Run the following in console:
```
(function () {
const { port2 } = new MessageChannel();
port2.start();
})()
```
3. Simulate garbage collection with "Collect Garbage"
4. Take a heap snapshot and search for "message port"
|
https://github.com/electron/electron/issues/40041
|
https://github.com/electron/electron/pull/40189
|
5d6023ae0dfa289b8ce1427722b0a8c0ab24e648
|
bbd2236bdd4fda6ab702c67fa9a5cec13cc6df01
| 2023-09-29T02:54:28Z |
c++
| 2023-10-13T20:09:28Z |
patches/chromium/ensure_messageports_get_gced_when_not_referenced.patch
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,041 |
[Bug]: Message ports don't close after garbage collection
|
### 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
28.0.0 / main
### What operating system are you using?
macOS
### Operating System Version
13.5
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
Prior to this CL: https://github.com/electron/electron/pull/39944
### Expected Behavior
Message ports will be automatically closed after they are garbage collected
### Actual Behavior
Message ports do not automatically closed after they are garbage collected, and won't close unless close is explicitly called
### Testcase Gist URL
https://gist.github.com/VerteDinde/8caf3292beb8cd8168e776d194f2bc64
### Additional Information
Steps to Repro:
1. Load the above gist
2. Let garbage collection occur, or simulate garbage collection with "Collect Garbage"
3. Take a heap snapshot and search for "message port".
Upstream Chromium bug filed here: https://bugs.chromium.org/p/chromium/issues/detail?id=1487835
This can also be reproduced in Chrome Canary by doing the following:
1. Load Canary, open DevTools
2. Run the following in console:
```
(function () {
const { port2 } = new MessageChannel();
port2.start();
})()
```
3. Simulate garbage collection with "Collect Garbage"
4. Take a heap snapshot and search for "message port"
|
https://github.com/electron/electron/issues/40041
|
https://github.com/electron/electron/pull/40189
|
5d6023ae0dfa289b8ce1427722b0a8c0ab24e648
|
bbd2236bdd4fda6ab702c67fa9a5cec13cc6df01
| 2023-09-29T02:54:28Z |
c++
| 2023-10-13T20:09:28Z |
spec/api-ipc-spec.ts
|
import { EventEmitter, once } from 'node:events';
import { expect } from 'chai';
import { BrowserWindow, ipcMain, IpcMainInvokeEvent, MessageChannelMain, WebContents } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import { defer, listen } from './lib/spec-helpers';
import * as path from 'node:path';
import * as http from 'node:http';
const v8Util = process._linkedBinding('electron_common_v8_util');
const fixturesPath = path.resolve(__dirname, 'fixtures');
describe('ipc module', () => {
describe('invoke', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.loadURL('about:blank');
});
after(async () => {
w.destroy();
});
async function rendererInvoke (...args: any[]) {
const { ipcRenderer } = require('electron');
try {
const result = await ipcRenderer.invoke('test', ...args);
ipcRenderer.send('result', { result });
} catch (e) {
ipcRenderer.send('result', { error: (e as Error).message });
}
}
it('receives a response from a synchronous handler', async () => {
ipcMain.handleOnce('test', (e: IpcMainInvokeEvent, arg: number) => {
expect(arg).to.equal(123);
return 3;
});
const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => {
expect(arg).to.deep.equal({ result: 3 });
resolve();
}));
await w.webContents.executeJavaScript(`(${rendererInvoke})(123)`);
await done;
});
it('receives a response from an asynchronous handler', async () => {
ipcMain.handleOnce('test', async (e: IpcMainInvokeEvent, arg: number) => {
expect(arg).to.equal(123);
await new Promise(setImmediate);
return 3;
});
const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => {
expect(arg).to.deep.equal({ result: 3 });
resolve();
}));
await w.webContents.executeJavaScript(`(${rendererInvoke})(123)`);
await done;
});
it('receives an error from a synchronous handler', async () => {
ipcMain.handleOnce('test', () => {
throw new Error('some error');
});
const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => {
expect(arg.error).to.match(/some error/);
resolve();
}));
await w.webContents.executeJavaScript(`(${rendererInvoke})()`);
await done;
});
it('receives an error from an asynchronous handler', async () => {
ipcMain.handleOnce('test', async () => {
await new Promise(setImmediate);
throw new Error('some error');
});
const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => {
expect(arg.error).to.match(/some error/);
resolve();
}));
await w.webContents.executeJavaScript(`(${rendererInvoke})()`);
await done;
});
it('throws an error if no handler is registered', async () => {
const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => {
expect(arg.error).to.match(/No handler registered/);
resolve();
}));
await w.webContents.executeJavaScript(`(${rendererInvoke})()`);
await done;
});
it('throws an error when invoking a handler that was removed', async () => {
ipcMain.handle('test', () => { });
ipcMain.removeHandler('test');
const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => {
expect(arg.error).to.match(/No handler registered/);
resolve();
}));
await w.webContents.executeJavaScript(`(${rendererInvoke})()`);
await done;
});
it('forbids multiple handlers', async () => {
ipcMain.handle('test', () => { });
try {
expect(() => { ipcMain.handle('test', () => { }); }).to.throw(/second handler/);
} finally {
ipcMain.removeHandler('test');
}
});
it('throws an error in the renderer if the reply callback is dropped', async () => {
ipcMain.handleOnce('test', () => new Promise(() => {
setTimeout(() => v8Util.requestGarbageCollectionForTesting());
/* never resolve */
}));
w.webContents.executeJavaScript(`(${rendererInvoke})()`);
const [, { error }] = await once(ipcMain, 'result');
expect(error).to.match(/reply was never sent/);
});
});
describe('ordering', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.loadURL('about:blank');
});
after(async () => {
w.destroy();
});
it('between send and sendSync is consistent', async () => {
const received: number[] = [];
ipcMain.on('test-async', (e, i) => { received.push(i); });
ipcMain.on('test-sync', (e, i) => { received.push(i); e.returnValue = null; });
const done = new Promise<void>(resolve => ipcMain.once('done', () => { resolve(); }));
function rendererStressTest () {
const { ipcRenderer } = require('electron');
for (let i = 0; i < 1000; i++) {
switch ((Math.random() * 2) | 0) {
case 0:
ipcRenderer.send('test-async', i);
break;
case 1:
ipcRenderer.sendSync('test-sync', i);
break;
}
}
ipcRenderer.send('done');
}
try {
w.webContents.executeJavaScript(`(${rendererStressTest})()`);
await done;
} finally {
ipcMain.removeAllListeners('test-async');
ipcMain.removeAllListeners('test-sync');
}
expect(received).to.have.lengthOf(1000);
expect(received).to.deep.equal([...received].sort((a, b) => a - b));
});
it('between send, sendSync, and invoke is consistent', async () => {
const received: number[] = [];
ipcMain.handle('test-invoke', (e, i) => { received.push(i); });
ipcMain.on('test-async', (e, i) => { received.push(i); });
ipcMain.on('test-sync', (e, i) => { received.push(i); e.returnValue = null; });
const done = new Promise<void>(resolve => ipcMain.once('done', () => { resolve(); }));
function rendererStressTest () {
const { ipcRenderer } = require('electron');
for (let i = 0; i < 1000; i++) {
switch ((Math.random() * 3) | 0) {
case 0:
ipcRenderer.send('test-async', i);
break;
case 1:
ipcRenderer.sendSync('test-sync', i);
break;
case 2:
ipcRenderer.invoke('test-invoke', i);
break;
}
}
ipcRenderer.send('done');
}
try {
w.webContents.executeJavaScript(`(${rendererStressTest})()`);
await done;
} finally {
ipcMain.removeHandler('test-invoke');
ipcMain.removeAllListeners('test-async');
ipcMain.removeAllListeners('test-sync');
}
expect(received).to.have.lengthOf(1000);
expect(received).to.deep.equal([...received].sort((a, b) => a - b));
});
});
describe('MessagePort', () => {
afterEach(closeAllWindows);
it('can send a port to the main process', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
const p = once(ipcMain, 'port');
await w.webContents.executeJavaScript(`(${function () {
const channel = new MessageChannel();
require('electron').ipcRenderer.postMessage('port', 'hi', [channel.port1]);
}})()`);
const [ev, msg] = await p;
expect(msg).to.equal('hi');
expect(ev.ports).to.have.length(1);
expect(ev.senderFrame.parent).to.be.null();
expect(ev.senderFrame.routingId).to.equal(w.webContents.mainFrame.routingId);
const [port] = ev.ports;
expect(port).to.be.an.instanceOf(EventEmitter);
});
it('can sent a message without a transfer', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
const p = once(ipcMain, 'port');
await w.webContents.executeJavaScript(`(${function () {
require('electron').ipcRenderer.postMessage('port', 'hi');
}})()`);
const [ev, msg] = await p;
expect(msg).to.equal('hi');
expect(ev.ports).to.deep.equal([]);
expect(ev.senderFrame.routingId).to.equal(w.webContents.mainFrame.routingId);
});
it('can communicate between main and renderer', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
const p = once(ipcMain, 'port');
await w.webContents.executeJavaScript(`(${function () {
const channel = new MessageChannel();
channel.port2.onmessage = (ev: any) => {
channel.port2.postMessage(ev.data * 2);
};
require('electron').ipcRenderer.postMessage('port', '', [channel.port1]);
}})()`);
const [ev] = await p;
expect(ev.ports).to.have.length(1);
expect(ev.senderFrame.routingId).to.equal(w.webContents.mainFrame.routingId);
const [port] = ev.ports;
port.start();
port.postMessage(42);
const [ev2] = await once(port, 'message');
expect(ev2.data).to.equal(84);
});
it('can receive a port from a renderer over a MessagePort connection', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
function fn () {
const channel1 = new MessageChannel();
const channel2 = new MessageChannel();
channel1.port2.postMessage('', [channel2.port1]);
channel2.port2.postMessage('matryoshka');
require('electron').ipcRenderer.postMessage('port', '', [channel1.port1]);
}
w.webContents.executeJavaScript(`(${fn})()`);
const [{ ports: [port1] }] = await once(ipcMain, 'port');
port1.start();
const [{ ports: [port2] }] = await once(port1, 'message');
port2.start();
const [{ data }] = await once(port2, 'message');
expect(data).to.equal('matryoshka');
});
it('can forward a port from one renderer to another renderer', async () => {
const w1 = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const w2 = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w1.loadURL('about:blank');
w2.loadURL('about:blank');
w1.webContents.executeJavaScript(`(${function () {
const channel = new MessageChannel();
channel.port2.onmessage = (ev: any) => {
require('electron').ipcRenderer.send('message received', ev.data);
};
require('electron').ipcRenderer.postMessage('port', '', [channel.port1]);
}})()`);
const [{ ports: [port] }] = await once(ipcMain, 'port');
await w2.webContents.executeJavaScript(`(${function () {
require('electron').ipcRenderer.on('port', ({ ports: [port] }: any) => {
port.postMessage('a message');
});
}})()`);
w2.webContents.postMessage('port', '', [port]);
const [, data] = await once(ipcMain, 'message received');
expect(data).to.equal('a message');
});
describe('close event', () => {
describe('in renderer', () => {
it('is emitted when the main process closes its end of the port', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
await w.webContents.executeJavaScript(`(${function () {
const { ipcRenderer } = require('electron');
ipcRenderer.on('port', e => {
const [port] = e.ports;
port.start();
port.onclose = () => {
ipcRenderer.send('closed');
};
});
}})()`);
const { port1, port2 } = new MessageChannelMain();
w.webContents.postMessage('port', null, [port2]);
port1.close();
await once(ipcMain, 'closed');
});
// TODO(@vertedinde): This broke upstream in CL https://chromium-review.googlesource.com/c/chromium/src/+/4831380
// The behavior seems to be an intentional change, we need to either A) implement the task_container_ model in
// our renderer message ports or B) patch how we handle renderer message ports being garbage collected
// crbug: https://bugs.chromium.org/p/chromium/issues/detail?id=1487835
it.skip('is emitted when the other end of a port is garbage-collected', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
await w.webContents.executeJavaScript(`(${async function () {
const { port2 } = new MessageChannel();
await new Promise<void>(resolve => {
port2.start();
port2.onclose = resolve;
process._linkedBinding('electron_common_v8_util').requestGarbageCollectionForTesting();
});
}})()`);
});
it('is emitted when the other end of a port is sent to nowhere', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
ipcMain.once('do-a-gc', () => v8Util.requestGarbageCollectionForTesting());
await w.webContents.executeJavaScript(`(${async function () {
const { port1, port2 } = new MessageChannel();
await new Promise<void>(resolve => {
port2.start();
port2.onclose = resolve;
require('electron').ipcRenderer.postMessage('nobody-listening', null, [port1]);
require('electron').ipcRenderer.send('do-a-gc');
});
}})()`);
});
});
});
describe('MessageChannelMain', () => {
it('can be created', () => {
const { port1, port2 } = new MessageChannelMain();
expect(port1).not.to.be.null();
expect(port2).not.to.be.null();
});
it('throws an error when an invalid parameter is sent to postMessage', () => {
const { port1 } = new MessageChannelMain();
expect(() => {
const buffer = new ArrayBuffer(10) as any;
port1.postMessage(null, [buffer]);
}).to.throw(/Port at index 0 is not a valid port/);
expect(() => {
port1.postMessage(null, ['1' as any]);
}).to.throw(/Port at index 0 is not a valid port/);
expect(() => {
port1.postMessage(null, [new Date() as any]);
}).to.throw(/Port at index 0 is not a valid port/);
});
it('throws when postMessage transferables contains the source port', () => {
const { port1 } = new MessageChannelMain();
expect(() => {
port1.postMessage(null, [port1]);
}).to.throw(/Port at index 0 contains the source port./);
});
it('can send messages within the process', async () => {
const { port1, port2 } = new MessageChannelMain();
port2.postMessage('hello');
port1.start();
const [ev] = await once(port1, 'message');
expect(ev.data).to.equal('hello');
});
it('can pass one end to a WebContents', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
await w.webContents.executeJavaScript(`(${function () {
const { ipcRenderer } = require('electron');
ipcRenderer.on('port', ev => {
const [port] = ev.ports;
port.onmessage = () => {
ipcRenderer.send('done');
};
});
}})()`);
const { port1, port2 } = new MessageChannelMain();
port1.postMessage('hello');
w.webContents.postMessage('port', null, [port2]);
await once(ipcMain, 'done');
});
it('can be passed over another channel', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
await w.webContents.executeJavaScript(`(${function () {
const { ipcRenderer } = require('electron');
ipcRenderer.on('port', e1 => {
e1.ports[0].onmessage = e2 => {
e2.ports[0].onmessage = e3 => {
ipcRenderer.send('done', e3.data);
};
};
});
}})()`);
const { port1, port2 } = new MessageChannelMain();
const { port1: port3, port2: port4 } = new MessageChannelMain();
port1.postMessage(null, [port4]);
port3.postMessage('hello');
w.webContents.postMessage('port', null, [port2]);
const [, message] = await once(ipcMain, 'done');
expect(message).to.equal('hello');
});
it('can send messages to a closed port', () => {
const { port1, port2 } = new MessageChannelMain();
port2.start();
port2.on('message', () => { throw new Error('unexpected message received'); });
port1.close();
port1.postMessage('hello');
});
it('can send messages to a port whose remote end is closed', () => {
const { port1, port2 } = new MessageChannelMain();
port2.start();
port2.on('message', () => { throw new Error('unexpected message received'); });
port2.close();
port1.postMessage('hello');
});
it('throws when passing null ports', () => {
const { port1 } = new MessageChannelMain();
expect(() => {
port1.postMessage(null, [null] as any);
}).to.throw(/Port at index 0 is not a valid port/);
});
it('throws when passing duplicate ports', () => {
const { port1 } = new MessageChannelMain();
const { port1: port3 } = new MessageChannelMain();
expect(() => {
port1.postMessage(null, [port3, port3]);
}).to.throw(/duplicate/);
});
it('throws when passing ports that have already been neutered', () => {
const { port1 } = new MessageChannelMain();
const { port1: port3 } = new MessageChannelMain();
port1.postMessage(null, [port3]);
expect(() => {
port1.postMessage(null, [port3]);
}).to.throw(/already neutered/);
});
it('throws when passing itself', () => {
const { port1 } = new MessageChannelMain();
expect(() => {
port1.postMessage(null, [port1]);
}).to.throw(/contains the source port/);
});
describe('GC behavior', () => {
it('is not collected while it could still receive messages', async () => {
let trigger: Function;
const promise = new Promise(resolve => { trigger = resolve; });
const port1 = (() => {
const { port1, port2 } = new MessageChannelMain();
port2.on('message', (e) => { trigger(e.data); });
port2.start();
return port1;
})();
v8Util.requestGarbageCollectionForTesting();
port1.postMessage('hello');
expect(await promise).to.equal('hello');
});
});
});
const generateTests = (title: string, postMessage: (contents: WebContents) => WebContents['postMessage']) => {
describe(title, () => {
it('sends a message', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
await w.webContents.executeJavaScript(`(${function () {
const { ipcRenderer } = require('electron');
ipcRenderer.on('foo', (_e, msg) => {
ipcRenderer.send('bar', msg);
});
}})()`);
postMessage(w.webContents)('foo', { some: 'message' });
const [, msg] = await once(ipcMain, 'bar');
expect(msg).to.deep.equal({ some: 'message' });
});
describe('error handling', () => {
it('throws on missing channel', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(() => {
(postMessage(w.webContents) as any)();
}).to.throw(/Insufficient number of arguments/);
});
it('throws on invalid channel', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(() => {
postMessage(w.webContents)(null as any, '', []);
}).to.throw(/Error processing argument at index 0/);
});
it('throws on missing message', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(() => {
(postMessage(w.webContents) as any)('channel');
}).to.throw(/Insufficient number of arguments/);
});
it('throws on non-serializable message', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(() => {
postMessage(w.webContents)('channel', w);
}).to.throw(/An object could not be cloned/);
});
it('throws on invalid transferable list', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(() => {
postMessage(w.webContents)('', '', null as any);
}).to.throw(/Invalid value for transfer/);
});
it('throws on transferring non-transferable', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(() => {
(postMessage(w.webContents) as any)('channel', '', [123]);
}).to.throw(/Invalid value for transfer/);
});
it('throws when passing null ports', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(() => {
postMessage(w.webContents)('foo', null, [null] as any);
}).to.throw(/Invalid value for transfer/);
});
it('throws when passing duplicate ports', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const { port1 } = new MessageChannelMain();
expect(() => {
postMessage(w.webContents)('foo', null, [port1, port1]);
}).to.throw(/duplicate/);
});
it('throws when passing ports that have already been neutered', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const { port1 } = new MessageChannelMain();
postMessage(w.webContents)('foo', null, [port1]);
expect(() => {
postMessage(w.webContents)('foo', null, [port1]);
}).to.throw(/already neutered/);
});
});
});
};
generateTests('WebContents.postMessage', contents => contents.postMessage.bind(contents));
generateTests('WebFrameMain.postMessage', contents => contents.mainFrame.postMessage.bind(contents.mainFrame));
});
describe('WebContents.ipc', () => {
afterEach(closeAllWindows);
it('receives ipc messages sent from the WebContents', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.send(\'test\', 42)');
const [, num] = await once(w.webContents.ipc, 'test');
expect(num).to.equal(42);
});
it('receives sync-ipc messages sent from the WebContents', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.ipc.on('test', (event, arg) => {
event.returnValue = arg * 2;
});
const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.sendSync(\'test\', 42)');
expect(result).to.equal(42 * 2);
});
it('receives postMessage messages sent from the WebContents, w/ MessagePorts', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.postMessage(\'test\', null, [(new MessageChannel).port1])');
const [event] = await once(w.webContents.ipc, 'test');
expect(event.ports.length).to.equal(1);
});
it('handles invoke messages sent from the WebContents', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.ipc.handle('test', (_event, arg) => arg * 2);
const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
expect(result).to.equal(42 * 2);
});
it('cascades to ipcMain', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
let gotFromIpcMain = false;
const ipcMainReceived = new Promise<void>(resolve => ipcMain.on('test', () => { gotFromIpcMain = true; resolve(); }));
const ipcReceived = new Promise<boolean>(resolve => w.webContents.ipc.on('test', () => { resolve(gotFromIpcMain); }));
defer(() => ipcMain.removeAllListeners('test'));
w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.send(\'test\', 42)');
// assert that they are delivered in the correct order
expect(await ipcReceived).to.be.false();
await ipcMainReceived;
});
it('overrides ipcMain handlers', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.ipc.handle('test', (_event, arg) => arg * 2);
ipcMain.handle('test', () => { throw new Error('should not be called'); });
defer(() => ipcMain.removeHandler('test'));
const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
expect(result).to.equal(42 * 2);
});
it('falls back to ipcMain handlers', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
ipcMain.handle('test', (_event, arg) => { return arg * 2; });
defer(() => ipcMain.removeHandler('test'));
const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
expect(result).to.equal(42 * 2);
});
it('receives ipcs from child frames', async () => {
const server = http.createServer((req, res) => {
res.setHeader('content-type', 'text/html');
res.end('');
});
const { port } = await listen(server);
defer(() => {
server.close();
});
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, preload: path.resolve(fixturesPath, 'preload-expose-ipc.js') } });
// Preloads don't run in about:blank windows, and file:// urls can't be loaded in iframes, so use a blank http page.
await w.loadURL(`data:text/html,<iframe src="http://localhost:${port}"></iframe>`);
w.webContents.mainFrame.frames[0].executeJavaScript('ipc.send(\'test\', 42)');
const [, arg] = await once(w.webContents.ipc, 'test');
expect(arg).to.equal(42);
});
});
describe('WebFrameMain.ipc', () => {
afterEach(closeAllWindows);
it('responds to ipc messages in the main frame', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.send(\'test\', 42)');
const [, arg] = await once(w.webContents.mainFrame.ipc, 'test');
expect(arg).to.equal(42);
});
it('responds to sync ipc messages in the main frame', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.mainFrame.ipc.on('test', (event, arg) => {
event.returnValue = arg * 2;
});
const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.sendSync(\'test\', 42)');
expect(result).to.equal(42 * 2);
});
it('receives postMessage messages sent from the WebContents, w/ MessagePorts', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.postMessage(\'test\', null, [(new MessageChannel).port1])');
const [event] = await once(w.webContents.mainFrame.ipc, 'test');
expect(event.ports.length).to.equal(1);
});
it('handles invoke messages sent from the WebContents', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.mainFrame.ipc.handle('test', (_event, arg) => arg * 2);
const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
expect(result).to.equal(42 * 2);
});
it('cascades to WebContents and ipcMain', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
let gotFromIpcMain = false;
let gotFromWebContents = false;
const ipcMainReceived = new Promise<void>(resolve => ipcMain.on('test', () => { gotFromIpcMain = true; resolve(); }));
const ipcWebContentsReceived = new Promise<boolean>(resolve => w.webContents.ipc.on('test', () => { gotFromWebContents = true; resolve(gotFromIpcMain); }));
const ipcReceived = new Promise<boolean>(resolve => w.webContents.mainFrame.ipc.on('test', () => { resolve(gotFromWebContents); }));
defer(() => ipcMain.removeAllListeners('test'));
w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.send(\'test\', 42)');
// assert that they are delivered in the correct order
expect(await ipcReceived).to.be.false();
expect(await ipcWebContentsReceived).to.be.false();
await ipcMainReceived;
});
it('overrides ipcMain handlers', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.mainFrame.ipc.handle('test', (_event, arg) => arg * 2);
ipcMain.handle('test', () => { throw new Error('should not be called'); });
defer(() => ipcMain.removeHandler('test'));
const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
expect(result).to.equal(42 * 2);
});
it('overrides WebContents handlers', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.ipc.handle('test', () => { throw new Error('should not be called'); });
w.webContents.mainFrame.ipc.handle('test', (_event, arg) => arg * 2);
ipcMain.handle('test', () => { throw new Error('should not be called'); });
defer(() => ipcMain.removeHandler('test'));
const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
expect(result).to.equal(42 * 2);
});
it('falls back to WebContents handlers', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.ipc.handle('test', (_event, arg) => { return arg * 2; });
const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
expect(result).to.equal(42 * 2);
});
it('receives ipcs from child frames', async () => {
const server = http.createServer((req, res) => {
res.setHeader('content-type', 'text/html');
res.end('');
});
const { port } = await listen(server);
defer(() => {
server.close();
});
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, preload: path.resolve(fixturesPath, 'preload-expose-ipc.js') } });
// Preloads don't run in about:blank windows, and file:// urls can't be loaded in iframes, so use a blank http page.
await w.loadURL(`data:text/html,<iframe src="http://localhost:${port}"></iframe>`);
w.webContents.mainFrame.frames[0].executeJavaScript('ipc.send(\'test\', 42)');
w.webContents.mainFrame.ipc.on('test', () => { throw new Error('should not be called'); });
const [, arg] = await once(w.webContents.mainFrame.frames[0].ipc, 'test');
expect(arg).to.equal(42);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,041 |
[Bug]: Message ports don't close after garbage collection
|
### 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
28.0.0 / main
### What operating system are you using?
macOS
### Operating System Version
13.5
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
Prior to this CL: https://github.com/electron/electron/pull/39944
### Expected Behavior
Message ports will be automatically closed after they are garbage collected
### Actual Behavior
Message ports do not automatically closed after they are garbage collected, and won't close unless close is explicitly called
### Testcase Gist URL
https://gist.github.com/VerteDinde/8caf3292beb8cd8168e776d194f2bc64
### Additional Information
Steps to Repro:
1. Load the above gist
2. Let garbage collection occur, or simulate garbage collection with "Collect Garbage"
3. Take a heap snapshot and search for "message port".
Upstream Chromium bug filed here: https://bugs.chromium.org/p/chromium/issues/detail?id=1487835
This can also be reproduced in Chrome Canary by doing the following:
1. Load Canary, open DevTools
2. Run the following in console:
```
(function () {
const { port2 } = new MessageChannel();
port2.start();
})()
```
3. Simulate garbage collection with "Collect Garbage"
4. Take a heap snapshot and search for "message port"
|
https://github.com/electron/electron/issues/40041
|
https://github.com/electron/electron/pull/40189
|
5d6023ae0dfa289b8ce1427722b0a8c0ab24e648
|
bbd2236bdd4fda6ab702c67fa9a5cec13cc6df01
| 2023-09-29T02:54:28Z |
c++
| 2023-10-13T20:09:28Z |
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
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_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
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
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
refactor_expose_hostimportmoduledynamically_and.patch
feat_expose_documentloader_setdefersloading_on_webdocumentloader.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_disabling_background_throttling_in_compositor.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
fix_use_delegated_generic_capturer_when_available.patch
build_remove_ent_content_analysis_assert.patch
fix_activate_background_material_on_windows.patch
fix_move_autopipsettingshelper_behind_branding_buildflag.patch
revert_remove_the_allowaggressivethrottlingwithwebsocket_feature.patch
fix_handle_no_top_level_aura_window_in_webcontentsimpl.patch
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,041 |
[Bug]: Message ports don't close after garbage collection
|
### 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
28.0.0 / main
### What operating system are you using?
macOS
### Operating System Version
13.5
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
Prior to this CL: https://github.com/electron/electron/pull/39944
### Expected Behavior
Message ports will be automatically closed after they are garbage collected
### Actual Behavior
Message ports do not automatically closed after they are garbage collected, and won't close unless close is explicitly called
### Testcase Gist URL
https://gist.github.com/VerteDinde/8caf3292beb8cd8168e776d194f2bc64
### Additional Information
Steps to Repro:
1. Load the above gist
2. Let garbage collection occur, or simulate garbage collection with "Collect Garbage"
3. Take a heap snapshot and search for "message port".
Upstream Chromium bug filed here: https://bugs.chromium.org/p/chromium/issues/detail?id=1487835
This can also be reproduced in Chrome Canary by doing the following:
1. Load Canary, open DevTools
2. Run the following in console:
```
(function () {
const { port2 } = new MessageChannel();
port2.start();
})()
```
3. Simulate garbage collection with "Collect Garbage"
4. Take a heap snapshot and search for "message port"
|
https://github.com/electron/electron/issues/40041
|
https://github.com/electron/electron/pull/40189
|
5d6023ae0dfa289b8ce1427722b0a8c0ab24e648
|
bbd2236bdd4fda6ab702c67fa9a5cec13cc6df01
| 2023-09-29T02:54:28Z |
c++
| 2023-10-13T20:09:28Z |
patches/chromium/ensure_messageports_get_gced_when_not_referenced.patch
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,041 |
[Bug]: Message ports don't close after garbage collection
|
### 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
28.0.0 / main
### What operating system are you using?
macOS
### Operating System Version
13.5
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
Prior to this CL: https://github.com/electron/electron/pull/39944
### Expected Behavior
Message ports will be automatically closed after they are garbage collected
### Actual Behavior
Message ports do not automatically closed after they are garbage collected, and won't close unless close is explicitly called
### Testcase Gist URL
https://gist.github.com/VerteDinde/8caf3292beb8cd8168e776d194f2bc64
### Additional Information
Steps to Repro:
1. Load the above gist
2. Let garbage collection occur, or simulate garbage collection with "Collect Garbage"
3. Take a heap snapshot and search for "message port".
Upstream Chromium bug filed here: https://bugs.chromium.org/p/chromium/issues/detail?id=1487835
This can also be reproduced in Chrome Canary by doing the following:
1. Load Canary, open DevTools
2. Run the following in console:
```
(function () {
const { port2 } = new MessageChannel();
port2.start();
})()
```
3. Simulate garbage collection with "Collect Garbage"
4. Take a heap snapshot and search for "message port"
|
https://github.com/electron/electron/issues/40041
|
https://github.com/electron/electron/pull/40189
|
5d6023ae0dfa289b8ce1427722b0a8c0ab24e648
|
bbd2236bdd4fda6ab702c67fa9a5cec13cc6df01
| 2023-09-29T02:54:28Z |
c++
| 2023-10-13T20:09:28Z |
spec/api-ipc-spec.ts
|
import { EventEmitter, once } from 'node:events';
import { expect } from 'chai';
import { BrowserWindow, ipcMain, IpcMainInvokeEvent, MessageChannelMain, WebContents } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import { defer, listen } from './lib/spec-helpers';
import * as path from 'node:path';
import * as http from 'node:http';
const v8Util = process._linkedBinding('electron_common_v8_util');
const fixturesPath = path.resolve(__dirname, 'fixtures');
describe('ipc module', () => {
describe('invoke', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.loadURL('about:blank');
});
after(async () => {
w.destroy();
});
async function rendererInvoke (...args: any[]) {
const { ipcRenderer } = require('electron');
try {
const result = await ipcRenderer.invoke('test', ...args);
ipcRenderer.send('result', { result });
} catch (e) {
ipcRenderer.send('result', { error: (e as Error).message });
}
}
it('receives a response from a synchronous handler', async () => {
ipcMain.handleOnce('test', (e: IpcMainInvokeEvent, arg: number) => {
expect(arg).to.equal(123);
return 3;
});
const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => {
expect(arg).to.deep.equal({ result: 3 });
resolve();
}));
await w.webContents.executeJavaScript(`(${rendererInvoke})(123)`);
await done;
});
it('receives a response from an asynchronous handler', async () => {
ipcMain.handleOnce('test', async (e: IpcMainInvokeEvent, arg: number) => {
expect(arg).to.equal(123);
await new Promise(setImmediate);
return 3;
});
const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => {
expect(arg).to.deep.equal({ result: 3 });
resolve();
}));
await w.webContents.executeJavaScript(`(${rendererInvoke})(123)`);
await done;
});
it('receives an error from a synchronous handler', async () => {
ipcMain.handleOnce('test', () => {
throw new Error('some error');
});
const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => {
expect(arg.error).to.match(/some error/);
resolve();
}));
await w.webContents.executeJavaScript(`(${rendererInvoke})()`);
await done;
});
it('receives an error from an asynchronous handler', async () => {
ipcMain.handleOnce('test', async () => {
await new Promise(setImmediate);
throw new Error('some error');
});
const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => {
expect(arg.error).to.match(/some error/);
resolve();
}));
await w.webContents.executeJavaScript(`(${rendererInvoke})()`);
await done;
});
it('throws an error if no handler is registered', async () => {
const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => {
expect(arg.error).to.match(/No handler registered/);
resolve();
}));
await w.webContents.executeJavaScript(`(${rendererInvoke})()`);
await done;
});
it('throws an error when invoking a handler that was removed', async () => {
ipcMain.handle('test', () => { });
ipcMain.removeHandler('test');
const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => {
expect(arg.error).to.match(/No handler registered/);
resolve();
}));
await w.webContents.executeJavaScript(`(${rendererInvoke})()`);
await done;
});
it('forbids multiple handlers', async () => {
ipcMain.handle('test', () => { });
try {
expect(() => { ipcMain.handle('test', () => { }); }).to.throw(/second handler/);
} finally {
ipcMain.removeHandler('test');
}
});
it('throws an error in the renderer if the reply callback is dropped', async () => {
ipcMain.handleOnce('test', () => new Promise(() => {
setTimeout(() => v8Util.requestGarbageCollectionForTesting());
/* never resolve */
}));
w.webContents.executeJavaScript(`(${rendererInvoke})()`);
const [, { error }] = await once(ipcMain, 'result');
expect(error).to.match(/reply was never sent/);
});
});
describe('ordering', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.loadURL('about:blank');
});
after(async () => {
w.destroy();
});
it('between send and sendSync is consistent', async () => {
const received: number[] = [];
ipcMain.on('test-async', (e, i) => { received.push(i); });
ipcMain.on('test-sync', (e, i) => { received.push(i); e.returnValue = null; });
const done = new Promise<void>(resolve => ipcMain.once('done', () => { resolve(); }));
function rendererStressTest () {
const { ipcRenderer } = require('electron');
for (let i = 0; i < 1000; i++) {
switch ((Math.random() * 2) | 0) {
case 0:
ipcRenderer.send('test-async', i);
break;
case 1:
ipcRenderer.sendSync('test-sync', i);
break;
}
}
ipcRenderer.send('done');
}
try {
w.webContents.executeJavaScript(`(${rendererStressTest})()`);
await done;
} finally {
ipcMain.removeAllListeners('test-async');
ipcMain.removeAllListeners('test-sync');
}
expect(received).to.have.lengthOf(1000);
expect(received).to.deep.equal([...received].sort((a, b) => a - b));
});
it('between send, sendSync, and invoke is consistent', async () => {
const received: number[] = [];
ipcMain.handle('test-invoke', (e, i) => { received.push(i); });
ipcMain.on('test-async', (e, i) => { received.push(i); });
ipcMain.on('test-sync', (e, i) => { received.push(i); e.returnValue = null; });
const done = new Promise<void>(resolve => ipcMain.once('done', () => { resolve(); }));
function rendererStressTest () {
const { ipcRenderer } = require('electron');
for (let i = 0; i < 1000; i++) {
switch ((Math.random() * 3) | 0) {
case 0:
ipcRenderer.send('test-async', i);
break;
case 1:
ipcRenderer.sendSync('test-sync', i);
break;
case 2:
ipcRenderer.invoke('test-invoke', i);
break;
}
}
ipcRenderer.send('done');
}
try {
w.webContents.executeJavaScript(`(${rendererStressTest})()`);
await done;
} finally {
ipcMain.removeHandler('test-invoke');
ipcMain.removeAllListeners('test-async');
ipcMain.removeAllListeners('test-sync');
}
expect(received).to.have.lengthOf(1000);
expect(received).to.deep.equal([...received].sort((a, b) => a - b));
});
});
describe('MessagePort', () => {
afterEach(closeAllWindows);
it('can send a port to the main process', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
const p = once(ipcMain, 'port');
await w.webContents.executeJavaScript(`(${function () {
const channel = new MessageChannel();
require('electron').ipcRenderer.postMessage('port', 'hi', [channel.port1]);
}})()`);
const [ev, msg] = await p;
expect(msg).to.equal('hi');
expect(ev.ports).to.have.length(1);
expect(ev.senderFrame.parent).to.be.null();
expect(ev.senderFrame.routingId).to.equal(w.webContents.mainFrame.routingId);
const [port] = ev.ports;
expect(port).to.be.an.instanceOf(EventEmitter);
});
it('can sent a message without a transfer', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
const p = once(ipcMain, 'port');
await w.webContents.executeJavaScript(`(${function () {
require('electron').ipcRenderer.postMessage('port', 'hi');
}})()`);
const [ev, msg] = await p;
expect(msg).to.equal('hi');
expect(ev.ports).to.deep.equal([]);
expect(ev.senderFrame.routingId).to.equal(w.webContents.mainFrame.routingId);
});
it('can communicate between main and renderer', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
const p = once(ipcMain, 'port');
await w.webContents.executeJavaScript(`(${function () {
const channel = new MessageChannel();
channel.port2.onmessage = (ev: any) => {
channel.port2.postMessage(ev.data * 2);
};
require('electron').ipcRenderer.postMessage('port', '', [channel.port1]);
}})()`);
const [ev] = await p;
expect(ev.ports).to.have.length(1);
expect(ev.senderFrame.routingId).to.equal(w.webContents.mainFrame.routingId);
const [port] = ev.ports;
port.start();
port.postMessage(42);
const [ev2] = await once(port, 'message');
expect(ev2.data).to.equal(84);
});
it('can receive a port from a renderer over a MessagePort connection', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
function fn () {
const channel1 = new MessageChannel();
const channel2 = new MessageChannel();
channel1.port2.postMessage('', [channel2.port1]);
channel2.port2.postMessage('matryoshka');
require('electron').ipcRenderer.postMessage('port', '', [channel1.port1]);
}
w.webContents.executeJavaScript(`(${fn})()`);
const [{ ports: [port1] }] = await once(ipcMain, 'port');
port1.start();
const [{ ports: [port2] }] = await once(port1, 'message');
port2.start();
const [{ data }] = await once(port2, 'message');
expect(data).to.equal('matryoshka');
});
it('can forward a port from one renderer to another renderer', async () => {
const w1 = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const w2 = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w1.loadURL('about:blank');
w2.loadURL('about:blank');
w1.webContents.executeJavaScript(`(${function () {
const channel = new MessageChannel();
channel.port2.onmessage = (ev: any) => {
require('electron').ipcRenderer.send('message received', ev.data);
};
require('electron').ipcRenderer.postMessage('port', '', [channel.port1]);
}})()`);
const [{ ports: [port] }] = await once(ipcMain, 'port');
await w2.webContents.executeJavaScript(`(${function () {
require('electron').ipcRenderer.on('port', ({ ports: [port] }: any) => {
port.postMessage('a message');
});
}})()`);
w2.webContents.postMessage('port', '', [port]);
const [, data] = await once(ipcMain, 'message received');
expect(data).to.equal('a message');
});
describe('close event', () => {
describe('in renderer', () => {
it('is emitted when the main process closes its end of the port', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
await w.webContents.executeJavaScript(`(${function () {
const { ipcRenderer } = require('electron');
ipcRenderer.on('port', e => {
const [port] = e.ports;
port.start();
port.onclose = () => {
ipcRenderer.send('closed');
};
});
}})()`);
const { port1, port2 } = new MessageChannelMain();
w.webContents.postMessage('port', null, [port2]);
port1.close();
await once(ipcMain, 'closed');
});
// TODO(@vertedinde): This broke upstream in CL https://chromium-review.googlesource.com/c/chromium/src/+/4831380
// The behavior seems to be an intentional change, we need to either A) implement the task_container_ model in
// our renderer message ports or B) patch how we handle renderer message ports being garbage collected
// crbug: https://bugs.chromium.org/p/chromium/issues/detail?id=1487835
it.skip('is emitted when the other end of a port is garbage-collected', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
await w.webContents.executeJavaScript(`(${async function () {
const { port2 } = new MessageChannel();
await new Promise<void>(resolve => {
port2.start();
port2.onclose = resolve;
process._linkedBinding('electron_common_v8_util').requestGarbageCollectionForTesting();
});
}})()`);
});
it('is emitted when the other end of a port is sent to nowhere', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
ipcMain.once('do-a-gc', () => v8Util.requestGarbageCollectionForTesting());
await w.webContents.executeJavaScript(`(${async function () {
const { port1, port2 } = new MessageChannel();
await new Promise<void>(resolve => {
port2.start();
port2.onclose = resolve;
require('electron').ipcRenderer.postMessage('nobody-listening', null, [port1]);
require('electron').ipcRenderer.send('do-a-gc');
});
}})()`);
});
});
});
describe('MessageChannelMain', () => {
it('can be created', () => {
const { port1, port2 } = new MessageChannelMain();
expect(port1).not.to.be.null();
expect(port2).not.to.be.null();
});
it('throws an error when an invalid parameter is sent to postMessage', () => {
const { port1 } = new MessageChannelMain();
expect(() => {
const buffer = new ArrayBuffer(10) as any;
port1.postMessage(null, [buffer]);
}).to.throw(/Port at index 0 is not a valid port/);
expect(() => {
port1.postMessage(null, ['1' as any]);
}).to.throw(/Port at index 0 is not a valid port/);
expect(() => {
port1.postMessage(null, [new Date() as any]);
}).to.throw(/Port at index 0 is not a valid port/);
});
it('throws when postMessage transferables contains the source port', () => {
const { port1 } = new MessageChannelMain();
expect(() => {
port1.postMessage(null, [port1]);
}).to.throw(/Port at index 0 contains the source port./);
});
it('can send messages within the process', async () => {
const { port1, port2 } = new MessageChannelMain();
port2.postMessage('hello');
port1.start();
const [ev] = await once(port1, 'message');
expect(ev.data).to.equal('hello');
});
it('can pass one end to a WebContents', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
await w.webContents.executeJavaScript(`(${function () {
const { ipcRenderer } = require('electron');
ipcRenderer.on('port', ev => {
const [port] = ev.ports;
port.onmessage = () => {
ipcRenderer.send('done');
};
});
}})()`);
const { port1, port2 } = new MessageChannelMain();
port1.postMessage('hello');
w.webContents.postMessage('port', null, [port2]);
await once(ipcMain, 'done');
});
it('can be passed over another channel', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
await w.webContents.executeJavaScript(`(${function () {
const { ipcRenderer } = require('electron');
ipcRenderer.on('port', e1 => {
e1.ports[0].onmessage = e2 => {
e2.ports[0].onmessage = e3 => {
ipcRenderer.send('done', e3.data);
};
};
});
}})()`);
const { port1, port2 } = new MessageChannelMain();
const { port1: port3, port2: port4 } = new MessageChannelMain();
port1.postMessage(null, [port4]);
port3.postMessage('hello');
w.webContents.postMessage('port', null, [port2]);
const [, message] = await once(ipcMain, 'done');
expect(message).to.equal('hello');
});
it('can send messages to a closed port', () => {
const { port1, port2 } = new MessageChannelMain();
port2.start();
port2.on('message', () => { throw new Error('unexpected message received'); });
port1.close();
port1.postMessage('hello');
});
it('can send messages to a port whose remote end is closed', () => {
const { port1, port2 } = new MessageChannelMain();
port2.start();
port2.on('message', () => { throw new Error('unexpected message received'); });
port2.close();
port1.postMessage('hello');
});
it('throws when passing null ports', () => {
const { port1 } = new MessageChannelMain();
expect(() => {
port1.postMessage(null, [null] as any);
}).to.throw(/Port at index 0 is not a valid port/);
});
it('throws when passing duplicate ports', () => {
const { port1 } = new MessageChannelMain();
const { port1: port3 } = new MessageChannelMain();
expect(() => {
port1.postMessage(null, [port3, port3]);
}).to.throw(/duplicate/);
});
it('throws when passing ports that have already been neutered', () => {
const { port1 } = new MessageChannelMain();
const { port1: port3 } = new MessageChannelMain();
port1.postMessage(null, [port3]);
expect(() => {
port1.postMessage(null, [port3]);
}).to.throw(/already neutered/);
});
it('throws when passing itself', () => {
const { port1 } = new MessageChannelMain();
expect(() => {
port1.postMessage(null, [port1]);
}).to.throw(/contains the source port/);
});
describe('GC behavior', () => {
it('is not collected while it could still receive messages', async () => {
let trigger: Function;
const promise = new Promise(resolve => { trigger = resolve; });
const port1 = (() => {
const { port1, port2 } = new MessageChannelMain();
port2.on('message', (e) => { trigger(e.data); });
port2.start();
return port1;
})();
v8Util.requestGarbageCollectionForTesting();
port1.postMessage('hello');
expect(await promise).to.equal('hello');
});
});
});
const generateTests = (title: string, postMessage: (contents: WebContents) => WebContents['postMessage']) => {
describe(title, () => {
it('sends a message', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
await w.webContents.executeJavaScript(`(${function () {
const { ipcRenderer } = require('electron');
ipcRenderer.on('foo', (_e, msg) => {
ipcRenderer.send('bar', msg);
});
}})()`);
postMessage(w.webContents)('foo', { some: 'message' });
const [, msg] = await once(ipcMain, 'bar');
expect(msg).to.deep.equal({ some: 'message' });
});
describe('error handling', () => {
it('throws on missing channel', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(() => {
(postMessage(w.webContents) as any)();
}).to.throw(/Insufficient number of arguments/);
});
it('throws on invalid channel', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(() => {
postMessage(w.webContents)(null as any, '', []);
}).to.throw(/Error processing argument at index 0/);
});
it('throws on missing message', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(() => {
(postMessage(w.webContents) as any)('channel');
}).to.throw(/Insufficient number of arguments/);
});
it('throws on non-serializable message', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(() => {
postMessage(w.webContents)('channel', w);
}).to.throw(/An object could not be cloned/);
});
it('throws on invalid transferable list', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(() => {
postMessage(w.webContents)('', '', null as any);
}).to.throw(/Invalid value for transfer/);
});
it('throws on transferring non-transferable', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(() => {
(postMessage(w.webContents) as any)('channel', '', [123]);
}).to.throw(/Invalid value for transfer/);
});
it('throws when passing null ports', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(() => {
postMessage(w.webContents)('foo', null, [null] as any);
}).to.throw(/Invalid value for transfer/);
});
it('throws when passing duplicate ports', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const { port1 } = new MessageChannelMain();
expect(() => {
postMessage(w.webContents)('foo', null, [port1, port1]);
}).to.throw(/duplicate/);
});
it('throws when passing ports that have already been neutered', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const { port1 } = new MessageChannelMain();
postMessage(w.webContents)('foo', null, [port1]);
expect(() => {
postMessage(w.webContents)('foo', null, [port1]);
}).to.throw(/already neutered/);
});
});
});
};
generateTests('WebContents.postMessage', contents => contents.postMessage.bind(contents));
generateTests('WebFrameMain.postMessage', contents => contents.mainFrame.postMessage.bind(contents.mainFrame));
});
describe('WebContents.ipc', () => {
afterEach(closeAllWindows);
it('receives ipc messages sent from the WebContents', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.send(\'test\', 42)');
const [, num] = await once(w.webContents.ipc, 'test');
expect(num).to.equal(42);
});
it('receives sync-ipc messages sent from the WebContents', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.ipc.on('test', (event, arg) => {
event.returnValue = arg * 2;
});
const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.sendSync(\'test\', 42)');
expect(result).to.equal(42 * 2);
});
it('receives postMessage messages sent from the WebContents, w/ MessagePorts', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.postMessage(\'test\', null, [(new MessageChannel).port1])');
const [event] = await once(w.webContents.ipc, 'test');
expect(event.ports.length).to.equal(1);
});
it('handles invoke messages sent from the WebContents', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.ipc.handle('test', (_event, arg) => arg * 2);
const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
expect(result).to.equal(42 * 2);
});
it('cascades to ipcMain', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
let gotFromIpcMain = false;
const ipcMainReceived = new Promise<void>(resolve => ipcMain.on('test', () => { gotFromIpcMain = true; resolve(); }));
const ipcReceived = new Promise<boolean>(resolve => w.webContents.ipc.on('test', () => { resolve(gotFromIpcMain); }));
defer(() => ipcMain.removeAllListeners('test'));
w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.send(\'test\', 42)');
// assert that they are delivered in the correct order
expect(await ipcReceived).to.be.false();
await ipcMainReceived;
});
it('overrides ipcMain handlers', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.ipc.handle('test', (_event, arg) => arg * 2);
ipcMain.handle('test', () => { throw new Error('should not be called'); });
defer(() => ipcMain.removeHandler('test'));
const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
expect(result).to.equal(42 * 2);
});
it('falls back to ipcMain handlers', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
ipcMain.handle('test', (_event, arg) => { return arg * 2; });
defer(() => ipcMain.removeHandler('test'));
const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
expect(result).to.equal(42 * 2);
});
it('receives ipcs from child frames', async () => {
const server = http.createServer((req, res) => {
res.setHeader('content-type', 'text/html');
res.end('');
});
const { port } = await listen(server);
defer(() => {
server.close();
});
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, preload: path.resolve(fixturesPath, 'preload-expose-ipc.js') } });
// Preloads don't run in about:blank windows, and file:// urls can't be loaded in iframes, so use a blank http page.
await w.loadURL(`data:text/html,<iframe src="http://localhost:${port}"></iframe>`);
w.webContents.mainFrame.frames[0].executeJavaScript('ipc.send(\'test\', 42)');
const [, arg] = await once(w.webContents.ipc, 'test');
expect(arg).to.equal(42);
});
});
describe('WebFrameMain.ipc', () => {
afterEach(closeAllWindows);
it('responds to ipc messages in the main frame', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.send(\'test\', 42)');
const [, arg] = await once(w.webContents.mainFrame.ipc, 'test');
expect(arg).to.equal(42);
});
it('responds to sync ipc messages in the main frame', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.mainFrame.ipc.on('test', (event, arg) => {
event.returnValue = arg * 2;
});
const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.sendSync(\'test\', 42)');
expect(result).to.equal(42 * 2);
});
it('receives postMessage messages sent from the WebContents, w/ MessagePorts', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.postMessage(\'test\', null, [(new MessageChannel).port1])');
const [event] = await once(w.webContents.mainFrame.ipc, 'test');
expect(event.ports.length).to.equal(1);
});
it('handles invoke messages sent from the WebContents', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.mainFrame.ipc.handle('test', (_event, arg) => arg * 2);
const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
expect(result).to.equal(42 * 2);
});
it('cascades to WebContents and ipcMain', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
let gotFromIpcMain = false;
let gotFromWebContents = false;
const ipcMainReceived = new Promise<void>(resolve => ipcMain.on('test', () => { gotFromIpcMain = true; resolve(); }));
const ipcWebContentsReceived = new Promise<boolean>(resolve => w.webContents.ipc.on('test', () => { gotFromWebContents = true; resolve(gotFromIpcMain); }));
const ipcReceived = new Promise<boolean>(resolve => w.webContents.mainFrame.ipc.on('test', () => { resolve(gotFromWebContents); }));
defer(() => ipcMain.removeAllListeners('test'));
w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.send(\'test\', 42)');
// assert that they are delivered in the correct order
expect(await ipcReceived).to.be.false();
expect(await ipcWebContentsReceived).to.be.false();
await ipcMainReceived;
});
it('overrides ipcMain handlers', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.mainFrame.ipc.handle('test', (_event, arg) => arg * 2);
ipcMain.handle('test', () => { throw new Error('should not be called'); });
defer(() => ipcMain.removeHandler('test'));
const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
expect(result).to.equal(42 * 2);
});
it('overrides WebContents handlers', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.ipc.handle('test', () => { throw new Error('should not be called'); });
w.webContents.mainFrame.ipc.handle('test', (_event, arg) => arg * 2);
ipcMain.handle('test', () => { throw new Error('should not be called'); });
defer(() => ipcMain.removeHandler('test'));
const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
expect(result).to.equal(42 * 2);
});
it('falls back to WebContents handlers', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
w.webContents.ipc.handle('test', (_event, arg) => { return arg * 2; });
const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
expect(result).to.equal(42 * 2);
});
it('receives ipcs from child frames', async () => {
const server = http.createServer((req, res) => {
res.setHeader('content-type', 'text/html');
res.end('');
});
const { port } = await listen(server);
defer(() => {
server.close();
});
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, preload: path.resolve(fixturesPath, 'preload-expose-ipc.js') } });
// Preloads don't run in about:blank windows, and file:// urls can't be loaded in iframes, so use a blank http page.
await w.loadURL(`data:text/html,<iframe src="http://localhost:${port}"></iframe>`);
w.webContents.mainFrame.frames[0].executeJavaScript('ipc.send(\'test\', 42)');
w.webContents.mainFrame.ipc.on('test', () => { throw new Error('should not be called'); });
const [, arg] = await once(w.webContents.mainFrame.frames[0].ipc, 'test');
expect(arg).to.equal(42);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 39,885 |
[Bug]: Area where traffic lights is rendered does not receive click events when app is fullscreened with titlebar hidden 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
26.1.0
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.5.2
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
N/A
### Expected Behavior
Hi there! Apologies if there is already an opened issue for this, I tried to look in the repo but could not find anything relevant.
As the title suggests, we're currently experiencing an issue in our Mac app, which uses a hidden titlebar and therefore renders the traffic lights inline in our app's header alongside clickable elements such as buttons and popovers, where the leftmost buttons are no longer clickable when the app is maximized.
In debugging this, I realized that those buttons (which we have set up to replace the position of where the traffic lights were in the maximized state) do not receive click events at all (e.g. I can't select them from the Chromium inspector and setting a debugger for `onclick` events in the DOM yields nothing when I click that region.
Other relevant information here is that our header which renders these buttons has `-webkit-app-region: drag` set (so it does not receive DOM click events as expected) but each individual button has `-webkit-app-region: no-drag` set to allow them to be clickable and otherwise work just fine when the app is not maximized and the buttons have not been rendered where the traffic lights were in the un-maximized state.
### Actual Behavior
As described above, the relevant two leftmost buttons in our draggable header (which have `no-drag` set) are clickable when rendered next to the traffic lights while the app is not maximized but no longer receive click events when they replace the traffic lights at the edge of the window when it is maximized.
See demo gif below:

### Testcase Gist URL
https://gist.github.com/sergeichestakov/c84835f4d80182744b99e837268edc7c
### Additional Information
Worth noting that we can only reproduce this so far in macOS Ventura (on an M1 Mac). We also tried macOS Big Sur (on an x86 Mac) but this bug does not reproduce there.
Also relevant, we initialize the BrowserWindow with the following options:
```typescript
const window = new BrowserWindow({
webPreferences: {
preload,
additionalArguments: [
`--app-version=${app.getVersion()}`,
`--platform=${process.platform}`,
],
webviewTag: true,
},
title,
icon,
minWidth: 720,
minHeight: 480,
backgroundColor,
autoHideMenuBar: true,
// on macOS:
titleBarStyle: 'hidden',
titleBarOverlay: { height: 48 },
trafficLightPosition: { x: 20, y: 16 },
});
```
|
https://github.com/electron/electron/issues/39885
|
https://github.com/electron/electron/pull/40179
|
c9f6f15df63e80fa12afe5fb981d17faa1f9772e
|
f362e089b16252cb65bfb7fb44ee5ae88c1e4fcc
| 2023-09-15T19:42:11Z |
c++
| 2023-10-16T09:18:31Z |
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 "include/core/SkColor.h"
#include "shell/browser/background_throttling_source.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/compositor/compositor.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_);
#if BUILDFLAG(IS_WIN)
options.Get(options::kBackgroundMaterial, &background_material_);
#elif BUILDFLAG(IS_MAC)
options.Get(options::kVibrancyType, &vibrancy_);
#endif
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;
auto titlebar_overlay_dict =
gin_helper::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, ¢er) && 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 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
}
options.Get(options::kFullScreenable, &fullscreenable);
SetFullScreenable(fullscreenable);
if (fullscreen)
SetFullScreen(true);
bool resizable;
if (options.Get(options::kResizable, &resizable)) {
SetResizable(resizable);
}
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
SkColor background_color = SK_ColorWHITE;
if (std::string color; options.Get(options::kBackgroundColor, &color)) {
background_color = ParseCSSColor(color);
} else if (IsTranslucent()) {
background_color = SK_ColorTRANSPARENT;
}
SetBackgroundColor(background_color);
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();
}
// Windows/Linux:
// 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.
//
// macOS:
// The min/max sizes are set directly by calling NSWindow's methods.
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
}
absl::optional<std::string> NativeWindow::GetTabbingIdentifier() const {
return ""; // for non-Mac platforms
}
void NativeWindow::SetVibrancy(const std::string& type) {
vibrancy_ = type;
}
void NativeWindow::SetBackgroundMaterial(const std::string& type) {
background_material_ = 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; });
}
void NativeWindow::AddBackgroundThrottlingSource(
BackgroundThrottlingSource* source) {
auto result = background_throttling_sources_.insert(source);
DCHECK(result.second) << "Added already stored BackgroundThrottlingSource.";
UpdateBackgroundThrottlingState();
}
void NativeWindow::RemoveBackgroundThrottlingSource(
BackgroundThrottlingSource* source) {
auto result = background_throttling_sources_.erase(source);
DCHECK(result == 1)
<< "Tried to remove non existing BackgroundThrottlingSource.";
UpdateBackgroundThrottlingState();
}
void NativeWindow::UpdateBackgroundThrottlingState() {
if (!GetWidget() || !GetWidget()->GetCompositor()) {
return;
}
bool enable_background_throttling = true;
for (const auto* background_throttling_source :
background_throttling_sources_) {
if (!background_throttling_source->GetBackgroundThrottling()) {
enable_background_throttling = false;
break;
}
}
GetWidget()->GetCompositor()->SetBackgroundThrottling(
enable_background_throttling);
}
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;
bool NativeWindow::IsTranslucent() const {
// Transparent windows are translucent
if (transparent()) {
return true;
}
#if BUILDFLAG(IS_MAC)
// Windows with vibrancy set are translucent
if (!vibrancy().empty()) {
return true;
}
#endif
#if BUILDFLAG(IS_WIN)
// Windows with certain background materials may be translucent
const std::string& bg_material = background_material();
if (!bg_material.empty() && bg_material != "none") {
return true;
}
#endif
return false;
}
// 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,885 |
[Bug]: Area where traffic lights is rendered does not receive click events when app is fullscreened with titlebar hidden 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
26.1.0
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.5.2
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
N/A
### Expected Behavior
Hi there! Apologies if there is already an opened issue for this, I tried to look in the repo but could not find anything relevant.
As the title suggests, we're currently experiencing an issue in our Mac app, which uses a hidden titlebar and therefore renders the traffic lights inline in our app's header alongside clickable elements such as buttons and popovers, where the leftmost buttons are no longer clickable when the app is maximized.
In debugging this, I realized that those buttons (which we have set up to replace the position of where the traffic lights were in the maximized state) do not receive click events at all (e.g. I can't select them from the Chromium inspector and setting a debugger for `onclick` events in the DOM yields nothing when I click that region.
Other relevant information here is that our header which renders these buttons has `-webkit-app-region: drag` set (so it does not receive DOM click events as expected) but each individual button has `-webkit-app-region: no-drag` set to allow them to be clickable and otherwise work just fine when the app is not maximized and the buttons have not been rendered where the traffic lights were in the un-maximized state.
### Actual Behavior
As described above, the relevant two leftmost buttons in our draggable header (which have `no-drag` set) are clickable when rendered next to the traffic lights while the app is not maximized but no longer receive click events when they replace the traffic lights at the edge of the window when it is maximized.
See demo gif below:

### Testcase Gist URL
https://gist.github.com/sergeichestakov/c84835f4d80182744b99e837268edc7c
### Additional Information
Worth noting that we can only reproduce this so far in macOS Ventura (on an M1 Mac). We also tried macOS Big Sur (on an x86 Mac) but this bug does not reproduce there.
Also relevant, we initialize the BrowserWindow with the following options:
```typescript
const window = new BrowserWindow({
webPreferences: {
preload,
additionalArguments: [
`--app-version=${app.getVersion()}`,
`--platform=${process.platform}`,
],
webviewTag: true,
},
title,
icon,
minWidth: 720,
minHeight: 480,
backgroundColor,
autoHideMenuBar: true,
// on macOS:
titleBarStyle: 'hidden',
titleBarOverlay: { height: 48 },
trafficLightPosition: { x: 20, y: 16 },
});
```
|
https://github.com/electron/electron/issues/39885
|
https://github.com/electron/electron/pull/40179
|
c9f6f15df63e80fa12afe5fb981d17faa1f9772e
|
f362e089b16252cb65bfb7fb44ee5ae88c1e4fcc
| 2023-09-15T19:42:11Z |
c++
| 2023-10-16T09:18:31Z |
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 BackgroundThrottlingSource;
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 RemoveChildFromParentWindow() = 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
const std::string& vibrancy() const { return vibrancy_; }
virtual void SetVibrancy(const std::string& type);
const std::string& background_material() const {
return background_material_;
}
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);
virtual absl::optional<std::string> GetTabbingIdentifier() const;
// 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);
bool IsTranslucent() const;
// Adds |source| to |background_throttling_sources_|, triggers update of
// background throttling state.
void AddBackgroundThrottlingSource(BackgroundThrottlingSource* source);
// Removes |source| to |background_throttling_sources_|, triggers update of
// background throttling state.
void RemoveBackgroundThrottlingSource(BackgroundThrottlingSource* source);
// Updates `ui::Compositor` background throttling state based on
// |background_throttling_sources_|. If at least one of the sources disables
// throttling, then throttling in the `ui::Compositor` will be disabled.
void UpdateBackgroundThrottlingState();
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_;
std::set<BackgroundThrottlingSource*> background_throttling_sources_;
// Accessible title.
std::u16string accessible_title_;
std::string vibrancy_;
std::string background_material_;
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
| 39,885 |
[Bug]: Area where traffic lights is rendered does not receive click events when app is fullscreened with titlebar hidden 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
26.1.0
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.5.2
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
N/A
### Expected Behavior
Hi there! Apologies if there is already an opened issue for this, I tried to look in the repo but could not find anything relevant.
As the title suggests, we're currently experiencing an issue in our Mac app, which uses a hidden titlebar and therefore renders the traffic lights inline in our app's header alongside clickable elements such as buttons and popovers, where the leftmost buttons are no longer clickable when the app is maximized.
In debugging this, I realized that those buttons (which we have set up to replace the position of where the traffic lights were in the maximized state) do not receive click events at all (e.g. I can't select them from the Chromium inspector and setting a debugger for `onclick` events in the DOM yields nothing when I click that region.
Other relevant information here is that our header which renders these buttons has `-webkit-app-region: drag` set (so it does not receive DOM click events as expected) but each individual button has `-webkit-app-region: no-drag` set to allow them to be clickable and otherwise work just fine when the app is not maximized and the buttons have not been rendered where the traffic lights were in the un-maximized state.
### Actual Behavior
As described above, the relevant two leftmost buttons in our draggable header (which have `no-drag` set) are clickable when rendered next to the traffic lights while the app is not maximized but no longer receive click events when they replace the traffic lights at the edge of the window when it is maximized.
See demo gif below:

### Testcase Gist URL
https://gist.github.com/sergeichestakov/c84835f4d80182744b99e837268edc7c
### Additional Information
Worth noting that we can only reproduce this so far in macOS Ventura (on an M1 Mac). We also tried macOS Big Sur (on an x86 Mac) but this bug does not reproduce there.
Also relevant, we initialize the BrowserWindow with the following options:
```typescript
const window = new BrowserWindow({
webPreferences: {
preload,
additionalArguments: [
`--app-version=${app.getVersion()}`,
`--platform=${process.platform}`,
],
webviewTag: true,
},
title,
icon,
minWidth: 720,
minHeight: 480,
backgroundColor,
autoHideMenuBar: true,
// on macOS:
titleBarStyle: 'hidden',
titleBarOverlay: { height: 48 },
trafficLightPosition: { x: 20, y: 16 },
});
```
|
https://github.com/electron/electron/issues/39885
|
https://github.com/electron/electron/pull/40179
|
c9f6f15df63e80fa12afe5fb981d17faa1f9772e
|
f362e089b16252cb65bfb7fb44ee5ae88c1e4fcc
| 2023-09-15T19:42:11Z |
c++
| 2023-10-16T09:18:31Z |
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 SetSizeConstraints(
const extensions::SizeConstraints& window_constraints) 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;
absl::optional<std::string> GetTabbingIdentifier() const 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() override;
// 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;
}
void set_wants_to_be_visible(bool visible) { wants_to_be_visible_ = visible; }
bool wants_to_be_visible() const { return wants_to_be_visible_; }
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;
// If true, the window is either visible, or wants to be visible but is
// currently hidden due to having a hidden parent.
bool wants_to_be_visible_ = 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
| 39,885 |
[Bug]: Area where traffic lights is rendered does not receive click events when app is fullscreened with titlebar hidden 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
26.1.0
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.5.2
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
N/A
### Expected Behavior
Hi there! Apologies if there is already an opened issue for this, I tried to look in the repo but could not find anything relevant.
As the title suggests, we're currently experiencing an issue in our Mac app, which uses a hidden titlebar and therefore renders the traffic lights inline in our app's header alongside clickable elements such as buttons and popovers, where the leftmost buttons are no longer clickable when the app is maximized.
In debugging this, I realized that those buttons (which we have set up to replace the position of where the traffic lights were in the maximized state) do not receive click events at all (e.g. I can't select them from the Chromium inspector and setting a debugger for `onclick` events in the DOM yields nothing when I click that region.
Other relevant information here is that our header which renders these buttons has `-webkit-app-region: drag` set (so it does not receive DOM click events as expected) but each individual button has `-webkit-app-region: no-drag` set to allow them to be clickable and otherwise work just fine when the app is not maximized and the buttons have not been rendered where the traffic lights were in the un-maximized state.
### Actual Behavior
As described above, the relevant two leftmost buttons in our draggable header (which have `no-drag` set) are clickable when rendered next to the traffic lights while the app is not maximized but no longer receive click events when they replace the traffic lights at the edge of the window when it is maximized.
See demo gif below:

### Testcase Gist URL
https://gist.github.com/sergeichestakov/c84835f4d80182744b99e837268edc7c
### Additional Information
Worth noting that we can only reproduce this so far in macOS Ventura (on an M1 Mac). We also tried macOS Big Sur (on an x86 Mac) but this bug does not reproduce there.
Also relevant, we initialize the BrowserWindow with the following options:
```typescript
const window = new BrowserWindow({
webPreferences: {
preload,
additionalArguments: [
`--app-version=${app.getVersion()}`,
`--platform=${process.platform}`,
],
webviewTag: true,
},
title,
icon,
minWidth: 720,
minHeight: 480,
backgroundColor,
autoHideMenuBar: true,
// on macOS:
titleBarStyle: 'hidden',
titleBarOverlay: { height: 48 },
trafficLightPosition: { x: 20, y: 16 },
});
```
|
https://github.com/electron/electron/issues/39885
|
https://github.com/electron/electron/pull/40179
|
c9f6f15df63e80fa12afe5fb981d17faa1f9772e
|
f362e089b16252cb65bfb7fb44ee5ae88c1e4fcc
| 2023-09-15T19:42:11Z |
c++
| 2023-10-16T09:18:31Z |
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/apple/scoped_cftyperef.h"
#include "base/mac/mac_util.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 "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]];
}
// -[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];
}
}
}
NSView* GetNativeNSView(NativeBrowserView* view) {
if (auto* inspectable = view->GetInspectableWebContentsView()) {
return inspectable->GetNativeView().GetNativeNSView();
} else {
return nullptr;
}
}
} // 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_);
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();
while (!child_windows_.empty()) {
auto* child = child_windows_.back();
child->RemoveChildFromParentWindow();
}
// 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() {
// Ensure we're detached from the parent window before closing.
RemoveChildFromParentWindow();
while (!child_windows_.empty()) {
auto* child = child_windows_.back();
child->RemoveChildFromParentWindow();
}
[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;
}
set_wants_to_be_visible(true);
// 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;
}
// If the window wants to be visible and has a parent, then the parent may
// order it back in (in the period between orderOut: and close).
set_wants_to_be_visible(false);
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() {
if (parent() && !is_modal()) {
parent()->RemoveChildWindow(this);
NativeWindow::SetParentWindow(nullptr);
}
}
void NativeWindowMac::AttachChildren() {
for (auto* child : child_windows_) {
if (!static_cast<NativeWindowMac*>(child)->wants_to_be_visible())
continue;
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() {
// 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) {
// [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;
if (![window_ toggleFullScreenMode:nil])
fullscreen_transition_state_ = FullScreenTransitionState::kNone;
}
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::SetSizeConstraints(
const extensions::SizeConstraints& window_constraints) {
// Apply the size constraints to NSWindow.
if (window_constraints.HasMinimumSize())
[window_ setMinSize:window_constraints.GetMinimumSize().ToCGSize()];
if (window_constraints.HasMaximumSize())
[window_ setMaxSize:window_constraints.GetMaximumSize().ToCGSize()];
NativeWindow::SetSizeConstraints(window_constraints);
}
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());
}
};
// Apply the size constraints to NSWindow.
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() || is_modal()) {
[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() || is_modal()) {
[window_ orderWindow:NSWindowAbove relativeTo:0];
} else {
ReorderChildWindowAbove(window_, nullptr);
}
}
void NativeWindowMac::SetResizable(bool resizable) {
ScopedDisableResize disable_resize;
SetStyleMask(resizable, NSWindowStyleMaskResizable);
bool was_fullscreenable = IsFullScreenable();
// Right now, resizable and fullscreenable are decoupled in
// documentation and on Windows/Linux. Chromium disables
// fullscreen collection behavior as well as the maximize traffic
// light in SetCanResize if resizability is false on macOS unless
// the window is both resizable and maximizable. We want consistent
// cross-platform behavior, so if resizability is disabled we disable
// the maximize button and ensure fullscreenability matches user setting.
SetCanResize(resizable);
SetFullScreenable(was_fullscreenable);
[[window_ standardWindowButton:NSWindowZoomButton]
setEnabled:resizable ? was_fullscreenable : false];
}
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::apple::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 (auto* native_view = GetNativeNSView(view)) {
[[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 (auto* native_view = GetNativeNSView(view)) {
[native_view 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 (auto* native_view = GetNativeNSView(view)) {
[[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);
const int macos_version = base::mac::MacOSMajorVersion();
// Modal window corners are rounded on macOS >= 11 or higher if the user
// hasn't passed noRoundedCorners.
bool should_round_modal =
!no_rounded_corner && (macos_version >= 11 ? true : !is_modal());
// Nonmodal window corners are rounded if they're frameless and the user
// hasn't passed noRoundedCorners.
bool should_round_nonmodal = !no_rounded_corner && !has_frame();
if (should_round_nonmodal || should_round_modal) {
CGFloat radius;
if (fullscreen) {
radius = 0.0f;
} else if (macos_version >= 11) {
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) {
NativeWindow::SetVibrancy(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;
}
absl::optional<std::string> NativeWindowMac::GetTabbingIdentifier() const {
if ([window_ tabbingMode] == NSWindowTabbingModeDisallowed)
return absl::nullopt;
return base::SysNSStringToUTF8([window_ tabbingIdentifier]);
}
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];
if (transparent() || !has_frame())
[window_ setTitlebarAppearsTransparent:NO];
}
void NativeWindowMac::NotifyWindowLeaveFullScreen() {
NativeWindow::NotifyWindowLeaveFullScreen();
// Restore window buttons.
if (buttons_proxy_ && window_button_visibility_.value_or(true)) {
[buttons_proxy_ redraw];
[buttons_proxy_ setVisible:YES];
}
if (transparent() || !has_frame())
[window_ setTitlebarAppearsTransparent: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();
// Set new parent window.
if (new_parent) {
new_parent->add_child_window(this);
if (attach)
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,885 |
[Bug]: Area where traffic lights is rendered does not receive click events when app is fullscreened with titlebar hidden 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
26.1.0
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.5.2
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
N/A
### Expected Behavior
Hi there! Apologies if there is already an opened issue for this, I tried to look in the repo but could not find anything relevant.
As the title suggests, we're currently experiencing an issue in our Mac app, which uses a hidden titlebar and therefore renders the traffic lights inline in our app's header alongside clickable elements such as buttons and popovers, where the leftmost buttons are no longer clickable when the app is maximized.
In debugging this, I realized that those buttons (which we have set up to replace the position of where the traffic lights were in the maximized state) do not receive click events at all (e.g. I can't select them from the Chromium inspector and setting a debugger for `onclick` events in the DOM yields nothing when I click that region.
Other relevant information here is that our header which renders these buttons has `-webkit-app-region: drag` set (so it does not receive DOM click events as expected) but each individual button has `-webkit-app-region: no-drag` set to allow them to be clickable and otherwise work just fine when the app is not maximized and the buttons have not been rendered where the traffic lights were in the un-maximized state.
### Actual Behavior
As described above, the relevant two leftmost buttons in our draggable header (which have `no-drag` set) are clickable when rendered next to the traffic lights while the app is not maximized but no longer receive click events when they replace the traffic lights at the edge of the window when it is maximized.
See demo gif below:

### Testcase Gist URL
https://gist.github.com/sergeichestakov/c84835f4d80182744b99e837268edc7c
### Additional Information
Worth noting that we can only reproduce this so far in macOS Ventura (on an M1 Mac). We also tried macOS Big Sur (on an x86 Mac) but this bug does not reproduce there.
Also relevant, we initialize the BrowserWindow with the following options:
```typescript
const window = new BrowserWindow({
webPreferences: {
preload,
additionalArguments: [
`--app-version=${app.getVersion()}`,
`--platform=${process.platform}`,
],
webviewTag: true,
},
title,
icon,
minWidth: 720,
minHeight: 480,
backgroundColor,
autoHideMenuBar: true,
// on macOS:
titleBarStyle: 'hidden',
titleBarOverlay: { height: 48 },
trafficLightPosition: { x: 20, y: 16 },
});
```
|
https://github.com/electron/electron/issues/39885
|
https://github.com/electron/electron/pull/40179
|
c9f6f15df63e80fa12afe5fb981d17faa1f9772e
|
f362e089b16252cb65bfb7fb44ee5ae88c1e4fcc
| 2023-09-15T19:42:11Z |
c++
| 2023-10-16T09:18:31Z |
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 "include/core/SkColor.h"
#include "shell/browser/background_throttling_source.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/compositor/compositor.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_);
#if BUILDFLAG(IS_WIN)
options.Get(options::kBackgroundMaterial, &background_material_);
#elif BUILDFLAG(IS_MAC)
options.Get(options::kVibrancyType, &vibrancy_);
#endif
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;
auto titlebar_overlay_dict =
gin_helper::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, ¢er) && 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 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
}
options.Get(options::kFullScreenable, &fullscreenable);
SetFullScreenable(fullscreenable);
if (fullscreen)
SetFullScreen(true);
bool resizable;
if (options.Get(options::kResizable, &resizable)) {
SetResizable(resizable);
}
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
SkColor background_color = SK_ColorWHITE;
if (std::string color; options.Get(options::kBackgroundColor, &color)) {
background_color = ParseCSSColor(color);
} else if (IsTranslucent()) {
background_color = SK_ColorTRANSPARENT;
}
SetBackgroundColor(background_color);
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();
}
// Windows/Linux:
// 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.
//
// macOS:
// The min/max sizes are set directly by calling NSWindow's methods.
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
}
absl::optional<std::string> NativeWindow::GetTabbingIdentifier() const {
return ""; // for non-Mac platforms
}
void NativeWindow::SetVibrancy(const std::string& type) {
vibrancy_ = type;
}
void NativeWindow::SetBackgroundMaterial(const std::string& type) {
background_material_ = 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; });
}
void NativeWindow::AddBackgroundThrottlingSource(
BackgroundThrottlingSource* source) {
auto result = background_throttling_sources_.insert(source);
DCHECK(result.second) << "Added already stored BackgroundThrottlingSource.";
UpdateBackgroundThrottlingState();
}
void NativeWindow::RemoveBackgroundThrottlingSource(
BackgroundThrottlingSource* source) {
auto result = background_throttling_sources_.erase(source);
DCHECK(result == 1)
<< "Tried to remove non existing BackgroundThrottlingSource.";
UpdateBackgroundThrottlingState();
}
void NativeWindow::UpdateBackgroundThrottlingState() {
if (!GetWidget() || !GetWidget()->GetCompositor()) {
return;
}
bool enable_background_throttling = true;
for (const auto* background_throttling_source :
background_throttling_sources_) {
if (!background_throttling_source->GetBackgroundThrottling()) {
enable_background_throttling = false;
break;
}
}
GetWidget()->GetCompositor()->SetBackgroundThrottling(
enable_background_throttling);
}
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;
bool NativeWindow::IsTranslucent() const {
// Transparent windows are translucent
if (transparent()) {
return true;
}
#if BUILDFLAG(IS_MAC)
// Windows with vibrancy set are translucent
if (!vibrancy().empty()) {
return true;
}
#endif
#if BUILDFLAG(IS_WIN)
// Windows with certain background materials may be translucent
const std::string& bg_material = background_material();
if (!bg_material.empty() && bg_material != "none") {
return true;
}
#endif
return false;
}
// 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,885 |
[Bug]: Area where traffic lights is rendered does not receive click events when app is fullscreened with titlebar hidden 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
26.1.0
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.5.2
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
N/A
### Expected Behavior
Hi there! Apologies if there is already an opened issue for this, I tried to look in the repo but could not find anything relevant.
As the title suggests, we're currently experiencing an issue in our Mac app, which uses a hidden titlebar and therefore renders the traffic lights inline in our app's header alongside clickable elements such as buttons and popovers, where the leftmost buttons are no longer clickable when the app is maximized.
In debugging this, I realized that those buttons (which we have set up to replace the position of where the traffic lights were in the maximized state) do not receive click events at all (e.g. I can't select them from the Chromium inspector and setting a debugger for `onclick` events in the DOM yields nothing when I click that region.
Other relevant information here is that our header which renders these buttons has `-webkit-app-region: drag` set (so it does not receive DOM click events as expected) but each individual button has `-webkit-app-region: no-drag` set to allow them to be clickable and otherwise work just fine when the app is not maximized and the buttons have not been rendered where the traffic lights were in the un-maximized state.
### Actual Behavior
As described above, the relevant two leftmost buttons in our draggable header (which have `no-drag` set) are clickable when rendered next to the traffic lights while the app is not maximized but no longer receive click events when they replace the traffic lights at the edge of the window when it is maximized.
See demo gif below:

### Testcase Gist URL
https://gist.github.com/sergeichestakov/c84835f4d80182744b99e837268edc7c
### Additional Information
Worth noting that we can only reproduce this so far in macOS Ventura (on an M1 Mac). We also tried macOS Big Sur (on an x86 Mac) but this bug does not reproduce there.
Also relevant, we initialize the BrowserWindow with the following options:
```typescript
const window = new BrowserWindow({
webPreferences: {
preload,
additionalArguments: [
`--app-version=${app.getVersion()}`,
`--platform=${process.platform}`,
],
webviewTag: true,
},
title,
icon,
minWidth: 720,
minHeight: 480,
backgroundColor,
autoHideMenuBar: true,
// on macOS:
titleBarStyle: 'hidden',
titleBarOverlay: { height: 48 },
trafficLightPosition: { x: 20, y: 16 },
});
```
|
https://github.com/electron/electron/issues/39885
|
https://github.com/electron/electron/pull/40179
|
c9f6f15df63e80fa12afe5fb981d17faa1f9772e
|
f362e089b16252cb65bfb7fb44ee5ae88c1e4fcc
| 2023-09-15T19:42:11Z |
c++
| 2023-10-16T09:18:31Z |
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 BackgroundThrottlingSource;
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 RemoveChildFromParentWindow() = 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
const std::string& vibrancy() const { return vibrancy_; }
virtual void SetVibrancy(const std::string& type);
const std::string& background_material() const {
return background_material_;
}
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);
virtual absl::optional<std::string> GetTabbingIdentifier() const;
// 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);
bool IsTranslucent() const;
// Adds |source| to |background_throttling_sources_|, triggers update of
// background throttling state.
void AddBackgroundThrottlingSource(BackgroundThrottlingSource* source);
// Removes |source| to |background_throttling_sources_|, triggers update of
// background throttling state.
void RemoveBackgroundThrottlingSource(BackgroundThrottlingSource* source);
// Updates `ui::Compositor` background throttling state based on
// |background_throttling_sources_|. If at least one of the sources disables
// throttling, then throttling in the `ui::Compositor` will be disabled.
void UpdateBackgroundThrottlingState();
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_;
std::set<BackgroundThrottlingSource*> background_throttling_sources_;
// Accessible title.
std::u16string accessible_title_;
std::string vibrancy_;
std::string background_material_;
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
| 39,885 |
[Bug]: Area where traffic lights is rendered does not receive click events when app is fullscreened with titlebar hidden 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
26.1.0
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.5.2
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
N/A
### Expected Behavior
Hi there! Apologies if there is already an opened issue for this, I tried to look in the repo but could not find anything relevant.
As the title suggests, we're currently experiencing an issue in our Mac app, which uses a hidden titlebar and therefore renders the traffic lights inline in our app's header alongside clickable elements such as buttons and popovers, where the leftmost buttons are no longer clickable when the app is maximized.
In debugging this, I realized that those buttons (which we have set up to replace the position of where the traffic lights were in the maximized state) do not receive click events at all (e.g. I can't select them from the Chromium inspector and setting a debugger for `onclick` events in the DOM yields nothing when I click that region.
Other relevant information here is that our header which renders these buttons has `-webkit-app-region: drag` set (so it does not receive DOM click events as expected) but each individual button has `-webkit-app-region: no-drag` set to allow them to be clickable and otherwise work just fine when the app is not maximized and the buttons have not been rendered where the traffic lights were in the un-maximized state.
### Actual Behavior
As described above, the relevant two leftmost buttons in our draggable header (which have `no-drag` set) are clickable when rendered next to the traffic lights while the app is not maximized but no longer receive click events when they replace the traffic lights at the edge of the window when it is maximized.
See demo gif below:

### Testcase Gist URL
https://gist.github.com/sergeichestakov/c84835f4d80182744b99e837268edc7c
### Additional Information
Worth noting that we can only reproduce this so far in macOS Ventura (on an M1 Mac). We also tried macOS Big Sur (on an x86 Mac) but this bug does not reproduce there.
Also relevant, we initialize the BrowserWindow with the following options:
```typescript
const window = new BrowserWindow({
webPreferences: {
preload,
additionalArguments: [
`--app-version=${app.getVersion()}`,
`--platform=${process.platform}`,
],
webviewTag: true,
},
title,
icon,
minWidth: 720,
minHeight: 480,
backgroundColor,
autoHideMenuBar: true,
// on macOS:
titleBarStyle: 'hidden',
titleBarOverlay: { height: 48 },
trafficLightPosition: { x: 20, y: 16 },
});
```
|
https://github.com/electron/electron/issues/39885
|
https://github.com/electron/electron/pull/40179
|
c9f6f15df63e80fa12afe5fb981d17faa1f9772e
|
f362e089b16252cb65bfb7fb44ee5ae88c1e4fcc
| 2023-09-15T19:42:11Z |
c++
| 2023-10-16T09:18:31Z |
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 SetSizeConstraints(
const extensions::SizeConstraints& window_constraints) 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;
absl::optional<std::string> GetTabbingIdentifier() const 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() override;
// 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;
}
void set_wants_to_be_visible(bool visible) { wants_to_be_visible_ = visible; }
bool wants_to_be_visible() const { return wants_to_be_visible_; }
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;
// If true, the window is either visible, or wants to be visible but is
// currently hidden due to having a hidden parent.
bool wants_to_be_visible_ = 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
| 39,885 |
[Bug]: Area where traffic lights is rendered does not receive click events when app is fullscreened with titlebar hidden 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
26.1.0
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.5.2
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
N/A
### Expected Behavior
Hi there! Apologies if there is already an opened issue for this, I tried to look in the repo but could not find anything relevant.
As the title suggests, we're currently experiencing an issue in our Mac app, which uses a hidden titlebar and therefore renders the traffic lights inline in our app's header alongside clickable elements such as buttons and popovers, where the leftmost buttons are no longer clickable when the app is maximized.
In debugging this, I realized that those buttons (which we have set up to replace the position of where the traffic lights were in the maximized state) do not receive click events at all (e.g. I can't select them from the Chromium inspector and setting a debugger for `onclick` events in the DOM yields nothing when I click that region.
Other relevant information here is that our header which renders these buttons has `-webkit-app-region: drag` set (so it does not receive DOM click events as expected) but each individual button has `-webkit-app-region: no-drag` set to allow them to be clickable and otherwise work just fine when the app is not maximized and the buttons have not been rendered where the traffic lights were in the un-maximized state.
### Actual Behavior
As described above, the relevant two leftmost buttons in our draggable header (which have `no-drag` set) are clickable when rendered next to the traffic lights while the app is not maximized but no longer receive click events when they replace the traffic lights at the edge of the window when it is maximized.
See demo gif below:

### Testcase Gist URL
https://gist.github.com/sergeichestakov/c84835f4d80182744b99e837268edc7c
### Additional Information
Worth noting that we can only reproduce this so far in macOS Ventura (on an M1 Mac). We also tried macOS Big Sur (on an x86 Mac) but this bug does not reproduce there.
Also relevant, we initialize the BrowserWindow with the following options:
```typescript
const window = new BrowserWindow({
webPreferences: {
preload,
additionalArguments: [
`--app-version=${app.getVersion()}`,
`--platform=${process.platform}`,
],
webviewTag: true,
},
title,
icon,
minWidth: 720,
minHeight: 480,
backgroundColor,
autoHideMenuBar: true,
// on macOS:
titleBarStyle: 'hidden',
titleBarOverlay: { height: 48 },
trafficLightPosition: { x: 20, y: 16 },
});
```
|
https://github.com/electron/electron/issues/39885
|
https://github.com/electron/electron/pull/40179
|
c9f6f15df63e80fa12afe5fb981d17faa1f9772e
|
f362e089b16252cb65bfb7fb44ee5ae88c1e4fcc
| 2023-09-15T19:42:11Z |
c++
| 2023-10-16T09:18:31Z |
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/apple/scoped_cftyperef.h"
#include "base/mac/mac_util.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 "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]];
}
// -[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];
}
}
}
NSView* GetNativeNSView(NativeBrowserView* view) {
if (auto* inspectable = view->GetInspectableWebContentsView()) {
return inspectable->GetNativeView().GetNativeNSView();
} else {
return nullptr;
}
}
} // 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_);
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();
while (!child_windows_.empty()) {
auto* child = child_windows_.back();
child->RemoveChildFromParentWindow();
}
// 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() {
// Ensure we're detached from the parent window before closing.
RemoveChildFromParentWindow();
while (!child_windows_.empty()) {
auto* child = child_windows_.back();
child->RemoveChildFromParentWindow();
}
[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;
}
set_wants_to_be_visible(true);
// 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;
}
// If the window wants to be visible and has a parent, then the parent may
// order it back in (in the period between orderOut: and close).
set_wants_to_be_visible(false);
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() {
if (parent() && !is_modal()) {
parent()->RemoveChildWindow(this);
NativeWindow::SetParentWindow(nullptr);
}
}
void NativeWindowMac::AttachChildren() {
for (auto* child : child_windows_) {
if (!static_cast<NativeWindowMac*>(child)->wants_to_be_visible())
continue;
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() {
// 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) {
// [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;
if (![window_ toggleFullScreenMode:nil])
fullscreen_transition_state_ = FullScreenTransitionState::kNone;
}
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::SetSizeConstraints(
const extensions::SizeConstraints& window_constraints) {
// Apply the size constraints to NSWindow.
if (window_constraints.HasMinimumSize())
[window_ setMinSize:window_constraints.GetMinimumSize().ToCGSize()];
if (window_constraints.HasMaximumSize())
[window_ setMaxSize:window_constraints.GetMaximumSize().ToCGSize()];
NativeWindow::SetSizeConstraints(window_constraints);
}
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());
}
};
// Apply the size constraints to NSWindow.
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() || is_modal()) {
[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() || is_modal()) {
[window_ orderWindow:NSWindowAbove relativeTo:0];
} else {
ReorderChildWindowAbove(window_, nullptr);
}
}
void NativeWindowMac::SetResizable(bool resizable) {
ScopedDisableResize disable_resize;
SetStyleMask(resizable, NSWindowStyleMaskResizable);
bool was_fullscreenable = IsFullScreenable();
// Right now, resizable and fullscreenable are decoupled in
// documentation and on Windows/Linux. Chromium disables
// fullscreen collection behavior as well as the maximize traffic
// light in SetCanResize if resizability is false on macOS unless
// the window is both resizable and maximizable. We want consistent
// cross-platform behavior, so if resizability is disabled we disable
// the maximize button and ensure fullscreenability matches user setting.
SetCanResize(resizable);
SetFullScreenable(was_fullscreenable);
[[window_ standardWindowButton:NSWindowZoomButton]
setEnabled:resizable ? was_fullscreenable : false];
}
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::apple::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 (auto* native_view = GetNativeNSView(view)) {
[[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 (auto* native_view = GetNativeNSView(view)) {
[native_view 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 (auto* native_view = GetNativeNSView(view)) {
[[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);
const int macos_version = base::mac::MacOSMajorVersion();
// Modal window corners are rounded on macOS >= 11 or higher if the user
// hasn't passed noRoundedCorners.
bool should_round_modal =
!no_rounded_corner && (macos_version >= 11 ? true : !is_modal());
// Nonmodal window corners are rounded if they're frameless and the user
// hasn't passed noRoundedCorners.
bool should_round_nonmodal = !no_rounded_corner && !has_frame();
if (should_round_nonmodal || should_round_modal) {
CGFloat radius;
if (fullscreen) {
radius = 0.0f;
} else if (macos_version >= 11) {
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) {
NativeWindow::SetVibrancy(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;
}
absl::optional<std::string> NativeWindowMac::GetTabbingIdentifier() const {
if ([window_ tabbingMode] == NSWindowTabbingModeDisallowed)
return absl::nullopt;
return base::SysNSStringToUTF8([window_ tabbingIdentifier]);
}
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];
if (transparent() || !has_frame())
[window_ setTitlebarAppearsTransparent:NO];
}
void NativeWindowMac::NotifyWindowLeaveFullScreen() {
NativeWindow::NotifyWindowLeaveFullScreen();
// Restore window buttons.
if (buttons_proxy_ && window_button_visibility_.value_or(true)) {
[buttons_proxy_ redraw];
[buttons_proxy_ setVisible:YES];
}
if (transparent() || !has_frame())
[window_ setTitlebarAppearsTransparent: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();
// Set new parent window.
if (new_parent) {
new_parent->add_child_window(this);
if (attach)
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
| 37,560 |
[Bug]: Open at login with setLoginItemSettings in MAS build is not working
|
### 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
16.0.6
### What operating system are you using?
macOS
### Operating System Version
Version 13.2 (22D49)
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Setting app to open at login with setLoginItemSettings api should work both locally and with MAS build.
Locally the app is added to login items but when i build it for MAS this doesn't work.
### Actual Behavior
Setting app to open at login with setLoginItemSettings api works locally but doesn't work in MAS build.
In MAS build the app is not added to login items.
<img width="477" alt="image" src="https://user-images.githubusercontent.com/17458685/224576455-a9145dfc-7121-4097-9fe4-a472f0c2ead4.png">
### Testcase Gist URL
_No response_
### Additional Information
According to docs https://www.electronjs.org/docs/latest/api/app#appsetloginitemsettingssettings-macos-windows setting login item in MAS build should work by using the following API
```js
app.setLoginItemSettings({
openAtLogin: openAtLogin,
})
```
In the docs on limitations of MAS build there is no mention of any limitation of using above API https://www.electronjs.org/docs/latest/tutorial/mac-app-store-submission-guide#limitations-of-mas-build
Here is possible related issue and PRs:
- https://github.com/electron/electron/issues/7312
- https://github.com/electron/electron/pull/11144
- https://github.com/electron/electron/pull/10856
|
https://github.com/electron/electron/issues/37560
|
https://github.com/electron/electron/pull/37244
|
6d0d350e138494cd68dd3d4fa73b2719da4575bf
|
f7b1c75c72a8dcab4157408f92bd3771606d8029
| 2023-03-12T22:11:32Z |
c++
| 2023-10-16T16:25:11Z |
docs/api/app.md
|
# app
> Control your application's event lifecycle.
Process: [Main](../glossary.md#main-process)
The following example shows how to quit the application when the last window is
closed:
```js
const { app } = require('electron')
app.on('window-all-closed', () => {
app.quit()
})
```
## Events
The `app` object emits the following events:
### Event: 'will-finish-launching'
Emitted when the application has finished basic startup. On Windows and Linux,
the `will-finish-launching` event is the same as the `ready` event; on macOS,
this event represents the `applicationWillFinishLaunching` notification of
`NSApplication`.
In most cases, you should do everything in the `ready` event handler.
### Event: 'ready'
Returns:
* `event` Event
* `launchInfo` Record<string, any> | [NotificationResponse](structures/notification-response.md) _macOS_
Emitted once, when Electron has finished initializing. On macOS, `launchInfo`
holds the `userInfo` of the [`NSUserNotification`](https://developer.apple.com/documentation/foundation/nsusernotification)
or information from [`UNNotificationResponse`](https://developer.apple.com/documentation/usernotifications/unnotificationresponse)
that was used to open the application, if it was launched from Notification Center.
You can also call `app.isReady()` to check if this event has already fired and `app.whenReady()`
to get a Promise that is fulfilled when Electron is initialized.
### Event: 'window-all-closed'
Emitted when all windows have been closed.
If you do not subscribe to this event and all windows are closed, the default
behavior is to quit the app; however, if you subscribe, you control whether the
app quits or not. If the user pressed `Cmd + Q`, or the developer called
`app.quit()`, Electron will first try to close all the windows and then emit the
`will-quit` event, and in this case the `window-all-closed` event would not be
emitted.
### Event: 'before-quit'
Returns:
* `event` Event
Emitted before the application starts closing its windows.
Calling `event.preventDefault()` will prevent the default behavior, which is
terminating the application.
**Note:** If application quit was initiated by `autoUpdater.quitAndInstall()`,
then `before-quit` is emitted _after_ emitting `close` event on all windows and
closing them.
**Note:** On Windows, this event will not be emitted if the app is closed due
to a shutdown/restart of the system or a user logout.
### Event: 'will-quit'
Returns:
* `event` Event
Emitted when all windows have been closed and the application will quit.
Calling `event.preventDefault()` will prevent the default behavior, which is
terminating the application.
See the description of the `window-all-closed` event for the differences between
the `will-quit` and `window-all-closed` events.
**Note:** On Windows, this event will not be emitted if the app is closed due
to a shutdown/restart of the system or a user logout.
### Event: 'quit'
Returns:
* `event` Event
* `exitCode` Integer
Emitted when the application is quitting.
**Note:** On Windows, this event will not be emitted if the app is closed due
to a shutdown/restart of the system or a user logout.
### Event: 'open-file' _macOS_
Returns:
* `event` Event
* `path` string
Emitted when the user wants to open a file with the application. The `open-file`
event is usually emitted when the application is already open and the OS wants
to reuse the application to open the file. `open-file` is also emitted when a
file is dropped onto the dock and the application is not yet running. Make sure
to listen for the `open-file` event very early in your application startup to
handle this case (even before the `ready` event is emitted).
You should call `event.preventDefault()` if you want to handle this event.
On Windows, you have to parse `process.argv` (in the main process) to get the
filepath.
### Event: 'open-url' _macOS_
Returns:
* `event` Event
* `url` string
Emitted when the user wants to open a URL with the application. Your application's
`Info.plist` file must define the URL scheme within the `CFBundleURLTypes` key, and
set `NSPrincipalClass` to `AtomApplication`.
As with the `open-file` event, be sure to register a listener for the `open-url`
event early in your application startup to detect if the application is being opened to handle a URL.
If you register the listener in response to a `ready` event, you'll miss URLs that trigger the launch of your application.
### Event: 'activate' _macOS_
Returns:
* `event` Event
* `hasVisibleWindows` boolean
Emitted when the application is activated. Various actions can trigger
this event, such as launching the application for the first time, attempting
to re-launch the application when it's already running, or clicking on the
application's dock or taskbar icon.
### Event: 'did-become-active' _macOS_
Returns:
* `event` Event
Emitted when the application becomes active. This differs from the `activate` event in
that `did-become-active` is emitted every time the app becomes active, not only
when Dock icon is clicked or application is re-launched. It is also emitted when a user
switches to the app via the macOS App Switcher.
### Event: 'did-resign-active' _macOS_
Returns:
* `event` Event
Emitted when the app is no longer active and doesnβt have focus. This can be triggered,
for example, by clicking on another application or by using the macOS App Switcher to
switch to another application.
### Event: 'continue-activity' _macOS_
Returns:
* `event` Event
* `type` string - A string identifying the activity. Maps to
[`NSUserActivity.activityType`][activity-type].
* `userInfo` unknown - Contains app-specific state stored by the activity on
another device.
* `details` Object
* `webpageURL` string (optional) - A string identifying the URL of the webpage accessed by the activity on another device, if available.
Emitted during [Handoff][handoff] when an activity from a different device wants
to be resumed. You should call `event.preventDefault()` if you want to handle
this event.
A user activity can be continued only in an app that has the same developer Team
ID as the activity's source app and that supports the activity's type.
Supported activity types are specified in the app's `Info.plist` under the
`NSUserActivityTypes` key.
### Event: 'will-continue-activity' _macOS_
Returns:
* `event` Event
* `type` string - A string identifying the activity. Maps to
[`NSUserActivity.activityType`][activity-type].
Emitted during [Handoff][handoff] before an activity from a different device wants
to be resumed. You should call `event.preventDefault()` if you want to handle
this event.
### Event: 'continue-activity-error' _macOS_
Returns:
* `event` Event
* `type` string - A string identifying the activity. Maps to
[`NSUserActivity.activityType`][activity-type].
* `error` string - A string with the error's localized description.
Emitted during [Handoff][handoff] when an activity from a different device
fails to be resumed.
### Event: 'activity-was-continued' _macOS_
Returns:
* `event` Event
* `type` string - A string identifying the activity. Maps to
[`NSUserActivity.activityType`][activity-type].
* `userInfo` unknown - Contains app-specific state stored by the activity.
Emitted during [Handoff][handoff] after an activity from this device was successfully
resumed on another one.
### Event: 'update-activity-state' _macOS_
Returns:
* `event` Event
* `type` string - A string identifying the activity. Maps to
[`NSUserActivity.activityType`][activity-type].
* `userInfo` unknown - Contains app-specific state stored by the activity.
Emitted when [Handoff][handoff] is about to be resumed on another device. If you need to update the state to be transferred, you should call `event.preventDefault()` immediately, construct a new `userInfo` dictionary and call `app.updateCurrentActivity()` in a timely manner. Otherwise, the operation will fail and `continue-activity-error` will be called.
### Event: 'new-window-for-tab' _macOS_
Returns:
* `event` Event
Emitted when the user clicks the native macOS new tab button. The new
tab button is only visible if the current `BrowserWindow` has a
`tabbingIdentifier`
### Event: 'browser-window-blur'
Returns:
* `event` Event
* `window` [BrowserWindow](browser-window.md)
Emitted when a [browserWindow](browser-window.md) gets blurred.
### Event: 'browser-window-focus'
Returns:
* `event` Event
* `window` [BrowserWindow](browser-window.md)
Emitted when a [browserWindow](browser-window.md) gets focused.
### Event: 'browser-window-created'
Returns:
* `event` Event
* `window` [BrowserWindow](browser-window.md)
Emitted when a new [browserWindow](browser-window.md) is created.
### Event: 'web-contents-created'
Returns:
* `event` Event
* `webContents` [WebContents](web-contents.md)
Emitted when a new [webContents](web-contents.md) is created.
### Event: 'certificate-error'
Returns:
* `event` Event
* `webContents` [WebContents](web-contents.md)
* `url` string
* `error` string - The error code
* `certificate` [Certificate](structures/certificate.md)
* `callback` Function
* `isTrusted` boolean - Whether to consider the certificate as trusted
* `isMainFrame` boolean
Emitted when failed to verify the `certificate` for `url`, to trust the
certificate you should prevent the default behavior with
`event.preventDefault()` and call `callback(true)`.
```js
const { app } = require('electron')
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
if (url === 'https://github.com') {
// Verification logic.
event.preventDefault()
callback(true)
} else {
callback(false)
}
})
```
### Event: 'select-client-certificate'
Returns:
* `event` Event
* `webContents` [WebContents](web-contents.md)
* `url` URL
* `certificateList` [Certificate[]](structures/certificate.md)
* `callback` Function
* `certificate` [Certificate](structures/certificate.md) (optional)
Emitted when a client certificate is requested.
The `url` corresponds to the navigation entry requesting the client certificate
and `callback` can be called with an entry filtered from the list. Using
`event.preventDefault()` prevents the application from using the first
certificate from the store.
```js
const { app } = require('electron')
app.on('select-client-certificate', (event, webContents, url, list, callback) => {
event.preventDefault()
callback(list[0])
})
```
### Event: 'login'
Returns:
* `event` Event
* `webContents` [WebContents](web-contents.md)
* `authenticationResponseDetails` Object
* `url` URL
* `authInfo` Object
* `isProxy` boolean
* `scheme` string
* `host` string
* `port` Integer
* `realm` string
* `callback` Function
* `username` string (optional)
* `password` string (optional)
Emitted when `webContents` wants to do basic auth.
The default behavior is to cancel all authentications. To override this you
should prevent the default behavior with `event.preventDefault()` and call
`callback(username, password)` with the credentials.
```js
const { app } = require('electron')
app.on('login', (event, webContents, details, authInfo, callback) => {
event.preventDefault()
callback('username', 'secret')
})
```
If `callback` is called without a username or password, the authentication
request will be cancelled and the authentication error will be returned to the
page.
### Event: 'gpu-info-update'
Emitted whenever there is a GPU info update.
### Event: 'gpu-process-crashed' _Deprecated_
Returns:
* `event` Event
* `killed` boolean
Emitted when the GPU process crashes or is killed.
**Deprecated:** This event is superceded by the `child-process-gone` event
which contains more information about why the child process disappeared. It
isn't always because it crashed. The `killed` boolean can be replaced by
checking `reason === 'killed'` when you switch to that event.
### Event: 'renderer-process-crashed' _Deprecated_
Returns:
* `event` Event
* `webContents` [WebContents](web-contents.md)
* `killed` boolean
Emitted when the renderer process of `webContents` crashes or is killed.
**Deprecated:** This event is superceded by the `render-process-gone` event
which contains more information about why the render process disappeared. It
isn't always because it crashed. The `killed` boolean can be replaced by
checking `reason === 'killed'` when you switch to that event.
### Event: 'render-process-gone'
Returns:
* `event` Event
* `webContents` [WebContents](web-contents.md)
* `details` [RenderProcessGoneDetails](structures/render-process-gone-details.md)
Emitted when the renderer process unexpectedly disappears. This is normally
because it was crashed or killed.
### Event: 'child-process-gone'
Returns:
* `event` Event
* `details` Object
* `type` string - Process type. One of the following values:
* `Utility`
* `Zygote`
* `Sandbox helper`
* `GPU`
* `Pepper Plugin`
* `Pepper Plugin Broker`
* `Unknown`
* `reason` string - The reason the child process is gone. Possible values:
* `clean-exit` - Process exited with an exit code of zero
* `abnormal-exit` - Process exited with a non-zero exit code
* `killed` - Process was sent a SIGTERM or otherwise killed externally
* `crashed` - Process crashed
* `oom` - Process ran out of memory
* `launch-failed` - Process never successfully launched
* `integrity-failure` - Windows code integrity checks failed
* `exitCode` number - The exit code for the process
(e.g. status from waitpid if on posix, from GetExitCodeProcess on Windows).
* `serviceName` string (optional) - The non-localized name of the process.
* `name` string (optional) - The name of the process.
Examples for utility: `Audio Service`, `Content Decryption Module Service`, `Network Service`, `Video Capture`, etc.
Emitted when the child process unexpectedly disappears. This is normally
because it was crashed or killed. It does not include renderer processes.
### Event: 'accessibility-support-changed' _macOS_ _Windows_
Returns:
* `event` Event
* `accessibilitySupportEnabled` boolean - `true` when Chrome's accessibility
support is enabled, `false` otherwise.
Emitted when Chrome's accessibility support changes. This event fires when
assistive technologies, such as screen readers, are enabled or disabled.
See https://www.chromium.org/developers/design-documents/accessibility for more
details.
### Event: 'session-created'
Returns:
* `session` [Session](session.md)
Emitted when Electron has created a new `session`.
```js
const { app } = require('electron')
app.on('session-created', (session) => {
console.log(session)
})
```
### Event: 'second-instance'
Returns:
* `event` Event
* `argv` string[] - An array of the second instance's command line arguments
* `workingDirectory` string - The second instance's working directory
* `additionalData` unknown - A JSON object of additional data passed from the second instance
This event will be emitted inside the primary instance of your application
when a second instance has been executed and calls `app.requestSingleInstanceLock()`.
`argv` is an Array of the second instance's command line arguments,
and `workingDirectory` is its current working directory. Usually
applications respond to this by making their primary window focused and
non-minimized.
**Note:** `argv` will not be exactly the same list of arguments as those passed
to the second instance. The order might change and additional arguments might be appended.
If you need to maintain the exact same arguments, it's advised to use `additionalData` instead.
**Note:** If the second instance is started by a different user than the first, the `argv` array will not include the arguments.
This event is guaranteed to be emitted after the `ready` event of `app`
gets emitted.
**Note:** Extra command line arguments might be added by Chromium,
such as `--original-process-start-time`.
## Methods
The `app` object has the following methods:
**Note:** Some methods are only available on specific operating systems and are
labeled as such.
### `app.quit()`
Try to close all windows. The `before-quit` event will be emitted first. If all
windows are successfully closed, the `will-quit` event will be emitted and by
default the application will terminate.
This method guarantees that all `beforeunload` and `unload` event handlers are
correctly executed. It is possible that a window cancels the quitting by
returning `false` in the `beforeunload` event handler.
### `app.exit([exitCode])`
* `exitCode` Integer (optional)
Exits immediately with `exitCode`. `exitCode` defaults to 0.
All windows will be closed immediately without asking the user, and the `before-quit`
and `will-quit` events will not be emitted.
### `app.relaunch([options])`
* `options` Object (optional)
* `args` string[] (optional)
* `execPath` string (optional)
Relaunches the app when current instance exits.
By default, the new instance will use the same working directory and command line
arguments with current instance. When `args` is specified, the `args` will be
passed as command line arguments instead. When `execPath` is specified, the
`execPath` will be executed for relaunch instead of current app.
Note that this method does not quit the app when executed, you have to call
`app.quit` or `app.exit` after calling `app.relaunch` to make the app restart.
When `app.relaunch` is called for multiple times, multiple instances will be
started after current instance exited.
An example of restarting current instance immediately and adding a new command
line argument to the new instance:
```js
const { app } = require('electron')
app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) })
app.exit(0)
```
### `app.isReady()`
Returns `boolean` - `true` if Electron has finished initializing, `false` otherwise.
See also `app.whenReady()`.
### `app.whenReady()`
Returns `Promise<void>` - fulfilled when Electron is initialized.
May be used as a convenient alternative to checking `app.isReady()`
and subscribing to the `ready` event if the app is not ready yet.
### `app.focus([options])`
* `options` Object (optional)
* `steal` boolean _macOS_ - Make the receiver the active app even if another app is
currently active.
On Linux, focuses on the first visible window. On macOS, makes the application
the active app. On Windows, focuses on the application's first window.
You should seek to use the `steal` option as sparingly as possible.
### `app.hide()` _macOS_
Hides all application windows without minimizing them.
### `app.isHidden()` _macOS_
Returns `boolean` - `true` if the applicationβincluding all of its windowsβis hidden (e.g. with `Command-H`), `false` otherwise.
### `app.show()` _macOS_
Shows application windows after they were hidden. Does not automatically focus
them.
### `app.setAppLogsPath([path])`
* `path` string (optional) - A custom path for your logs. Must be absolute.
Sets or creates a directory your app's logs which can then be manipulated with `app.getPath()` or `app.setPath(pathName, newPath)`.
Calling `app.setAppLogsPath()` without a `path` parameter will result in this directory being set to `~/Library/Logs/YourAppName` on _macOS_, and inside the `userData` directory on _Linux_ and _Windows_.
### `app.getAppPath()`
Returns `string` - The current application directory.
### `app.getPath(name)`
* `name` string - You can request the following paths by the name:
* `home` User's home directory.
* `appData` Per-user application data directory, which by default points to:
* `%APPDATA%` on Windows
* `$XDG_CONFIG_HOME` or `~/.config` on Linux
* `~/Library/Application Support` on macOS
* `userData` The directory for storing your app's configuration files, which
by default is the `appData` directory appended with your app's name. By
convention files storing user data should be written to this directory, and
it is not recommended to write large files here because some environments
may backup this directory to cloud storage.
* `sessionData` The directory for storing data generated by `Session`, such
as localStorage, cookies, disk cache, downloaded dictionaries, network
state, devtools files. By default this points to `userData`. Chromium may
write very large disk cache here, so if your app does not rely on browser
storage like localStorage or cookies to save user data, it is recommended
to set this directory to other locations to avoid polluting the `userData`
directory.
* `temp` Temporary directory.
* `exe` The current executable file.
* `module` The `libchromiumcontent` library.
* `desktop` The current user's Desktop directory.
* `documents` Directory for a user's "My Documents".
* `downloads` Directory for a user's downloads.
* `music` Directory for a user's music.
* `pictures` Directory for a user's pictures.
* `videos` Directory for a user's videos.
* `recent` Directory for the user's recent files (Windows only).
* `logs` Directory for your app's log folder.
* `crashDumps` Directory where crash dumps are stored.
Returns `string` - A path to a special directory or file associated with `name`. On
failure, an `Error` is thrown.
If `app.getPath('logs')` is called without called `app.setAppLogsPath()` being called first, a default log directory will be created equivalent to calling `app.setAppLogsPath()` without a `path` parameter.
### `app.getFileIcon(path[, options])`
* `path` string
* `options` Object (optional)
* `size` string
* `small` - 16x16
* `normal` - 32x32
* `large` - 48x48 on _Linux_, 32x32 on _Windows_, unsupported on _macOS_.
Returns `Promise<NativeImage>` - fulfilled with the app's icon, which is a [NativeImage](native-image.md).
Fetches a path's associated icon.
On _Windows_, there a 2 kinds of icons:
* Icons associated with certain file extensions, like `.mp3`, `.png`, etc.
* Icons inside the file itself, like `.exe`, `.dll`, `.ico`.
On _Linux_ and _macOS_, icons depend on the application associated with file mime type.
### `app.setPath(name, path)`
* `name` string
* `path` string
Overrides the `path` to a special directory or file associated with `name`.
If the path specifies a directory that does not exist, an `Error` is thrown.
In that case, the directory should be created with `fs.mkdirSync` or similar.
You can only override paths of a `name` defined in `app.getPath`.
By default, web pages' cookies and caches will be stored under the `sessionData`
directory. If you want to change this location, you have to override the
`sessionData` path before the `ready` event of the `app` module is emitted.
### `app.getVersion()`
Returns `string` - The version of the loaded application. If no version is found in the
application's `package.json` file, the version of the current bundle or
executable is returned.
### `app.getName()`
Returns `string` - The current application's name, which is the name in the application's
`package.json` file.
Usually the `name` field of `package.json` is a short lowercase name, according
to the npm modules spec. You should usually also specify a `productName`
field, which is your application's full capitalized name, and which will be
preferred over `name` by Electron.
### `app.setName(name)`
* `name` string
Overrides the current application's name.
**Note:** This function overrides the name used internally by Electron; it does not affect the name that the OS uses.
### `app.getLocale()`
Returns `string` - The current application locale, fetched using Chromium's `l10n_util` library.
Possible return values are documented [here](https://source.chromium.org/chromium/chromium/src/+/main:ui/base/l10n/l10n_util.cc).
To set the locale, you'll want to use a command line switch at app startup, which may be found [here](command-line-switches.md).
**Note:** When distributing your packaged app, you have to also ship the
`locales` folder.
**Note:** This API must be called after the `ready` event is emitted.
**Note:** To see example return values of this API compared to other locale and language APIs, see [`app.getPreferredSystemLanguages()`](#appgetpreferredsystemlanguages).
### `app.getLocaleCountryCode()`
Returns `string` - User operating system's locale two-letter [ISO 3166](https://www.iso.org/iso-3166-country-codes.html) country code. The value is taken from native OS APIs.
**Note:** When unable to detect locale country code, it returns empty string.
### `app.getSystemLocale()`
Returns `string` - The current system locale. On Windows and Linux, it is fetched using Chromium's `i18n` library. On macOS, `[NSLocale currentLocale]` is used instead. To get the user's current system language, which is not always the same as the locale, it is better to use [`app.getPreferredSystemLanguages()`](#appgetpreferredsystemlanguages).
Different operating systems also use the regional data differently:
* Windows 11 uses the regional format for numbers, dates, and times.
* macOS Monterey uses the region for formatting numbers, dates, times, and for selecting the currency symbol to use.
Therefore, this API can be used for purposes such as choosing a format for rendering dates and times in a calendar app, especially when the developer wants the format to be consistent with the OS.
**Note:** This API must be called after the `ready` event is emitted.
**Note:** To see example return values of this API compared to other locale and language APIs, see [`app.getPreferredSystemLanguages()`](#appgetpreferredsystemlanguages).
### `app.getPreferredSystemLanguages()`
Returns `string[]` - The user's preferred system languages from most preferred to least preferred, including the country codes if applicable. A user can modify and add to this list on Windows or macOS through the Language and Region settings.
The API uses `GlobalizationPreferences` (with a fallback to `GetSystemPreferredUILanguages`) on Windows, `\[NSLocale preferredLanguages\]` on macOS, and `g_get_language_names` on Linux.
This API can be used for purposes such as deciding what language to present the application in.
Here are some examples of return values of the various language and locale APIs with different configurations:
On Windows, given application locale is German, the regional format is Finnish (Finland), and the preferred system languages from most to least preferred are French (Canada), English (US), Simplified Chinese (China), Finnish, and Spanish (Latin America):
```js
app.getLocale() // 'de'
app.getSystemLocale() // 'fi-FI'
app.getPreferredSystemLanguages() // ['fr-CA', 'en-US', 'zh-Hans-CN', 'fi', 'es-419']
```
On macOS, given the application locale is German, the region is Finland, and the preferred system languages from most to least preferred are French (Canada), English (US), Simplified Chinese, and Spanish (Latin America):
```js
app.getLocale() // 'de'
app.getSystemLocale() // 'fr-FI'
app.getPreferredSystemLanguages() // ['fr-CA', 'en-US', 'zh-Hans-FI', 'es-419']
```
Both the available languages and regions and the possible return values differ between the two operating systems.
As can be seen with the example above, on Windows, it is possible that a preferred system language has no country code, and that one of the preferred system languages corresponds with the language used for the regional format. On macOS, the region serves more as a default country code: the user doesn't need to have Finnish as a preferred language to use Finland as the region,and the country code `FI` is used as the country code for preferred system languages that do not have associated countries in the language name.
### `app.addRecentDocument(path)` _macOS_ _Windows_
* `path` string
Adds `path` to the recent documents list.
This list is managed by the OS. On Windows, you can visit the list from the task
bar, and on macOS, you can visit it from dock menu.
### `app.clearRecentDocuments()` _macOS_ _Windows_
Clears the recent documents list.
### `app.setAsDefaultProtocolClient(protocol[, path, args])`
* `protocol` string - The name of your protocol, without `://`. For example,
if you want your app to handle `electron://` links, call this method with
`electron` as the parameter.
* `path` string (optional) _Windows_ - The path to the Electron executable.
Defaults to `process.execPath`
* `args` string[] (optional) _Windows_ - Arguments passed to the executable.
Defaults to an empty array
Returns `boolean` - Whether the call succeeded.
Sets the current executable as the default handler for a protocol (aka URI
scheme). It allows you to integrate your app deeper into the operating system.
Once registered, all links with `your-protocol://` will be opened with the
current executable. The whole link, including protocol, will be passed to your
application as a parameter.
**Note:** On macOS, you can only register protocols that have been added to
your app's `info.plist`, which cannot be modified at runtime. However, you can
change the file during build time via [Electron Forge][electron-forge],
[Electron Packager][electron-packager], or by editing `info.plist` with a text
editor. Please refer to [Apple's documentation][CFBundleURLTypes] for details.
**Note:** In a Windows Store environment (when packaged as an `appx`) this API
will return `true` for all calls but the registry key it sets won't be accessible
by other applications. In order to register your Windows Store application
as a default protocol handler you must [declare the protocol in your manifest](https://learn.microsoft.com/en-us/uwp/schemas/appxpackage/uapmanifestschema/element-uap-protocol).
The API uses the Windows Registry and `LSSetDefaultHandlerForURLScheme` internally.
### `app.removeAsDefaultProtocolClient(protocol[, path, args])` _macOS_ _Windows_
* `protocol` string - The name of your protocol, without `://`.
* `path` string (optional) _Windows_ - Defaults to `process.execPath`
* `args` string[] (optional) _Windows_ - Defaults to an empty array
Returns `boolean` - Whether the call succeeded.
This method checks if the current executable as the default handler for a
protocol (aka URI scheme). If so, it will remove the app as the default handler.
### `app.isDefaultProtocolClient(protocol[, path, args])`
* `protocol` string - The name of your protocol, without `://`.
* `path` string (optional) _Windows_ - Defaults to `process.execPath`
* `args` string[] (optional) _Windows_ - Defaults to an empty array
Returns `boolean` - Whether the current executable is the default handler for a
protocol (aka URI scheme).
**Note:** On macOS, you can use this method to check if the app has been
registered as the default protocol handler for a protocol. You can also verify
this by checking `~/Library/Preferences/com.apple.LaunchServices.plist` on the
macOS machine. Please refer to
[Apple's documentation][LSCopyDefaultHandlerForURLScheme] for details.
The API uses the Windows Registry and `LSCopyDefaultHandlerForURLScheme` internally.
### `app.getApplicationNameForProtocol(url)`
* `url` string - a URL with the protocol name to check. Unlike the other
methods in this family, this accepts an entire URL, including `://` at a
minimum (e.g. `https://`).
Returns `string` - Name of the application handling the protocol, or an empty
string if there is no handler. For instance, if Electron is the default
handler of the URL, this could be `Electron` on Windows and Mac. However,
don't rely on the precise format which is not guaranteed to remain unchanged.
Expect a different format on Linux, possibly with a `.desktop` suffix.
This method returns the application name of the default handler for the protocol
(aka URI scheme) of a URL.
### `app.getApplicationInfoForProtocol(url)` _macOS_ _Windows_
* `url` string - a URL with the protocol name to check. Unlike the other
methods in this family, this accepts an entire URL, including `://` at a
minimum (e.g. `https://`).
Returns `Promise<Object>` - Resolve with an object containing the following:
* `icon` NativeImage - the display icon of the app handling the protocol.
* `path` string - installation path of the app handling the protocol.
* `name` string - display name of the app handling the protocol.
This method returns a promise that contains the application name, icon and path of the default handler for the protocol
(aka URI scheme) of a URL.
### `app.setUserTasks(tasks)` _Windows_
* `tasks` [Task[]](structures/task.md) - Array of `Task` objects
Adds `tasks` to the [Tasks][tasks] category of the Jump List on Windows.
`tasks` is an array of [`Task`](structures/task.md) objects.
Returns `boolean` - Whether the call succeeded.
**Note:** If you'd like to customize the Jump List even more use
`app.setJumpList(categories)` instead.
### `app.getJumpListSettings()` _Windows_
Returns `Object`:
* `minItems` Integer - The minimum number of items that will be shown in the
Jump List (for a more detailed description of this value see the
[MSDN docs][JumpListBeginListMSDN]).
* `removedItems` [JumpListItem[]](structures/jump-list-item.md) - Array of `JumpListItem`
objects that correspond to items that the user has explicitly removed from custom categories in the
Jump List. These items must not be re-added to the Jump List in the **next**
call to `app.setJumpList()`, Windows will not display any custom category
that contains any of the removed items.
### `app.setJumpList(categories)` _Windows_
* `categories` [JumpListCategory[]](structures/jump-list-category.md) | `null` - Array of `JumpListCategory` objects.
Returns `string`
Sets or removes a custom Jump List for the application, and returns one of the
following strings:
* `ok` - Nothing went wrong.
* `error` - One or more errors occurred, enable runtime logging to figure out
the likely cause.
* `invalidSeparatorError` - An attempt was made to add a separator to a
custom category in the Jump List. Separators are only allowed in the
standard `Tasks` category.
* `fileTypeRegistrationError` - An attempt was made to add a file link to
the Jump List for a file type the app isn't registered to handle.
* `customCategoryAccessDeniedError` - Custom categories can't be added to the
Jump List due to user privacy or group policy settings.
If `categories` is `null` the previously set custom Jump List (if any) will be
replaced by the standard Jump List for the app (managed by Windows).
**Note:** If a `JumpListCategory` object has neither the `type` nor the `name`
property set then its `type` is assumed to be `tasks`. If the `name` property
is set but the `type` property is omitted then the `type` is assumed to be
`custom`.
**Note:** Users can remove items from custom categories, and Windows will not
allow a removed item to be added back into a custom category until **after**
the next successful call to `app.setJumpList(categories)`. Any attempt to
re-add a removed item to a custom category earlier than that will result in the
entire custom category being omitted from the Jump List. The list of removed
items can be obtained using `app.getJumpListSettings()`.
**Note:** The maximum length of a Jump List item's `description` property is
260 characters. Beyond this limit, the item will not be added to the Jump
List, nor will it be displayed.
Here's a very simple example of creating a custom Jump List:
```js
const { app } = require('electron')
app.setJumpList([
{
type: 'custom',
name: 'Recent Projects',
items: [
{ type: 'file', path: 'C:\\Projects\\project1.proj' },
{ type: 'file', path: 'C:\\Projects\\project2.proj' }
]
},
{ // has a name so `type` is assumed to be "custom"
name: 'Tools',
items: [
{
type: 'task',
title: 'Tool A',
program: process.execPath,
args: '--run-tool-a',
iconPath: process.execPath,
iconIndex: 0,
description: 'Runs Tool A'
},
{
type: 'task',
title: 'Tool B',
program: process.execPath,
args: '--run-tool-b',
iconPath: process.execPath,
iconIndex: 0,
description: 'Runs Tool B'
}
]
},
{ type: 'frequent' },
{ // has no name and no type so `type` is assumed to be "tasks"
items: [
{
type: 'task',
title: 'New Project',
program: process.execPath,
args: '--new-project',
description: 'Create a new project.'
},
{ type: 'separator' },
{
type: 'task',
title: 'Recover Project',
program: process.execPath,
args: '--recover-project',
description: 'Recover Project'
}
]
}
])
```
### `app.requestSingleInstanceLock([additionalData])`
* `additionalData` Record<any, any> (optional) - A JSON object containing additional data to send to the first instance.
Returns `boolean`
The return value of this method indicates whether or not this instance of your
application successfully obtained the lock. If it failed to obtain the lock,
you can assume that another instance of your application is already running with
the lock and exit immediately.
I.e. This method returns `true` if your process is the primary instance of your
application and your app should continue loading. It returns `false` if your
process should immediately quit as it has sent its parameters to another
instance that has already acquired the lock.
On macOS, the system enforces single instance automatically when users try to open
a second instance of your app in Finder, and the `open-file` and `open-url`
events will be emitted for that. However when users start your app in command
line, the system's single instance mechanism will be bypassed, and you have to
use this method to ensure single instance.
An example of activating the window of primary instance when a second instance
starts:
```js
const { app, BrowserWindow } = require('electron')
let myWindow = null
const additionalData = { myKey: 'myValue' }
const gotTheLock = app.requestSingleInstanceLock(additionalData)
if (!gotTheLock) {
app.quit()
} else {
app.on('second-instance', (event, commandLine, workingDirectory, additionalData) => {
// Print out data received from the second instance.
console.log(additionalData)
// Someone tried to run a second instance, we should focus our window.
if (myWindow) {
if (myWindow.isMinimized()) myWindow.restore()
myWindow.focus()
}
})
app.whenReady().then(() => {
myWindow = new BrowserWindow({})
myWindow.loadURL('https://electronjs.org')
})
}
```
### `app.hasSingleInstanceLock()`
Returns `boolean`
This method returns whether or not this instance of your app is currently
holding the single instance lock. You can request the lock with
`app.requestSingleInstanceLock()` and release with
`app.releaseSingleInstanceLock()`
### `app.releaseSingleInstanceLock()`
Releases all locks that were created by `requestSingleInstanceLock`. This will
allow multiple instances of the application to once again run side by side.
### `app.setUserActivity(type, userInfo[, webpageURL])` _macOS_
* `type` string - Uniquely identifies the activity. Maps to
[`NSUserActivity.activityType`][activity-type].
* `userInfo` any - App-specific state to store for use by another device.
* `webpageURL` string (optional) - The webpage to load in a browser if no suitable app is
installed on the resuming device. The scheme must be `http` or `https`.
Creates an `NSUserActivity` and sets it as the current activity. The activity
is eligible for [Handoff][handoff] to another device afterward.
### `app.getCurrentActivityType()` _macOS_
Returns `string` - The type of the currently running activity.
### `app.invalidateCurrentActivity()` _macOS_
Invalidates the current [Handoff][handoff] user activity.
### `app.resignCurrentActivity()` _macOS_
Marks the current [Handoff][handoff] user activity as inactive without invalidating it.
### `app.updateCurrentActivity(type, userInfo)` _macOS_
* `type` string - Uniquely identifies the activity. Maps to
[`NSUserActivity.activityType`][activity-type].
* `userInfo` any - App-specific state to store for use by another device.
Updates the current activity if its type matches `type`, merging the entries from
`userInfo` into its current `userInfo` dictionary.
### `app.setAppUserModelId(id)` _Windows_
* `id` string
Changes the [Application User Model ID][app-user-model-id] to `id`.
### `app.setActivationPolicy(policy)` _macOS_
* `policy` string - Can be 'regular', 'accessory', or 'prohibited'.
Sets the activation policy for a given app.
Activation policy types:
* 'regular' - The application is an ordinary app that appears in the Dock and may have a user interface.
* 'accessory' - The application doesnβt appear in the Dock and doesnβt have a menu bar, but it may be activated programmatically or by clicking on one of its windows.
* 'prohibited' - The application doesnβt appear in the Dock and may not create windows or be activated.
### `app.importCertificate(options, callback)` _Linux_
* `options` Object
* `certificate` string - Path for the pkcs12 file.
* `password` string - Passphrase for the certificate.
* `callback` Function
* `result` Integer - Result of import.
Imports the certificate in pkcs12 format into the platform certificate store.
`callback` is called with the `result` of import operation, a value of `0`
indicates success while any other value indicates failure according to Chromium [net_error_list](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h).
### `app.configureHostResolver(options)`
* `options` Object
* `enableBuiltInResolver` boolean (optional) - Whether the built-in host
resolver is used in preference to getaddrinfo. When enabled, the built-in
resolver will attempt to use the system's DNS settings to do DNS lookups
itself. Enabled by default on macOS, disabled by default on Windows and
Linux.
* `secureDnsMode` string (optional) - Can be 'off', 'automatic' or 'secure'.
Configures the DNS-over-HTTP mode. When 'off', no DoH lookups will be
performed. When 'automatic', DoH lookups will be performed first if DoH is
available, and insecure DNS lookups will be performed as a fallback. When
'secure', only DoH lookups will be performed. Defaults to 'automatic'.
* `secureDnsServers` string[] (optional) - A list of DNS-over-HTTP
server templates. See [RFC8484 Β§ 3][] for details on the template format.
Most servers support the POST method; the template for such servers is
simply a URI. Note that for [some DNS providers][doh-providers], the
resolver will automatically upgrade to DoH unless DoH is explicitly
disabled, even if there are no DoH servers provided in this list.
* `enableAdditionalDnsQueryTypes` boolean (optional) - Controls whether additional DNS
query types, e.g. HTTPS (DNS type 65) will be allowed besides the
traditional A and AAAA queries when a request is being made via insecure
DNS. Has no effect on Secure DNS which always allows additional types.
Defaults to true.
Configures host resolution (DNS and DNS-over-HTTPS). By default, the following
resolvers will be used, in order:
1. DNS-over-HTTPS, if the [DNS provider supports it][doh-providers], then
2. the built-in resolver (enabled on macOS only by default), then
3. the system's resolver (e.g. `getaddrinfo`).
This can be configured to either restrict usage of non-encrypted DNS
(`secureDnsMode: "secure"`), or disable DNS-over-HTTPS (`secureDnsMode:
"off"`). It is also possible to enable or disable the built-in resolver.
To disable insecure DNS, you can specify a `secureDnsMode` of `"secure"`. If you do
so, you should make sure to provide a list of DNS-over-HTTPS servers to use, in
case the user's DNS configuration does not include a provider that supports
DoH.
```js
const { app } = require('electron')
app.whenReady().then(() => {
app.configureHostResolver({
secureDnsMode: 'secure',
secureDnsServers: [
'https://cloudflare-dns.com/dns-query'
]
})
})
```
This API must be called after the `ready` event is emitted.
[doh-providers]: https://source.chromium.org/chromium/chromium/src/+/main:net/dns/public/doh_provider_entry.cc;l=31?q=%22DohProviderEntry::GetList()%22&ss=chromium%2Fchromium%2Fsrc
[RFC8484 Β§ 3]: https://datatracker.ietf.org/doc/html/rfc8484#section-3
### `app.disableHardwareAcceleration()`
Disables hardware acceleration for current app.
This method can only be called before app is ready.
### `app.disableDomainBlockingFor3DAPIs()`
By default, Chromium disables 3D APIs (e.g. WebGL) until restart on a per
domain basis if the GPU processes crashes too frequently. This function
disables that behavior.
This method can only be called before app is ready.
### `app.getAppMetrics()`
Returns [`ProcessMetric[]`](structures/process-metric.md): Array of `ProcessMetric` objects that correspond to memory and CPU usage statistics of all the processes associated with the app.
### `app.getGPUFeatureStatus()`
Returns [`GPUFeatureStatus`](structures/gpu-feature-status.md) - The Graphics Feature Status from `chrome://gpu/`.
**Note:** This information is only usable after the `gpu-info-update` event is emitted.
### `app.getGPUInfo(infoType)`
* `infoType` string - Can be `basic` or `complete`.
Returns `Promise<unknown>`
For `infoType` equal to `complete`:
Promise is fulfilled with `Object` containing all the GPU Information as in [chromium's GPUInfo object](https://chromium.googlesource.com/chromium/src/+/4178e190e9da409b055e5dff469911ec6f6b716f/gpu/config/gpu_info.cc). This includes the version and driver information that's shown on `chrome://gpu` page.
For `infoType` equal to `basic`:
Promise is fulfilled with `Object` containing fewer attributes than when requested with `complete`. Here's an example of basic response:
```js
{
auxAttributes:
{
amdSwitchable: true,
canSupportThreadedTextureMailbox: false,
directComposition: false,
directRendering: true,
glResetNotificationStrategy: 0,
inProcessGpu: true,
initializationTime: 0,
jpegDecodeAcceleratorSupported: false,
optimus: false,
passthroughCmdDecoder: false,
sandboxed: false,
softwareRendering: false,
supportsOverlays: false,
videoDecodeAcceleratorFlags: 0
},
gpuDevice:
[{ active: true, deviceId: 26657, vendorId: 4098 },
{ active: false, deviceId: 3366, vendorId: 32902 }],
machineModelName: 'MacBookPro',
machineModelVersion: '11.5'
}
```
Using `basic` should be preferred if only basic information like `vendorId` or `deviceId` is needed.
### `app.setBadgeCount([count])` _Linux_ _macOS_
* `count` Integer (optional) - If a value is provided, set the badge to the provided value otherwise, on macOS, display a plain white dot (e.g. unknown number of notifications). On Linux, if a value is not provided the badge will not display.
Returns `boolean` - Whether the call succeeded.
Sets the counter badge for current app. Setting the count to `0` will hide the
badge.
On macOS, it shows on the dock icon. On Linux, it only works for Unity launcher.
**Note:** Unity launcher requires a `.desktop` file to work. For more information,
please read the [Unity integration documentation][unity-requirement].
**Note:** On macOS, you need to ensure that your application has the permission
to display notifications for this method to work.
### `app.getBadgeCount()` _Linux_ _macOS_
Returns `Integer` - The current value displayed in the counter badge.
### `app.isUnityRunning()` _Linux_
Returns `boolean` - Whether the current desktop environment is Unity launcher.
### `app.getLoginItemSettings([options])` _macOS_ _Windows_
* `options` Object (optional)
* `path` string (optional) _Windows_ - The executable path to compare against.
Defaults to `process.execPath`.
* `args` string[] (optional) _Windows_ - The command-line arguments to compare
against. Defaults to an empty array.
If you provided `path` and `args` options to `app.setLoginItemSettings`, then you
need to pass the same arguments here for `openAtLogin` to be set correctly.
Returns `Object`:
* `openAtLogin` boolean - `true` if the app is set to open at login.
* `openAsHidden` boolean _macOS_ - `true` if the app is set to open as hidden at login.
This setting is not available on [MAS builds][mas-builds].
* `wasOpenedAtLogin` boolean _macOS_ - `true` if the app was opened at login
automatically. This setting is not available on [MAS builds][mas-builds].
* `wasOpenedAsHidden` boolean _macOS_ - `true` if the app was opened as a hidden login
item. This indicates that the app should not open any windows at startup.
This setting is not available on [MAS builds][mas-builds].
* `restoreState` boolean _macOS_ - `true` if the app was opened as a login item that
should restore the state from the previous session. This indicates that the
app should restore the windows that were open the last time the app was
closed. This setting is not available on [MAS builds][mas-builds].
* `executableWillLaunchAtLogin` boolean _Windows_ - `true` if app is set to open at login and its run key is not deactivated. This differs from `openAtLogin` as it ignores the `args` option, this property will be true if the given executable would be launched at login with **any** arguments.
* `launchItems` Object[] _Windows_
* `name` string _Windows_ - name value of a registry entry.
* `path` string _Windows_ - The executable to an app that corresponds to a registry entry.
* `args` string[] _Windows_ - the command-line arguments to pass to the executable.
* `scope` string _Windows_ - one of `user` or `machine`. Indicates whether the registry entry is under `HKEY_CURRENT USER` or `HKEY_LOCAL_MACHINE`.
* `enabled` boolean _Windows_ - `true` if the app registry key is startup approved and therefore shows as `enabled` in Task Manager and Windows settings.
### `app.setLoginItemSettings(settings)` _macOS_ _Windows_
* `settings` Object
* `openAtLogin` boolean (optional) - `true` to open the app at login, `false` to remove
the app as a login item. Defaults to `false`.
* `openAsHidden` boolean (optional) _macOS_ - `true` to open the app as hidden. Defaults to
`false`. The user can edit this setting from the System Preferences so
`app.getLoginItemSettings().wasOpenedAsHidden` should be checked when the app
is opened to know the current value. This setting is not available on [MAS builds][mas-builds].
* `path` string (optional) _Windows_ - The executable to launch at login.
Defaults to `process.execPath`.
* `args` string[] (optional) _Windows_ - The command-line arguments to pass to
the executable. Defaults to an empty array. Take care to wrap paths in
quotes.
* `enabled` boolean (optional) _Windows_ - `true` will change the startup approved registry key and `enable / disable` the App in Task Manager and Windows Settings.
Defaults to `true`.
* `name` string (optional) _Windows_ - value name to write into registry. Defaults to the app's AppUserModelId().
Set the app's login item settings.
To work with Electron's `autoUpdater` on Windows, which uses [Squirrel][Squirrel-Windows],
you'll want to set the launch path to Update.exe, and pass arguments that specify your
application name. For example:
``` js
const { app } = require('electron')
const path = require('node:path')
const appFolder = path.dirname(process.execPath)
const updateExe = path.resolve(appFolder, '..', 'Update.exe')
const exeName = path.basename(process.execPath)
app.setLoginItemSettings({
openAtLogin: true,
path: updateExe,
args: [
'--processStart', `"${exeName}"`,
'--process-start-args', '"--hidden"'
]
})
```
### `app.isAccessibilitySupportEnabled()` _macOS_ _Windows_
Returns `boolean` - `true` if Chrome's accessibility support is enabled,
`false` otherwise. This API will return `true` if the use of assistive
technologies, such as screen readers, has been detected. See
https://www.chromium.org/developers/design-documents/accessibility for more
details.
### `app.setAccessibilitySupportEnabled(enabled)` _macOS_ _Windows_
* `enabled` boolean - Enable or disable [accessibility tree](https://developers.google.com/web/fundamentals/accessibility/semantics-builtin/the-accessibility-tree) rendering
Manually enables Chrome's accessibility support, allowing to expose accessibility switch to users in application settings. See [Chromium's accessibility docs](https://www.chromium.org/developers/design-documents/accessibility) for more
details. Disabled by default.
This API must be called after the `ready` event is emitted.
**Note:** Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default.
### `app.showAboutPanel()`
Show the app's about panel options. These options can be overridden with `app.setAboutPanelOptions(options)`. This function runs asynchronously.
### `app.setAboutPanelOptions(options)`
* `options` Object
* `applicationName` string (optional) - The app's name.
* `applicationVersion` string (optional) - The app's version.
* `copyright` string (optional) - Copyright information.
* `version` string (optional) _macOS_ - The app's build version number.
* `credits` string (optional) _macOS_ _Windows_ - Credit information.
* `authors` string[] (optional) _Linux_ - List of app authors.
* `website` string (optional) _Linux_ - The app's website.
* `iconPath` string (optional) _Linux_ _Windows_ - Path to the app's icon in a JPEG or PNG file format. On Linux, will be shown as 64x64 pixels while retaining aspect ratio.
Set the about panel options. This will override the values defined in the app's `.plist` file on macOS. See the [Apple docs][about-panel-options] for more details. On Linux, values must be set in order to be shown; there are no defaults.
If you do not set `credits` but still wish to surface them in your app, AppKit will look for a file named "Credits.html", "Credits.rtf", and "Credits.rtfd", in that order, in the bundle returned by the NSBundle class method main. The first file found is used, and if none is found, the info area is left blank. See Apple [documentation](https://developer.apple.com/documentation/appkit/nsaboutpaneloptioncredits?language=objc) for more information.
### `app.isEmojiPanelSupported()`
Returns `boolean` - whether or not the current OS version allows for native emoji pickers.
### `app.showEmojiPanel()` _macOS_ _Windows_
Show the platform's native emoji picker.
### `app.startAccessingSecurityScopedResource(bookmarkData)` _mas_
* `bookmarkData` string - The base64 encoded security scoped bookmark data returned by the `dialog.showOpenDialog` or `dialog.showSaveDialog` methods.
Returns `Function` - This function **must** be called once you have finished accessing the security scoped file. If you do not remember to stop accessing the bookmark, [kernel resources will be leaked](https://developer.apple.com/reference/foundation/nsurl/1417051-startaccessingsecurityscopedreso?language=objc) and your app will lose its ability to reach outside the sandbox completely, until your app is restarted.
```js
const { app, dialog } = require('electron')
const fs = require('node:fs')
let filepath
let bookmark
dialog.showOpenDialog(null, { securityScopedBookmarks: true }).then(({ filePaths, bookmarks }) => {
filepath = filePaths[0]
bookmark = bookmarks[0]
fs.readFileSync(filepath)
})
// ... restart app ...
const stopAccessingSecurityScopedResource = app.startAccessingSecurityScopedResource(bookmark)
fs.readFileSync(filepath)
stopAccessingSecurityScopedResource()
```
Start accessing a security scoped resource. With this method Electron applications that are packaged for the Mac App Store may reach outside their sandbox to access files chosen by the user. See [Apple's documentation](https://developer.apple.com/library/content/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16) for a description of how this system works.
### `app.enableSandbox()`
Enables full sandbox mode on the app. This means that all renderers will be launched sandboxed, regardless of the value of the `sandbox` flag in [`WebPreferences`](structures/web-preferences.md).
This method can only be called before app is ready.
### `app.isInApplicationsFolder()` _macOS_
Returns `boolean` - Whether the application is currently running from the
systems Application folder. Use in combination with `app.moveToApplicationsFolder()`
### `app.moveToApplicationsFolder([options])` _macOS_
* `options` Object (optional)
* `conflictHandler` Function\<boolean> (optional) - A handler for potential conflict in move failure.
* `conflictType` string - The type of move conflict encountered by the handler; can be `exists` or `existsAndRunning`, where `exists` means that an app of the same name is present in the Applications directory and `existsAndRunning` means both that it exists and that it's presently running.
Returns `boolean` - Whether the move was successful. Please note that if
the move is successful, your application will quit and relaunch.
No confirmation dialog will be presented by default. If you wish to allow
the user to confirm the operation, you may do so using the
[`dialog`](dialog.md) API.
**NOTE:** This method throws errors if anything other than the user causes the
move to fail. For instance if the user cancels the authorization dialog, this
method returns false. If we fail to perform the copy, then this method will
throw an error. The message in the error should be informative and tell
you exactly what went wrong.
By default, if an app of the same name as the one being moved exists in the Applications directory and is _not_ running, the existing app will be trashed and the active app moved into its place. If it _is_ running, the preexisting running app will assume focus and the previously active app will quit itself. This behavior can be changed by providing the optional conflict handler, where the boolean returned by the handler determines whether or not the move conflict is resolved with default behavior. i.e. returning `false` will ensure no further action is taken, returning `true` will result in the default behavior and the method continuing.
For example:
```js
const { app, dialog } = require('electron')
app.moveToApplicationsFolder({
conflictHandler: (conflictType) => {
if (conflictType === 'exists') {
return dialog.showMessageBoxSync({
type: 'question',
buttons: ['Halt Move', 'Continue Move'],
defaultId: 0,
message: 'An app of this name already exists'
}) === 1
}
}
})
```
Would mean that if an app already exists in the user directory, if the user chooses to 'Continue Move' then the function would continue with its default behavior and the existing app will be trashed and the active app moved into its place.
### `app.isSecureKeyboardEntryEnabled()` _macOS_
Returns `boolean` - whether `Secure Keyboard Entry` is enabled.
By default this API will return `false`.
### `app.setSecureKeyboardEntryEnabled(enabled)` _macOS_
* `enabled` boolean - Enable or disable `Secure Keyboard Entry`
Set the `Secure Keyboard Entry` is enabled in your application.
By using this API, important information such as password and other sensitive information can be prevented from being intercepted by other processes.
See [Apple's documentation](https://developer.apple.com/library/archive/technotes/tn2150/_index.html) for more
details.
**Note:** Enable `Secure Keyboard Entry` only when it is needed and disable it when it is no longer needed.
## Properties
### `app.accessibilitySupportEnabled` _macOS_ _Windows_
A `boolean` property that's `true` if Chrome's accessibility support is enabled, `false` otherwise. This property will be `true` if the use of assistive technologies, such as screen readers, has been detected. Setting this property to `true` manually enables Chrome's accessibility support, allowing developers to expose accessibility switch to users in application settings.
See [Chromium's accessibility docs](https://www.chromium.org/developers/design-documents/accessibility) for more details. Disabled by default.
This API must be called after the `ready` event is emitted.
**Note:** Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default.
### `app.applicationMenu`
A `Menu | null` property that returns [`Menu`](menu.md) if one has been set and `null` otherwise.
Users can pass a [Menu](menu.md) to set this property.
### `app.badgeCount` _Linux_ _macOS_
An `Integer` property that returns the badge count for current app. Setting the count to `0` will hide the badge.
On macOS, setting this with any nonzero integer shows on the dock icon. On Linux, this property only works for Unity launcher.
**Note:** Unity launcher requires a `.desktop` file to work. For more information,
please read the [Unity integration documentation][unity-requirement].
**Note:** On macOS, you need to ensure that your application has the permission
to display notifications for this property to take effect.
### `app.commandLine` _Readonly_
A [`CommandLine`](./command-line.md) object that allows you to read and manipulate the
command line arguments that Chromium uses.
### `app.dock` _macOS_ _Readonly_
A [`Dock`](./dock.md) `| undefined` object that allows you to perform actions on your app icon in the user's
dock on macOS.
### `app.isPackaged` _Readonly_
A `boolean` property that returns `true` if the app is packaged, `false` otherwise. For many apps, this property can be used to distinguish development and production environments.
[tasks]:https://learn.microsoft.com/en-us/windows/win32/shell/taskbar-extensions#tasks
[app-user-model-id]: https://learn.microsoft.com/en-us/windows/win32/shell/appids
[electron-forge]: https://www.electronforge.io/
[electron-packager]: https://github.com/electron/electron-packager
[CFBundleURLTypes]: https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115
[LSCopyDefaultHandlerForURLScheme]: https://developer.apple.com/documentation/coreservices/1441725-lscopydefaulthandlerforurlscheme?language=objc
[handoff]: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/Handoff/HandoffFundamentals/HandoffFundamentals.html
[activity-type]: https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSUserActivity_Class/index.html#//apple_ref/occ/instp/NSUserActivity/activityType
[unity-requirement]: https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles#Adding_shortcuts_to_a_launcher
[mas-builds]: ../tutorial/mac-app-store-submission-guide.md
[Squirrel-Windows]: https://github.com/Squirrel/Squirrel.Windows
[JumpListBeginListMSDN]: https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-icustomdestinationlist-beginlist
[about-panel-options]: https://developer.apple.com/reference/appkit/nsapplication/1428479-orderfrontstandardaboutpanelwith?language=objc
### `app.name`
A `string` property that indicates the current application's name, which is the name in the application's `package.json` file.
Usually the `name` field of `package.json` is a short lowercase name, according
to the npm modules spec. You should usually also specify a `productName`
field, which is your application's full capitalized name, and which will be
preferred over `name` by Electron.
### `app.userAgentFallback`
A `string` which is the user agent string Electron will use as a global fallback.
This is the user agent that will be used when no user agent is set at the
`webContents` or `session` level. It is useful for ensuring that your entire
app has the same user agent. Set to a custom value as early as possible
in your app's initialization to ensure that your overridden value is used.
### `app.runningUnderARM64Translation` _Readonly_ _macOS_ _Windows_
A `boolean` which when `true` indicates that the app is currently running under
an ARM64 translator (like the macOS
[Rosetta Translator Environment](https://en.wikipedia.org/wiki/Rosetta_(software))
or Windows [WOW](https://en.wikipedia.org/wiki/Windows_on_Windows)).
You can use this property to prompt users to download the arm64 version of
your application when they are mistakenly running the x64 version under Rosetta or WOW.
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 37,560 |
[Bug]: Open at login with setLoginItemSettings in MAS build is not working
|
### 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
16.0.6
### What operating system are you using?
macOS
### Operating System Version
Version 13.2 (22D49)
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Setting app to open at login with setLoginItemSettings api should work both locally and with MAS build.
Locally the app is added to login items but when i build it for MAS this doesn't work.
### Actual Behavior
Setting app to open at login with setLoginItemSettings api works locally but doesn't work in MAS build.
In MAS build the app is not added to login items.
<img width="477" alt="image" src="https://user-images.githubusercontent.com/17458685/224576455-a9145dfc-7121-4097-9fe4-a472f0c2ead4.png">
### Testcase Gist URL
_No response_
### Additional Information
According to docs https://www.electronjs.org/docs/latest/api/app#appsetloginitemsettingssettings-macos-windows setting login item in MAS build should work by using the following API
```js
app.setLoginItemSettings({
openAtLogin: openAtLogin,
})
```
In the docs on limitations of MAS build there is no mention of any limitation of using above API https://www.electronjs.org/docs/latest/tutorial/mac-app-store-submission-guide#limitations-of-mas-build
Here is possible related issue and PRs:
- https://github.com/electron/electron/issues/7312
- https://github.com/electron/electron/pull/11144
- https://github.com/electron/electron/pull/10856
|
https://github.com/electron/electron/issues/37560
|
https://github.com/electron/electron/pull/37244
|
6d0d350e138494cd68dd3d4fa73b2719da4575bf
|
f7b1c75c72a8dcab4157408f92bd3771606d8029
| 2023-03-12T22:11:32Z |
c++
| 2023-10-16T16:25:11Z |
shell/browser/api/electron_api_app.cc
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_app.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/command_line.h"
#include "base/containers/fixed_flat_map.h"
#include "base/containers/span.h"
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/callback_helpers.h"
#include "base/path_service.h"
#include "base/system/sys_info.h"
#include "base/values.h"
#include "base/win/windows_version.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/icon_manager.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_paths.h"
#include "content/browser/gpu/compositor_util.h" // nogncheck
#include "content/browser/gpu/gpu_data_manager_impl.h" // nogncheck
#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/browser_child_process_host.h"
#include "content/public/browser/child_process_data.h"
#include "content/public/browser/client_certificate_delegate.h"
#include "content/public/browser/gpu_data_manager.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/common/content_switches.h"
#include "crypto/crypto_buildflags.h"
#include "media/audio/audio_manager.h"
#include "net/dns/public/dns_over_https_config.h"
#include "net/dns/public/dns_over_https_server_config.h"
#include "net/dns/public/util.h"
#include "net/ssl/client_cert_identity.h"
#include "net/ssl/ssl_cert_request_info.h"
#include "net/ssl/ssl_private_key.h"
#include "sandbox/policy/switches.h"
#include "services/network/network_service.h"
#include "shell/app/command_line_args.h"
#include "shell/browser/api/electron_api_menu.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/api/electron_api_utility_process.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/api/gpuinfo_manager.h"
#include "shell/browser/browser_process_impl.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/javascript_environment.h"
#include "shell/browser/login_handler.h"
#include "shell/browser/relauncher.h"
#include "shell/common/application_info.h"
#include "shell/common/electron_command_line.h"
#include "shell/common/electron_paths.h"
#include "shell/common/gin_converters/base_converter.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/language_util.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/platform_util.h"
#include "shell/common/thread_restrictions.h"
#include "shell/common/v8_value_serializer.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/gfx/image/image.h"
#if BUILDFLAG(IS_WIN)
#include "base/strings/utf_string_conversions.h"
#include "shell/browser/ui/win/jump_list.h"
#endif
#if BUILDFLAG(IS_MAC)
#include <CoreFoundation/CoreFoundation.h>
#include "shell/browser/ui/cocoa/electron_bundle_mover.h"
#endif
using electron::Browser;
namespace gin {
#if BUILDFLAG(IS_WIN)
template <>
struct Converter<electron::ProcessIntegrityLevel> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
electron::ProcessIntegrityLevel value) {
switch (value) {
case electron::ProcessIntegrityLevel::kUntrusted:
return StringToV8(isolate, "untrusted");
case electron::ProcessIntegrityLevel::kLow:
return StringToV8(isolate, "low");
case electron::ProcessIntegrityLevel::kMedium:
return StringToV8(isolate, "medium");
case electron::ProcessIntegrityLevel::kHigh:
return StringToV8(isolate, "high");
default:
return StringToV8(isolate, "unknown");
}
}
};
template <>
struct Converter<Browser::UserTask> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
Browser::UserTask* out) {
gin_helper::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
if (!dict.Get("program", &(out->program)) ||
!dict.Get("title", &(out->title)))
return false;
if (dict.Get("iconPath", &(out->icon_path)) &&
!dict.Get("iconIndex", &(out->icon_index)))
return false;
dict.Get("arguments", &(out->arguments));
dict.Get("description", &(out->description));
dict.Get("workingDirectory", &(out->working_dir));
return true;
}
};
using electron::JumpListCategory;
using electron::JumpListItem;
using electron::JumpListResult;
template <>
struct Converter<JumpListItem::Type> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
JumpListItem::Type* out) {
return FromV8WithLookup(isolate, val, Lookup, out);
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
JumpListItem::Type val) {
for (const auto& [name, item_val] : Lookup)
if (item_val == val)
return gin::ConvertToV8(isolate, name);
return gin::ConvertToV8(isolate, "");
}
private:
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, JumpListItem::Type>({
{"file", JumpListItem::Type::kFile},
{"separator", JumpListItem::Type::kSeparator},
{"task", JumpListItem::Type::kTask},
});
};
template <>
struct Converter<JumpListItem> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
JumpListItem* out) {
gin_helper::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
if (!dict.Get("type", &(out->type)))
return false;
switch (out->type) {
case JumpListItem::Type::kTask:
if (!dict.Get("program", &(out->path)) ||
!dict.Get("title", &(out->title)))
return false;
if (dict.Get("iconPath", &(out->icon_path)) &&
!dict.Get("iconIndex", &(out->icon_index)))
return false;
dict.Get("args", &(out->arguments));
dict.Get("description", &(out->description));
dict.Get("workingDirectory", &(out->working_dir));
return true;
case JumpListItem::Type::kSeparator:
return true;
case JumpListItem::Type::kFile:
return dict.Get("path", &(out->path));
}
assert(false);
return false;
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const JumpListItem& val) {
auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
dict.Set("type", val.type);
switch (val.type) {
case JumpListItem::Type::kTask:
dict.Set("program", val.path);
dict.Set("args", val.arguments);
dict.Set("title", val.title);
dict.Set("iconPath", val.icon_path);
dict.Set("iconIndex", val.icon_index);
dict.Set("description", val.description);
dict.Set("workingDirectory", val.working_dir);
break;
case JumpListItem::Type::kSeparator:
break;
case JumpListItem::Type::kFile:
dict.Set("path", val.path);
break;
}
return dict.GetHandle();
}
};
template <>
struct Converter<JumpListCategory::Type> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
JumpListCategory::Type* out) {
return FromV8WithLookup(isolate, val, Lookup, out);
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
JumpListCategory::Type val) {
for (const auto& [name, type_val] : Lookup)
if (type_val == val)
return gin::ConvertToV8(isolate, name);
return gin::ConvertToV8(isolate, "");
}
private:
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, JumpListCategory::Type>({
{"custom", JumpListCategory::Type::kCustom},
{"frequent", JumpListCategory::Type::kFrequent},
{"recent", JumpListCategory::Type::kRecent},
{"tasks", JumpListCategory::Type::kTasks},
});
};
template <>
struct Converter<JumpListCategory> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
JumpListCategory* out) {
gin_helper::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
if (dict.Get("name", &(out->name)) && out->name.empty())
return false;
if (!dict.Get("type", &(out->type))) {
if (out->name.empty())
out->type = JumpListCategory::Type::kTasks;
else
out->type = JumpListCategory::Type::kCustom;
}
if ((out->type == JumpListCategory::Type::kTasks) ||
(out->type == JumpListCategory::Type::kCustom)) {
if (!dict.Get("items", &(out->items)))
return false;
}
return true;
}
};
// static
template <>
struct Converter<JumpListResult> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, JumpListResult val) {
std::string result_code;
switch (val) {
case JumpListResult::kSuccess:
result_code = "ok";
break;
case JumpListResult::kArgumentError:
result_code = "argumentError";
break;
case JumpListResult::kGenericError:
result_code = "error";
break;
case JumpListResult::kCustomCategorySeparatorError:
result_code = "invalidSeparatorError";
break;
case JumpListResult::kMissingFileTypeRegistrationError:
result_code = "fileTypeRegistrationError";
break;
case JumpListResult::kCustomCategoryAccessDeniedError:
result_code = "customCategoryAccessDeniedError";
break;
}
return ConvertToV8(isolate, result_code);
}
};
#endif
#if BUILDFLAG(IS_WIN)
template <>
struct Converter<Browser::LaunchItem> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
Browser::LaunchItem* out) {
gin_helper::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
dict.Get("name", &(out->name));
dict.Get("path", &(out->path));
dict.Get("args", &(out->args));
dict.Get("scope", &(out->scope));
dict.Get("enabled", &(out->enabled));
return true;
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
Browser::LaunchItem val) {
auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
dict.Set("name", val.name);
dict.Set("path", val.path);
dict.Set("args", val.args);
dict.Set("scope", val.scope);
dict.Set("enabled", val.enabled);
return dict.GetHandle();
}
};
#endif
template <>
struct Converter<Browser::LoginItemSettings> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
Browser::LoginItemSettings* out) {
gin_helper::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
dict.Get("openAtLogin", &(out->open_at_login));
dict.Get("openAsHidden", &(out->open_as_hidden));
dict.Get("path", &(out->path));
dict.Get("args", &(out->args));
#if BUILDFLAG(IS_WIN)
dict.Get("enabled", &(out->enabled));
dict.Get("name", &(out->name));
#endif
return true;
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
Browser::LoginItemSettings val) {
auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
dict.Set("openAtLogin", val.open_at_login);
dict.Set("openAsHidden", val.open_as_hidden);
dict.Set("restoreState", val.restore_state);
dict.Set("wasOpenedAtLogin", val.opened_at_login);
dict.Set("wasOpenedAsHidden", val.opened_as_hidden);
#if BUILDFLAG(IS_WIN)
dict.Set("launchItems", val.launch_items);
dict.Set("executableWillLaunchAtLogin",
val.executable_will_launch_at_login);
#endif
return dict.GetHandle();
}
};
template <>
struct Converter<content::CertificateRequestResultType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
content::CertificateRequestResultType* out) {
bool b;
if (!ConvertFromV8(isolate, val, &b))
return false;
*out = b ? content::CERTIFICATE_REQUEST_RESULT_TYPE_CONTINUE
: content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
return true;
}
};
template <>
struct Converter<net::SecureDnsMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
net::SecureDnsMode* out) {
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, net::SecureDnsMode>({
{"automatic", net::SecureDnsMode::kAutomatic},
{"off", net::SecureDnsMode::kOff},
{"secure", net::SecureDnsMode::kSecure},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
} // namespace gin
namespace electron::api {
gin::WrapperInfo App::kWrapperInfo = {gin::kEmbedderNativeGin};
namespace {
IconLoader::IconSize GetIconSizeByString(const std::string& size) {
if (size == "small") {
return IconLoader::IconSize::SMALL;
} else if (size == "large") {
return IconLoader::IconSize::LARGE;
}
return IconLoader::IconSize::NORMAL;
}
// Return the path constant from string.
int GetPathConstant(base::StringPiece name) {
// clang-format off
constexpr auto Lookup = base::MakeFixedFlatMapSorted<base::StringPiece, int>({
{"appData", DIR_APP_DATA},
#if BUILDFLAG(IS_POSIX)
{"cache", base::DIR_CACHE},
#else
{"cache", base::DIR_ROAMING_APP_DATA},
#endif
{"crashDumps", DIR_CRASH_DUMPS},
{"desktop", base::DIR_USER_DESKTOP},
{"documents", chrome::DIR_USER_DOCUMENTS},
{"downloads", chrome::DIR_DEFAULT_DOWNLOADS},
{"exe", base::FILE_EXE},
{"home", base::DIR_HOME},
{"logs", DIR_APP_LOGS},
{"module", base::FILE_MODULE},
{"music", chrome::DIR_USER_MUSIC},
{"pictures", chrome::DIR_USER_PICTURES},
#if BUILDFLAG(IS_WIN)
{"recent", electron::DIR_RECENT},
#endif
{"sessionData", DIR_SESSION_DATA},
{"temp", base::DIR_TEMP},
{"userCache", DIR_USER_CACHE},
{"userData", chrome::DIR_USER_DATA},
{"userDesktop", base::DIR_USER_DESKTOP},
{"videos", chrome::DIR_USER_VIDEOS},
});
// clang-format on
const auto* iter = Lookup.find(name);
return iter != Lookup.end() ? iter->second : -1;
}
bool NotificationCallbackWrapper(
const base::RepeatingCallback<
void(const base::CommandLine& command_line,
const base::FilePath& current_directory,
const std::vector<const uint8_t> additional_data)>& callback,
const base::CommandLine& cmd,
const base::FilePath& cwd,
const std::vector<const uint8_t> additional_data) {
// Make sure the callback is called after app gets ready.
if (Browser::Get()->is_ready()) {
callback.Run(cmd, cwd, std::move(additional_data));
} else {
scoped_refptr<base::SingleThreadTaskRunner> task_runner(
base::SingleThreadTaskRunner::GetCurrentDefault());
// Make a copy of the span so that the data isn't lost.
task_runner->PostTask(FROM_HERE,
base::BindOnce(base::IgnoreResult(callback), cmd, cwd,
std::move(additional_data)));
}
// ProcessSingleton needs to know whether current process is quiting.
return !Browser::Get()->is_shutting_down();
}
void GotPrivateKey(std::shared_ptr<content::ClientCertificateDelegate> delegate,
scoped_refptr<net::X509Certificate> cert,
scoped_refptr<net::SSLPrivateKey> private_key) {
delegate->ContinueWithCertificate(cert, private_key);
}
void OnClientCertificateSelected(
v8::Isolate* isolate,
std::shared_ptr<content::ClientCertificateDelegate> delegate,
std::shared_ptr<net::ClientCertIdentityList> identities,
gin::Arguments* args) {
if (args->Length() == 2) {
delegate->ContinueWithCertificate(nullptr, nullptr);
return;
}
v8::Local<v8::Value> val;
args->GetNext(&val);
if (val->IsNull()) {
delegate->ContinueWithCertificate(nullptr, nullptr);
return;
}
gin_helper::Dictionary cert_data;
if (!gin::ConvertFromV8(isolate, val, &cert_data)) {
gin_helper::ErrorThrower(isolate).ThrowError(
"Must pass valid certificate object.");
return;
}
std::string data;
if (!cert_data.Get("data", &data))
return;
auto certs = net::X509Certificate::CreateCertificateListFromBytes(
base::as_bytes(base::make_span(data.c_str(), data.size())),
net::X509Certificate::FORMAT_AUTO);
if (!certs.empty()) {
scoped_refptr<net::X509Certificate> cert(certs[0].get());
for (auto& identity : *identities) {
scoped_refptr<net::X509Certificate> identity_cert =
identity->certificate();
// Since |cert| was recreated from |data|, it won't include any
// intermediates. That's fine for checking equality, but once a match is
// found then |identity_cert| should be used since it will include the
// intermediates which would otherwise be lost.
if (cert->EqualsExcludingChain(identity_cert.get())) {
net::ClientCertIdentity::SelfOwningAcquirePrivateKey(
std::move(identity), base::BindRepeating(&GotPrivateKey, delegate,
std::move(identity_cert)));
break;
}
}
}
}
#if BUILDFLAG(USE_NSS_CERTS)
int ImportIntoCertStore(CertificateManagerModel* model, base::Value options) {
std::string file_data, cert_path;
std::u16string password;
net::ScopedCERTCertificateList imported_certs;
int rv = -1;
if (const base::Value::Dict* dict = options.GetIfDict(); dict != nullptr) {
if (const std::string* str = dict->FindString("certificate"); str)
cert_path = *str;
if (const std::string* str = dict->FindString("password"); str)
password = base::UTF8ToUTF16(*str);
}
if (!cert_path.empty()) {
if (base::ReadFileToString(base::FilePath(cert_path), &file_data)) {
auto module = model->cert_db()->GetPrivateSlot();
rv = model->ImportFromPKCS12(module.get(), file_data, password, true,
&imported_certs);
if (imported_certs.size() > 1) {
auto it = imported_certs.begin();
++it; // skip first which would be the client certificate.
for (; it != imported_certs.end(); ++it)
rv &= model->SetCertTrust(it->get(), net::CA_CERT,
net::NSSCertDatabase::TRUSTED_SSL);
}
}
}
return rv;
}
#endif
void OnIconDataAvailable(gin_helper::Promise<gfx::Image> promise,
gfx::Image icon) {
if (!icon.IsEmpty()) {
promise.Resolve(icon);
} else {
promise.RejectWithErrorMessage("Failed to get file icon.");
}
}
} // namespace
App::App() {
static_cast<ElectronBrowserClient*>(ElectronBrowserClient::Get())
->set_delegate(this);
Browser::Get()->AddObserver(this);
auto pid = content::ChildProcessHost::kInvalidUniqueID;
auto process_metric = std::make_unique<electron::ProcessMetric>(
content::PROCESS_TYPE_BROWSER, base::GetCurrentProcessHandle(),
base::ProcessMetrics::CreateCurrentProcessMetrics());
app_metrics_[pid] = std::move(process_metric);
}
App::~App() {
static_cast<ElectronBrowserClient*>(ElectronBrowserClient::Get())
->set_delegate(nullptr);
Browser::Get()->RemoveObserver(this);
content::GpuDataManager::GetInstance()->RemoveObserver(this);
content::BrowserChildProcessObserver::Remove(this);
}
void App::OnBeforeQuit(bool* prevent_default) {
if (Emit("before-quit")) {
*prevent_default = true;
}
}
void App::OnWillQuit(bool* prevent_default) {
if (Emit("will-quit")) {
*prevent_default = true;
}
}
void App::OnWindowAllClosed() {
Emit("window-all-closed");
}
void App::OnQuit() {
const int exitCode = ElectronBrowserMainParts::Get()->GetExitCode();
Emit("quit", exitCode);
if (process_singleton_) {
process_singleton_->Cleanup();
process_singleton_.reset();
}
}
void App::OnOpenFile(bool* prevent_default, const std::string& file_path) {
if (Emit("open-file", file_path)) {
*prevent_default = true;
}
}
void App::OnOpenURL(const std::string& url) {
Emit("open-url", url);
}
void App::OnActivate(bool has_visible_windows) {
Emit("activate", has_visible_windows);
}
void App::OnWillFinishLaunching() {
Emit("will-finish-launching");
}
void App::OnFinishLaunching(base::Value::Dict launch_info) {
#if BUILDFLAG(IS_LINUX)
// Set the application name for audio streams shown in external
// applications. Only affects pulseaudio currently.
media::AudioManager::SetGlobalAppName(Browser::Get()->GetName());
#endif
Emit("ready", base::Value(std::move(launch_info)));
}
void App::OnPreMainMessageLoopRun() {
content::BrowserChildProcessObserver::Add(this);
if (process_singleton_ && watch_singleton_socket_on_ready_) {
process_singleton_->StartWatching();
watch_singleton_socket_on_ready_ = false;
}
}
void App::OnPreCreateThreads() {
DCHECK(!content::GpuDataManager::Initialized());
content::GpuDataManager* manager = content::GpuDataManager::GetInstance();
manager->AddObserver(this);
if (disable_hw_acceleration_) {
manager->DisableHardwareAcceleration();
}
if (disable_domain_blocking_for_3DAPIs_) {
content::GpuDataManagerImpl::GetInstance()
->DisableDomainBlockingFor3DAPIsForTesting();
}
}
void App::OnAccessibilitySupportChanged() {
Emit("accessibility-support-changed", IsAccessibilitySupportEnabled());
}
#if BUILDFLAG(IS_MAC)
void App::OnWillContinueUserActivity(bool* prevent_default,
const std::string& type) {
if (Emit("will-continue-activity", type)) {
*prevent_default = true;
}
}
void App::OnDidFailToContinueUserActivity(const std::string& type,
const std::string& error) {
Emit("continue-activity-error", type, error);
}
void App::OnContinueUserActivity(bool* prevent_default,
const std::string& type,
base::Value::Dict user_info,
base::Value::Dict details) {
if (Emit("continue-activity", type, base::Value(std::move(user_info)),
base::Value(std::move(details)))) {
*prevent_default = true;
}
}
void App::OnUserActivityWasContinued(const std::string& type,
base::Value::Dict user_info) {
Emit("activity-was-continued", type, base::Value(std::move(user_info)));
}
void App::OnUpdateUserActivityState(bool* prevent_default,
const std::string& type,
base::Value::Dict user_info) {
if (Emit("update-activity-state", type, base::Value(std::move(user_info)))) {
*prevent_default = true;
}
}
void App::OnNewWindowForTab() {
Emit("new-window-for-tab");
}
void App::OnDidBecomeActive() {
Emit("did-become-active");
}
void App::OnDidResignActive() {
Emit("did-resign-active");
}
#endif
bool App::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) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
content::WebContents* web_contents =
content::WebContents::FromRenderFrameHost(opener);
if (web_contents) {
WebContents* api_web_contents = WebContents::From(web_contents);
// No need to emit any event if the WebContents is not available in JS.
if (api_web_contents) {
api_web_contents->OnCreateWindow(target_url, referrer, frame_name,
disposition, raw_features, body);
}
}
return false;
}
void App::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) {
auto adapted_callback = base::AdaptCallbackForRepeating(std::move(callback));
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
bool prevent_default = Emit(
"certificate-error", WebContents::FromOrCreate(isolate, web_contents),
request_url, net::ErrorToString(cert_error), ssl_info.cert,
adapted_callback, is_main_frame_request);
// Deny the certificate by default.
if (!prevent_default)
adapted_callback.Run(content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY);
}
base::OnceClosure App::SelectClientCertificate(
content::BrowserContext* browser_context,
content::WebContents* web_contents,
net::SSLCertRequestInfo* cert_request_info,
net::ClientCertIdentityList identities,
std::unique_ptr<content::ClientCertificateDelegate> delegate) {
std::shared_ptr<content::ClientCertificateDelegate> shared_delegate(
delegate.release());
// Convert the ClientCertIdentityList to a CertificateList
// to avoid changes in the API.
auto client_certs = net::CertificateList();
for (const std::unique_ptr<net::ClientCertIdentity>& identity : identities)
client_certs.emplace_back(identity->certificate());
auto shared_identities =
std::make_shared<net::ClientCertIdentityList>(std::move(identities));
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
bool prevent_default =
Emit("select-client-certificate",
WebContents::FromOrCreate(isolate, web_contents),
cert_request_info->host_and_port.ToString(), std::move(client_certs),
base::BindOnce(&OnClientCertificateSelected, isolate,
shared_delegate, shared_identities));
// Default to first certificate from the platform store.
if (!prevent_default) {
scoped_refptr<net::X509Certificate> cert =
(*shared_identities)[0]->certificate();
net::ClientCertIdentity::SelfOwningAcquirePrivateKey(
std::move((*shared_identities)[0]),
base::BindRepeating(&GotPrivateKey, shared_delegate, std::move(cert)));
}
return base::OnceClosure();
}
void App::OnGpuInfoUpdate() {
Emit("gpu-info-update");
}
void App::OnGpuProcessCrashed() {
Emit("gpu-process-crashed", true);
}
void App::BrowserChildProcessLaunchedAndConnected(
const content::ChildProcessData& data) {
ChildProcessLaunched(data.process_type, data.id, data.GetProcess().Handle(),
data.metrics_name, base::UTF16ToUTF8(data.name));
}
void App::BrowserChildProcessHostDisconnected(
const content::ChildProcessData& data) {
ChildProcessDisconnected(data.id);
}
void App::BrowserChildProcessCrashed(
const content::ChildProcessData& data,
const content::ChildProcessTerminationInfo& info) {
ChildProcessDisconnected(data.id);
BrowserChildProcessCrashedOrKilled(data, info);
}
void App::BrowserChildProcessKilled(
const content::ChildProcessData& data,
const content::ChildProcessTerminationInfo& info) {
ChildProcessDisconnected(data.id);
BrowserChildProcessCrashedOrKilled(data, info);
}
void App::BrowserChildProcessCrashedOrKilled(
const content::ChildProcessData& data,
const content::ChildProcessTerminationInfo& info) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("type", content::GetProcessTypeNameInEnglish(data.process_type));
details.Set("reason", info.status);
details.Set("exitCode", info.exit_code);
details.Set("serviceName", data.metrics_name);
if (!data.name.empty()) {
details.Set("name", data.name);
}
if (data.process_type == content::PROCESS_TYPE_UTILITY) {
base::ProcessId pid = data.GetProcess().Pid();
auto utility_process_wrapper = UtilityProcessWrapper::FromProcessId(pid);
if (utility_process_wrapper)
utility_process_wrapper->Shutdown(info.exit_code);
}
Emit("child-process-gone", details);
}
void App::RenderProcessReady(content::RenderProcessHost* host) {
ChildProcessLaunched(content::PROCESS_TYPE_RENDERER, host->GetID(),
host->GetProcess().Handle());
}
void App::RenderProcessExited(content::RenderProcessHost* host) {
ChildProcessDisconnected(host->GetID());
}
void App::ChildProcessLaunched(int process_type,
int pid,
base::ProcessHandle handle,
const std::string& service_name,
const std::string& name) {
#if BUILDFLAG(IS_MAC)
auto metrics = base::ProcessMetrics::CreateProcessMetrics(
handle, content::BrowserChildProcessHost::GetPortProvider());
#else
auto metrics = base::ProcessMetrics::CreateProcessMetrics(handle);
#endif
app_metrics_[pid] = std::make_unique<electron::ProcessMetric>(
process_type, handle, std::move(metrics), service_name, name);
}
void App::ChildProcessDisconnected(int pid) {
app_metrics_.erase(pid);
}
base::FilePath App::GetAppPath() const {
return app_path_;
}
void App::SetAppPath(const base::FilePath& app_path) {
app_path_ = app_path;
}
#if !BUILDFLAG(IS_MAC)
void App::SetAppLogsPath(gin_helper::ErrorThrower thrower,
absl::optional<base::FilePath> custom_path) {
if (custom_path.has_value()) {
if (!custom_path->IsAbsolute()) {
thrower.ThrowError("Path must be absolute");
return;
}
{
ScopedAllowBlockingForElectron allow_blocking;
base::PathService::Override(DIR_APP_LOGS, custom_path.value());
}
} else {
base::FilePath path;
if (base::PathService::Get(chrome::DIR_USER_DATA, &path)) {
path = path.Append(base::FilePath::FromUTF8Unsafe("logs"));
{
ScopedAllowBlockingForElectron allow_blocking;
base::PathService::Override(DIR_APP_LOGS, path);
}
}
}
}
#endif
// static
bool App::IsPackaged() {
auto env = base::Environment::Create();
if (env->HasVar("ELECTRON_FORCE_IS_PACKAGED"))
return true;
base::FilePath exe_path;
base::PathService::Get(base::FILE_EXE, &exe_path);
base::FilePath::StringType base_name =
base::ToLowerASCII(exe_path.BaseName().value());
#if BUILDFLAG(IS_WIN)
return base_name != FILE_PATH_LITERAL("electron.exe");
#else
return base_name != FILE_PATH_LITERAL("electron");
#endif
}
base::FilePath App::GetPath(gin_helper::ErrorThrower thrower,
const std::string& name) {
base::FilePath path;
int key = GetPathConstant(name);
if (key < 0 || !base::PathService::Get(key, &path))
thrower.ThrowError("Failed to get '" + name + "' path");
return path;
}
void App::SetPath(gin_helper::ErrorThrower thrower,
const std::string& name,
const base::FilePath& path) {
if (!path.IsAbsolute()) {
thrower.ThrowError("Path must be absolute");
return;
}
int key = GetPathConstant(name);
if (key < 0 || !base::PathService::OverrideAndCreateIfNeeded(
key, path, /* is_absolute = */ true, /* create = */ false))
thrower.ThrowError("Failed to set path");
}
void App::SetDesktopName(const std::string& desktop_name) {
#if BUILDFLAG(IS_LINUX)
auto env = base::Environment::Create();
env->SetVar("CHROME_DESKTOP", desktop_name);
#endif
}
std::string App::GetLocale() {
return g_browser_process->GetApplicationLocale();
}
std::string App::GetSystemLocale(gin_helper::ErrorThrower thrower) const {
if (!Browser::Get()->is_ready()) {
thrower.ThrowError(
"app.getSystemLocale() can only be called "
"after app is ready");
return std::string();
}
return static_cast<BrowserProcessImpl*>(g_browser_process)->GetSystemLocale();
}
std::string App::GetLocaleCountryCode() {
std::string region;
#if BUILDFLAG(IS_WIN)
WCHAR locale_name[LOCALE_NAME_MAX_LENGTH] = {0};
if (GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SISO3166CTRYNAME,
(LPWSTR)&locale_name,
sizeof(locale_name) / sizeof(WCHAR)) ||
GetLocaleInfoEx(LOCALE_NAME_SYSTEM_DEFAULT, LOCALE_SISO3166CTRYNAME,
(LPWSTR)&locale_name,
sizeof(locale_name) / sizeof(WCHAR))) {
base::WideToUTF8(locale_name, wcslen(locale_name), ®ion);
}
#elif BUILDFLAG(IS_MAC)
CFLocaleRef locale = CFLocaleCopyCurrent();
CFStringRef value = CFStringRef(
static_cast<CFTypeRef>(CFLocaleGetValue(locale, kCFLocaleCountryCode)));
if (value != nil) {
char temporaryCString[3];
const CFIndex kCStringSize = sizeof(temporaryCString);
if (CFStringGetCString(value, temporaryCString, kCStringSize,
kCFStringEncodingUTF8)) {
region = temporaryCString;
}
}
#else
const char* locale_ptr = setlocale(LC_TIME, nullptr);
if (!locale_ptr)
locale_ptr = setlocale(LC_NUMERIC, nullptr);
if (locale_ptr) {
std::string locale = locale_ptr;
std::string::size_type rpos = locale.find('.');
if (rpos != std::string::npos)
locale = locale.substr(0, rpos);
rpos = locale.find('_');
if (rpos != std::string::npos && rpos + 1 < locale.size())
region = locale.substr(rpos + 1);
}
#endif
return region.size() == 2 ? region : std::string();
}
void App::OnSecondInstance(const base::CommandLine& cmd,
const base::FilePath& cwd,
const std::vector<const uint8_t> additional_data) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Value> data_value =
DeserializeV8Value(isolate, std::move(additional_data));
Emit("second-instance", cmd.argv(), cwd, data_value);
}
bool App::HasSingleInstanceLock() const {
if (process_singleton_)
return true;
return false;
}
bool App::RequestSingleInstanceLock(gin::Arguments* args) {
if (HasSingleInstanceLock())
return true;
std::string program_name = electron::Browser::Get()->GetName();
base::FilePath user_dir;
base::PathService::Get(chrome::DIR_USER_DATA, &user_dir);
// The user_dir may not have been created yet.
base::CreateDirectoryAndGetError(user_dir, nullptr);
auto cb = base::BindRepeating(&App::OnSecondInstance, base::Unretained(this));
blink::CloneableMessage additional_data_message;
args->GetNext(&additional_data_message);
#if BUILDFLAG(IS_WIN)
bool app_is_sandboxed =
IsSandboxEnabled(base::CommandLine::ForCurrentProcess());
process_singleton_ = std::make_unique<ProcessSingleton>(
program_name, user_dir, additional_data_message.encoded_message,
app_is_sandboxed, base::BindRepeating(NotificationCallbackWrapper, cb));
#else
process_singleton_ = std::make_unique<ProcessSingleton>(
user_dir, additional_data_message.encoded_message,
base::BindRepeating(NotificationCallbackWrapper, cb));
#endif
switch (process_singleton_->NotifyOtherProcessOrCreate()) {
case ProcessSingleton::NotifyResult::PROCESS_NONE:
if (content::BrowserThread::IsThreadInitialized(
content::BrowserThread::IO)) {
process_singleton_->StartWatching();
} else {
watch_singleton_socket_on_ready_ = true;
}
return true;
case ProcessSingleton::NotifyResult::LOCK_ERROR:
case ProcessSingleton::NotifyResult::PROFILE_IN_USE:
case ProcessSingleton::NotifyResult::PROCESS_NOTIFIED: {
process_singleton_.reset();
return false;
}
}
}
void App::ReleaseSingleInstanceLock() {
if (process_singleton_) {
process_singleton_->Cleanup();
process_singleton_.reset();
}
}
bool App::Relaunch(gin::Arguments* js_args) {
// Parse parameters.
bool override_argv = false;
base::FilePath exec_path;
relauncher::StringVector args;
gin_helper::Dictionary options;
if (js_args->GetNext(&options)) {
bool has_exec_path = options.Get("execPath", &exec_path);
bool has_args = options.Get("args", &args);
if (has_exec_path || has_args)
override_argv = true;
}
if (!override_argv) {
const relauncher::StringVector& argv =
electron::ElectronCommandLine::argv();
return relauncher::RelaunchApp(argv);
}
relauncher::StringVector argv;
argv.reserve(1 + args.size());
if (exec_path.empty()) {
base::FilePath current_exe_path;
base::PathService::Get(base::FILE_EXE, ¤t_exe_path);
argv.push_back(current_exe_path.value());
} else {
argv.push_back(exec_path.value());
}
argv.insert(argv.end(), args.begin(), args.end());
return relauncher::RelaunchApp(argv);
}
void App::DisableHardwareAcceleration(gin_helper::ErrorThrower thrower) {
if (Browser::Get()->is_ready()) {
thrower.ThrowError(
"app.disableHardwareAcceleration() can only be called "
"before app is ready");
return;
}
if (content::GpuDataManager::Initialized()) {
content::GpuDataManager::GetInstance()->DisableHardwareAcceleration();
} else {
disable_hw_acceleration_ = true;
}
}
void App::DisableDomainBlockingFor3DAPIs(gin_helper::ErrorThrower thrower) {
if (Browser::Get()->is_ready()) {
thrower.ThrowError(
"app.disableDomainBlockingFor3DAPIs() can only be called "
"before app is ready");
return;
}
if (content::GpuDataManager::Initialized()) {
content::GpuDataManagerImpl::GetInstance()
->DisableDomainBlockingFor3DAPIsForTesting();
} else {
disable_domain_blocking_for_3DAPIs_ = true;
}
}
bool App::IsAccessibilitySupportEnabled() {
auto* ax_state = content::BrowserAccessibilityState::GetInstance();
return ax_state->IsAccessibleBrowser();
}
void App::SetAccessibilitySupportEnabled(gin_helper::ErrorThrower thrower,
bool enabled) {
if (!Browser::Get()->is_ready()) {
thrower.ThrowError(
"app.setAccessibilitySupportEnabled() can only be called "
"after app is ready");
return;
}
auto* ax_state = content::BrowserAccessibilityState::GetInstance();
if (enabled) {
ax_state->OnScreenReaderDetected();
} else {
ax_state->DisableAccessibility();
}
Browser::Get()->OnAccessibilitySupportChanged();
}
Browser::LoginItemSettings App::GetLoginItemSettings(gin::Arguments* args) {
Browser::LoginItemSettings options;
args->GetNext(&options);
return Browser::Get()->GetLoginItemSettings(options);
}
#if BUILDFLAG(USE_NSS_CERTS)
void App::ImportCertificate(gin_helper::ErrorThrower thrower,
base::Value options,
net::CompletionOnceCallback callback) {
if (!options.is_dict()) {
thrower.ThrowTypeError("Expected options to be an object");
return;
}
auto* browser_context = ElectronBrowserContext::From("", false);
if (!certificate_manager_model_) {
CertificateManagerModel::Create(
browser_context,
base::BindOnce(&App::OnCertificateManagerModelCreated,
base::Unretained(this), std::move(options),
std::move(callback)));
return;
}
int rv =
ImportIntoCertStore(certificate_manager_model_.get(), std::move(options));
std::move(callback).Run(rv);
}
void App::OnCertificateManagerModelCreated(
base::Value options,
net::CompletionOnceCallback callback,
std::unique_ptr<CertificateManagerModel> model) {
certificate_manager_model_ = std::move(model);
int rv =
ImportIntoCertStore(certificate_manager_model_.get(), std::move(options));
std::move(callback).Run(rv);
}
#endif
#if BUILDFLAG(IS_WIN)
v8::Local<v8::Value> App::GetJumpListSettings() {
JumpList jump_list(Browser::Get()->GetAppUserModelID());
int min_items = 10;
std::vector<JumpListItem> removed_items;
if (jump_list.Begin(&min_items, &removed_items)) {
// We don't actually want to change anything, so abort the transaction.
jump_list.Abort();
} else {
LOG(ERROR) << "Failed to begin Jump List transaction.";
}
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
dict.Set("minItems", min_items);
dict.Set("removedItems", gin::ConvertToV8(isolate, removed_items));
return dict.GetHandle();
}
JumpListResult App::SetJumpList(v8::Local<v8::Value> val,
gin::Arguments* args) {
std::vector<JumpListCategory> categories;
bool delete_jump_list = val->IsNull();
if (!delete_jump_list &&
!gin::ConvertFromV8(args->isolate(), val, &categories)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Argument must be null or an array of categories");
return JumpListResult::kArgumentError;
}
JumpList jump_list(Browser::Get()->GetAppUserModelID());
if (delete_jump_list) {
return jump_list.Delete() ? JumpListResult::kSuccess
: JumpListResult::kGenericError;
}
// Start a transaction that updates the JumpList of this application.
if (!jump_list.Begin())
return JumpListResult::kGenericError;
JumpListResult result = jump_list.AppendCategories(categories);
// AppendCategories may have failed to add some categories, but it's better
// to have something than nothing so try to commit the changes anyway.
if (!jump_list.Commit()) {
LOG(ERROR) << "Failed to commit changes to custom Jump List.";
// It's more useful to return the earlier error code that might give
// some indication as to why the transaction actually failed, so don't
// overwrite it with a "generic error" code here.
if (result == JumpListResult::kSuccess)
result = JumpListResult::kGenericError;
}
return result;
}
#endif // BUILDFLAG(IS_WIN)
v8::Local<v8::Promise> App::GetFileIcon(const base::FilePath& path,
gin::Arguments* args) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<gfx::Image> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
base::FilePath normalized_path = path.NormalizePathSeparators();
IconLoader::IconSize icon_size;
gin_helper::Dictionary options;
if (!args->GetNext(&options)) {
icon_size = IconLoader::IconSize::NORMAL;
} else {
std::string icon_size_string;
options.Get("size", &icon_size_string);
icon_size = GetIconSizeByString(icon_size_string);
}
auto* icon_manager = ElectronBrowserMainParts::Get()->GetIconManager();
gfx::Image* icon =
icon_manager->LookupIconFromFilepath(normalized_path, icon_size, 1.0f);
if (icon) {
promise.Resolve(*icon);
} else {
icon_manager->LoadIcon(
normalized_path, icon_size, 1.0f,
base::BindOnce(&OnIconDataAvailable, std::move(promise)),
&cancelable_task_tracker_);
}
return handle;
}
std::vector<gin_helper::Dictionary> App::GetAppMetrics(v8::Isolate* isolate) {
std::vector<gin_helper::Dictionary> result;
result.reserve(app_metrics_.size());
int processor_count = base::SysInfo::NumberOfProcessors();
for (const auto& process_metric : app_metrics_) {
auto pid_dict = gin_helper::Dictionary::CreateEmpty(isolate);
auto cpu_dict = gin_helper::Dictionary::CreateEmpty(isolate);
cpu_dict.Set(
"percentCPUUsage",
process_metric.second->metrics->GetPlatformIndependentCPUUsage() /
processor_count);
#if !BUILDFLAG(IS_WIN)
cpu_dict.Set("idleWakeupsPerSecond",
process_metric.second->metrics->GetIdleWakeupsPerSecond());
#else
// Chrome's underlying process_metrics.cc will throw a non-fatal warning
// that this method isn't implemented on Windows, so set it to 0 instead
// of calling it
cpu_dict.Set("idleWakeupsPerSecond", 0);
#endif
pid_dict.Set("cpu", cpu_dict);
pid_dict.Set("pid", process_metric.second->process.Pid());
pid_dict.Set("type", content::GetProcessTypeNameInEnglish(
process_metric.second->type));
pid_dict.Set("creationTime",
process_metric.second->process.CreationTime().ToJsTime());
if (!process_metric.second->service_name.empty()) {
pid_dict.Set("serviceName", process_metric.second->service_name);
}
if (!process_metric.second->name.empty()) {
pid_dict.Set("name", process_metric.second->name);
}
#if !BUILDFLAG(IS_LINUX)
auto memory_info = process_metric.second->GetMemoryInfo();
auto memory_dict = gin_helper::Dictionary::CreateEmpty(isolate);
memory_dict.Set("workingSetSize",
static_cast<double>(memory_info.working_set_size >> 10));
memory_dict.Set(
"peakWorkingSetSize",
static_cast<double>(memory_info.peak_working_set_size >> 10));
#if BUILDFLAG(IS_WIN)
memory_dict.Set("privateBytes",
static_cast<double>(memory_info.private_bytes >> 10));
#endif
pid_dict.Set("memory", memory_dict);
#endif
#if BUILDFLAG(IS_MAC)
pid_dict.Set("sandboxed", process_metric.second->IsSandboxed());
#elif BUILDFLAG(IS_WIN)
auto integrity_level = process_metric.second->GetIntegrityLevel();
auto sandboxed = ProcessMetric::IsSandboxed(integrity_level);
pid_dict.Set("integrityLevel", integrity_level);
pid_dict.Set("sandboxed", sandboxed);
#endif
result.push_back(pid_dict);
}
return result;
}
v8::Local<v8::Value> App::GetGPUFeatureStatus(v8::Isolate* isolate) {
return gin::ConvertToV8(isolate, content::GetFeatureStatus());
}
v8::Local<v8::Promise> App::GetGPUInfo(v8::Isolate* isolate,
const std::string& info_type) {
auto* const gpu_data_manager = content::GpuDataManagerImpl::GetInstance();
gin_helper::Promise<base::Value> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (info_type != "basic" && info_type != "complete") {
promise.RejectWithErrorMessage(
"Invalid info type. Use 'basic' or 'complete'");
return handle;
}
std::string reason;
if (!gpu_data_manager->GpuAccessAllowed(&reason)) {
promise.RejectWithErrorMessage("GPU access not allowed. Reason: " + reason);
return handle;
}
auto* const info_mgr = GPUInfoManager::GetInstance();
if (info_type == "complete") {
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
info_mgr->FetchCompleteInfo(std::move(promise));
#else
info_mgr->FetchBasicInfo(std::move(promise));
#endif
} else /* (info_type == "basic") */ {
info_mgr->FetchBasicInfo(std::move(promise));
}
return handle;
}
static void RemoveNoSandboxSwitch(base::CommandLine* command_line) {
if (command_line->HasSwitch(sandbox::policy::switches::kNoSandbox)) {
const base::CommandLine::CharType* noSandboxArg =
FILE_PATH_LITERAL("--no-sandbox");
base::CommandLine::StringVector modified_command_line;
for (auto& arg : command_line->argv()) {
if (arg.compare(noSandboxArg) != 0) {
modified_command_line.push_back(arg);
}
}
command_line->InitFromArgv(modified_command_line);
}
}
void App::EnableSandbox(gin_helper::ErrorThrower thrower) {
if (Browser::Get()->is_ready()) {
thrower.ThrowError(
"app.enableSandbox() can only be called "
"before app is ready");
return;
}
auto* command_line = base::CommandLine::ForCurrentProcess();
RemoveNoSandboxSwitch(command_line);
command_line->AppendSwitch(switches::kEnableSandbox);
}
void App::SetUserAgentFallback(const std::string& user_agent) {
ElectronBrowserClient::Get()->SetUserAgent(user_agent);
}
#if BUILDFLAG(IS_WIN)
bool App::IsRunningUnderARM64Translation() const {
return base::win::OSInfo::IsRunningEmulatedOnArm64();
}
#endif
std::string App::GetUserAgentFallback() {
return ElectronBrowserClient::Get()->GetUserAgent();
}
#if BUILDFLAG(IS_MAC)
bool App::MoveToApplicationsFolder(gin_helper::ErrorThrower thrower,
gin::Arguments* args) {
return ElectronBundleMover::Move(thrower, args);
}
bool App::IsInApplicationsFolder() {
return ElectronBundleMover::IsCurrentAppInApplicationsFolder();
}
int DockBounce(gin::Arguments* args) {
int request_id = -1;
std::string type = "informational";
args->GetNext(&type);
if (type == "critical")
request_id = Browser::Get()->DockBounce(Browser::BounceType::kCritical);
else if (type == "informational")
request_id =
Browser::Get()->DockBounce(Browser::BounceType::kInformational);
return request_id;
}
void DockSetMenu(electron::api::Menu* menu) {
Browser::Get()->DockSetMenu(menu->model());
}
v8::Local<v8::Value> App::GetDockAPI(v8::Isolate* isolate) {
if (dock_.IsEmpty()) {
// Initialize the Dock API, the methods are bound to "dock" which exists
// for the lifetime of "app"
auto browser = base::Unretained(Browser::Get());
auto dock_obj = gin_helper::Dictionary::CreateEmpty(isolate);
dock_obj.SetMethod("bounce", &DockBounce);
dock_obj.SetMethod(
"cancelBounce",
base::BindRepeating(&Browser::DockCancelBounce, browser));
dock_obj.SetMethod(
"downloadFinished",
base::BindRepeating(&Browser::DockDownloadFinished, browser));
dock_obj.SetMethod(
"setBadge", base::BindRepeating(&Browser::DockSetBadgeText, browser));
dock_obj.SetMethod(
"getBadge", base::BindRepeating(&Browser::DockGetBadgeText, browser));
dock_obj.SetMethod("hide",
base::BindRepeating(&Browser::DockHide, browser));
dock_obj.SetMethod("show",
base::BindRepeating(&Browser::DockShow, browser));
dock_obj.SetMethod("isVisible",
base::BindRepeating(&Browser::DockIsVisible, browser));
dock_obj.SetMethod("setMenu", &DockSetMenu);
dock_obj.SetMethod("setIcon",
base::BindRepeating(&Browser::DockSetIcon, browser));
dock_.Reset(isolate, dock_obj.GetHandle());
}
return v8::Local<v8::Value>::New(isolate, dock_);
}
#endif
void ConfigureHostResolver(v8::Isolate* isolate,
const gin_helper::Dictionary& opts) {
gin_helper::ErrorThrower thrower(isolate);
if (!Browser::Get()->is_ready()) {
thrower.ThrowError(
"configureHostResolver cannot be called before the app is ready");
return;
}
net::SecureDnsMode secure_dns_mode = net::SecureDnsMode::kOff;
std::string default_doh_templates;
if (base::FeatureList::IsEnabled(features::kDnsOverHttps)) {
if (features::kDnsOverHttpsFallbackParam.Get()) {
secure_dns_mode = net::SecureDnsMode::kAutomatic;
} else {
secure_dns_mode = net::SecureDnsMode::kSecure;
}
default_doh_templates = features::kDnsOverHttpsTemplatesParam.Get();
}
net::DnsOverHttpsConfig doh_config;
if (!default_doh_templates.empty() &&
secure_dns_mode != net::SecureDnsMode::kOff) {
auto maybe_doh_config =
net::DnsOverHttpsConfig::FromString(default_doh_templates);
if (maybe_doh_config.has_value())
doh_config = maybe_doh_config.value();
}
bool enable_built_in_resolver =
base::FeatureList::IsEnabled(features::kAsyncDns);
bool additional_dns_query_types_enabled = true;
if (opts.Has("enableBuiltInResolver") &&
!opts.Get("enableBuiltInResolver", &enable_built_in_resolver)) {
thrower.ThrowTypeError("enableBuiltInResolver must be a boolean");
return;
}
if (opts.Has("secureDnsMode") &&
!opts.Get("secureDnsMode", &secure_dns_mode)) {
thrower.ThrowTypeError(
"secureDnsMode must be one of: off, automatic, secure");
return;
}
std::vector<std::string> secure_dns_server_strings;
if (opts.Has("secureDnsServers")) {
if (!opts.Get("secureDnsServers", &secure_dns_server_strings)) {
thrower.ThrowTypeError("secureDnsServers must be an array of strings");
return;
}
// Validate individual server templates prior to batch-assigning to
// doh_config.
std::vector<net::DnsOverHttpsServerConfig> servers;
for (const std::string& server_template : secure_dns_server_strings) {
absl::optional<net::DnsOverHttpsServerConfig> server_config =
net::DnsOverHttpsServerConfig::FromString(server_template);
if (!server_config.has_value()) {
thrower.ThrowTypeError(std::string("not a valid DoH template: ") +
server_template);
return;
}
servers.push_back(*server_config);
}
doh_config = net::DnsOverHttpsConfig(std::move(servers));
}
if (opts.Has("enableAdditionalDnsQueryTypes") &&
!opts.Get("enableAdditionalDnsQueryTypes",
&additional_dns_query_types_enabled)) {
thrower.ThrowTypeError("enableAdditionalDnsQueryTypes must be a boolean");
return;
}
// Configure the stub resolver. This must be done after the system
// NetworkContext is created, but before anything has the chance to use it.
content::GetNetworkService()->ConfigureStubHostResolver(
enable_built_in_resolver, secure_dns_mode, doh_config,
additional_dns_query_types_enabled);
}
// static
App* App::Get() {
static base::NoDestructor<App> app;
return app.get();
}
// static
gin::Handle<App> App::Create(v8::Isolate* isolate) {
return gin::CreateHandle(isolate, Get());
}
gin::ObjectTemplateBuilder App::GetObjectTemplateBuilder(v8::Isolate* isolate) {
auto browser = base::Unretained(Browser::Get());
return gin_helper::EventEmitterMixin<App>::GetObjectTemplateBuilder(isolate)
.SetMethod("quit", base::BindRepeating(&Browser::Quit, browser))
.SetMethod("exit", base::BindRepeating(&Browser::Exit, browser))
.SetMethod("focus", base::BindRepeating(&Browser::Focus, browser))
.SetMethod("getVersion",
base::BindRepeating(&Browser::GetVersion, browser))
.SetMethod("setVersion",
base::BindRepeating(&Browser::SetVersion, browser))
.SetMethod("getName", base::BindRepeating(&Browser::GetName, browser))
.SetMethod("setName", base::BindRepeating(&Browser::SetName, browser))
.SetMethod("isReady", base::BindRepeating(&Browser::is_ready, browser))
.SetMethod("whenReady", base::BindRepeating(&Browser::WhenReady, browser))
.SetMethod("addRecentDocument",
base::BindRepeating(&Browser::AddRecentDocument, browser))
.SetMethod("clearRecentDocuments",
base::BindRepeating(&Browser::ClearRecentDocuments, browser))
#if BUILDFLAG(IS_WIN)
.SetMethod("setAppUserModelId",
base::BindRepeating(&Browser::SetAppUserModelID, browser))
#endif
.SetMethod(
"isDefaultProtocolClient",
base::BindRepeating(&Browser::IsDefaultProtocolClient, browser))
.SetMethod(
"setAsDefaultProtocolClient",
base::BindRepeating(&Browser::SetAsDefaultProtocolClient, browser))
.SetMethod(
"removeAsDefaultProtocolClient",
base::BindRepeating(&Browser::RemoveAsDefaultProtocolClient, browser))
#if !BUILDFLAG(IS_LINUX)
.SetMethod(
"getApplicationInfoForProtocol",
base::BindRepeating(&Browser::GetApplicationInfoForProtocol, browser))
#endif
.SetMethod(
"getApplicationNameForProtocol",
base::BindRepeating(&Browser::GetApplicationNameForProtocol, browser))
.SetMethod("setBadgeCount",
base::BindRepeating(&Browser::SetBadgeCount, browser))
.SetMethod("getBadgeCount",
base::BindRepeating(&Browser::GetBadgeCount, browser))
.SetMethod("getLoginItemSettings", &App::GetLoginItemSettings)
.SetMethod("setLoginItemSettings",
base::BindRepeating(&Browser::SetLoginItemSettings, browser))
.SetMethod("isEmojiPanelSupported",
base::BindRepeating(&Browser::IsEmojiPanelSupported, browser))
#if BUILDFLAG(IS_MAC)
.SetMethod("hide", base::BindRepeating(&Browser::Hide, browser))
.SetMethod("isHidden", base::BindRepeating(&Browser::IsHidden, browser))
.SetMethod("show", base::BindRepeating(&Browser::Show, browser))
.SetMethod("setUserActivity",
base::BindRepeating(&Browser::SetUserActivity, browser))
.SetMethod("getCurrentActivityType",
base::BindRepeating(&Browser::GetCurrentActivityType, browser))
.SetMethod(
"invalidateCurrentActivity",
base::BindRepeating(&Browser::InvalidateCurrentActivity, browser))
.SetMethod("resignCurrentActivity",
base::BindRepeating(&Browser::ResignCurrentActivity, browser))
.SetMethod("updateCurrentActivity",
base::BindRepeating(&Browser::UpdateCurrentActivity, browser))
.SetMethod("moveToApplicationsFolder", &App::MoveToApplicationsFolder)
.SetMethod("isInApplicationsFolder", &App::IsInApplicationsFolder)
.SetMethod("setActivationPolicy", &App::SetActivationPolicy)
#endif
.SetMethod("setAboutPanelOptions",
base::BindRepeating(&Browser::SetAboutPanelOptions, browser))
.SetMethod("showAboutPanel",
base::BindRepeating(&Browser::ShowAboutPanel, browser))
#if BUILDFLAG(IS_MAC)
.SetMethod(
"isSecureKeyboardEntryEnabled",
base::BindRepeating(&Browser::IsSecureKeyboardEntryEnabled, browser))
.SetMethod(
"setSecureKeyboardEntryEnabled",
base::BindRepeating(&Browser::SetSecureKeyboardEntryEnabled, browser))
#endif
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
.SetMethod("showEmojiPanel",
base::BindRepeating(&Browser::ShowEmojiPanel, browser))
#endif
#if BUILDFLAG(IS_WIN)
.SetMethod("setUserTasks",
base::BindRepeating(&Browser::SetUserTasks, browser))
.SetMethod("getJumpListSettings", &App::GetJumpListSettings)
.SetMethod("setJumpList", &App::SetJumpList)
#endif
#if BUILDFLAG(IS_LINUX)
.SetMethod("isUnityRunning",
base::BindRepeating(&Browser::IsUnityRunning, browser))
#endif
.SetProperty("isPackaged", &App::IsPackaged)
.SetMethod("setAppPath", &App::SetAppPath)
.SetMethod("getAppPath", &App::GetAppPath)
.SetMethod("setPath", &App::SetPath)
.SetMethod("getPath", &App::GetPath)
.SetMethod("setAppLogsPath", &App::SetAppLogsPath)
.SetMethod("setDesktopName", &App::SetDesktopName)
.SetMethod("getLocale", &App::GetLocale)
.SetMethod("getPreferredSystemLanguages", &GetPreferredLanguages)
.SetMethod("getSystemLocale", &App::GetSystemLocale)
.SetMethod("getLocaleCountryCode", &App::GetLocaleCountryCode)
#if BUILDFLAG(USE_NSS_CERTS)
.SetMethod("importCertificate", &App::ImportCertificate)
#endif
.SetMethod("hasSingleInstanceLock", &App::HasSingleInstanceLock)
.SetMethod("requestSingleInstanceLock", &App::RequestSingleInstanceLock)
.SetMethod("releaseSingleInstanceLock", &App::ReleaseSingleInstanceLock)
.SetMethod("relaunch", &App::Relaunch)
.SetMethod("isAccessibilitySupportEnabled",
&App::IsAccessibilitySupportEnabled)
.SetMethod("setAccessibilitySupportEnabled",
&App::SetAccessibilitySupportEnabled)
.SetMethod("disableHardwareAcceleration",
&App::DisableHardwareAcceleration)
.SetMethod("disableDomainBlockingFor3DAPIs",
&App::DisableDomainBlockingFor3DAPIs)
.SetMethod("getFileIcon", &App::GetFileIcon)
.SetMethod("getAppMetrics", &App::GetAppMetrics)
.SetMethod("getGPUFeatureStatus", &App::GetGPUFeatureStatus)
.SetMethod("getGPUInfo", &App::GetGPUInfo)
#if IS_MAS_BUILD()
.SetMethod("startAccessingSecurityScopedResource",
&App::StartAccessingSecurityScopedResource)
#endif
#if BUILDFLAG(IS_MAC)
.SetProperty("dock", &App::GetDockAPI)
#endif
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
.SetProperty("runningUnderARM64Translation",
&App::IsRunningUnderARM64Translation)
#endif
.SetProperty("userAgentFallback", &App::GetUserAgentFallback,
&App::SetUserAgentFallback)
.SetMethod("configureHostResolver", &ConfigureHostResolver)
.SetMethod("enableSandbox", &App::EnableSandbox);
}
const char* App::GetTypeName() {
return "App";
}
} // namespace electron::api
namespace {
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("app", electron::api::App::Create(isolate));
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_app, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 37,560 |
[Bug]: Open at login with setLoginItemSettings in MAS build is not working
|
### 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
16.0.6
### What operating system are you using?
macOS
### Operating System Version
Version 13.2 (22D49)
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Setting app to open at login with setLoginItemSettings api should work both locally and with MAS build.
Locally the app is added to login items but when i build it for MAS this doesn't work.
### Actual Behavior
Setting app to open at login with setLoginItemSettings api works locally but doesn't work in MAS build.
In MAS build the app is not added to login items.
<img width="477" alt="image" src="https://user-images.githubusercontent.com/17458685/224576455-a9145dfc-7121-4097-9fe4-a472f0c2ead4.png">
### Testcase Gist URL
_No response_
### Additional Information
According to docs https://www.electronjs.org/docs/latest/api/app#appsetloginitemsettingssettings-macos-windows setting login item in MAS build should work by using the following API
```js
app.setLoginItemSettings({
openAtLogin: openAtLogin,
})
```
In the docs on limitations of MAS build there is no mention of any limitation of using above API https://www.electronjs.org/docs/latest/tutorial/mac-app-store-submission-guide#limitations-of-mas-build
Here is possible related issue and PRs:
- https://github.com/electron/electron/issues/7312
- https://github.com/electron/electron/pull/11144
- https://github.com/electron/electron/pull/10856
|
https://github.com/electron/electron/issues/37560
|
https://github.com/electron/electron/pull/37244
|
6d0d350e138494cd68dd3d4fa73b2719da4575bf
|
f7b1c75c72a8dcab4157408f92bd3771606d8029
| 2023-03-12T22:11:32Z |
c++
| 2023-10-16T16:25:11Z |
shell/browser/browser.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_BROWSER_H_
#define ELECTRON_SHELL_BROWSER_BROWSER_H_
#include <memory>
#include <string>
#include <vector>
#include "base/compiler_specific.h"
#include "base/observer_list.h"
#include "base/task/cancelable_task_tracker.h"
#include "base/values.h"
#include "gin/dictionary.h"
#include "shell/browser/browser_observer.h"
#include "shell/browser/window_list_observer.h"
#include "shell/common/gin_helper/promise.h"
#if BUILDFLAG(IS_WIN)
#include <windows.h>
#include "base/files/file_path.h"
#include "shell/browser/ui/win/taskbar_host.h"
#endif
#if BUILDFLAG(IS_MAC)
#include "ui/base/cocoa/secure_password_input.h"
#endif
namespace base {
class FilePath;
}
namespace gin_helper {
class Arguments;
}
namespace electron {
class ElectronMenuModel;
// This class is used for control application-wide operations.
class Browser : public WindowListObserver {
public:
Browser();
~Browser() override;
// disable copy
Browser(const Browser&) = delete;
Browser& operator=(const Browser&) = delete;
static Browser* Get();
// Try to close all windows and quit the application.
void Quit();
// Exit the application immediately and set exit code.
void Exit(gin::Arguments* args);
// Cleanup everything and shutdown the application gracefully.
void Shutdown();
// Focus the application.
void Focus(gin::Arguments* args);
// Returns the version of the executable (or bundle).
std::string GetVersion() const;
// Overrides the application version.
void SetVersion(const std::string& version);
// Returns the application's name, default is just Electron.
std::string GetName() const;
// Overrides the application name.
void SetName(const std::string& name);
// Add the |path| to recent documents list.
void AddRecentDocument(const base::FilePath& path);
// Clear the recent documents list.
void ClearRecentDocuments();
#if BUILDFLAG(IS_WIN)
// Set the application user model ID.
void SetAppUserModelID(const std::wstring& name);
#endif
// Remove the default protocol handler registry key
bool RemoveAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args);
// Set as default handler for a protocol.
bool SetAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args);
// Query the current state of default handler for a protocol.
bool IsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args);
std::u16string GetApplicationNameForProtocol(const GURL& url);
#if !BUILDFLAG(IS_LINUX)
// get the name, icon and path for an application
v8::Local<v8::Promise> GetApplicationInfoForProtocol(v8::Isolate* isolate,
const GURL& url);
#endif
// Set/Get the badge count.
bool SetBadgeCount(absl::optional<int> count);
int GetBadgeCount();
#if BUILDFLAG(IS_WIN)
struct LaunchItem {
std::wstring name;
std::wstring path;
std::wstring scope;
std::vector<std::wstring> args;
bool enabled = true;
LaunchItem();
~LaunchItem();
LaunchItem(const LaunchItem&);
};
#endif
// Set/Get the login item settings of the app
struct LoginItemSettings {
bool open_at_login = false;
bool open_as_hidden = false;
bool restore_state = false;
bool opened_at_login = false;
bool opened_as_hidden = false;
std::u16string path;
std::vector<std::u16string> args;
#if BUILDFLAG(IS_WIN)
// used in browser::setLoginItemSettings
bool enabled = true;
std::wstring name;
// used in browser::getLoginItemSettings
bool executable_will_launch_at_login = false;
std::vector<LaunchItem> launch_items;
#endif
LoginItemSettings();
~LoginItemSettings();
LoginItemSettings(const LoginItemSettings&);
};
void SetLoginItemSettings(LoginItemSettings settings);
LoginItemSettings GetLoginItemSettings(const LoginItemSettings& options);
#if BUILDFLAG(IS_MAC)
// Set the handler which decides whether to shutdown.
void SetShutdownHandler(base::RepeatingCallback<bool()> handler);
// Hide the application.
void Hide();
bool IsHidden();
// Show the application.
void Show();
// Creates an activity and sets it as the one currently in use.
void SetUserActivity(const std::string& type,
base::Value::Dict user_info,
gin::Arguments* args);
// Returns the type name of the current user activity.
std::string GetCurrentActivityType();
// Invalidates an activity and marks it as no longer eligible for
// continuation
void InvalidateCurrentActivity();
// Marks this activity object as inactive without invalidating it.
void ResignCurrentActivity();
// Updates the current user activity
void UpdateCurrentActivity(const std::string& type,
base::Value::Dict user_info);
// Indicates that an user activity is about to be resumed.
bool WillContinueUserActivity(const std::string& type);
// Indicates a failure to resume a Handoff activity.
void DidFailToContinueUserActivity(const std::string& type,
const std::string& error);
// Resumes an activity via hand-off.
bool ContinueUserActivity(const std::string& type,
base::Value::Dict user_info,
base::Value::Dict details);
// Indicates that an activity was continued on another device.
void UserActivityWasContinued(const std::string& type,
base::Value::Dict user_info);
// Gives an opportunity to update the Handoff payload.
bool UpdateUserActivityState(const std::string& type,
base::Value::Dict user_info);
void ApplyForcedRTL();
// Bounce the dock icon.
enum class BounceType {
kCritical = 0, // NSCriticalRequest
kInformational = 10, // NSInformationalRequest
};
int DockBounce(BounceType type);
void DockCancelBounce(int request_id);
// Bounce the Downloads stack.
void DockDownloadFinished(const std::string& filePath);
// Set/Get dock's badge text.
void DockSetBadgeText(const std::string& label);
std::string DockGetBadgeText();
// Hide/Show dock.
void DockHide();
v8::Local<v8::Promise> DockShow(v8::Isolate* isolate);
bool DockIsVisible();
// Set docks' menu.
void DockSetMenu(ElectronMenuModel* model);
// Set docks' icon.
void DockSetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon);
#endif // BUILDFLAG(IS_MAC)
void ShowAboutPanel();
void SetAboutPanelOptions(base::Value::Dict options);
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
void ShowEmojiPanel();
#endif
#if BUILDFLAG(IS_WIN)
struct UserTask {
base::FilePath program;
std::wstring arguments;
std::wstring title;
std::wstring description;
base::FilePath working_dir;
base::FilePath icon_path;
int icon_index;
UserTask();
UserTask(const UserTask&);
~UserTask();
};
// Add a custom task to jump list.
bool SetUserTasks(const std::vector<UserTask>& tasks);
// Returns the application user model ID, if there isn't one, then create
// one from app's name.
// The returned string managed by Browser, and should not be modified.
PCWSTR GetAppUserModelID();
#endif // BUILDFLAG(IS_WIN)
#if BUILDFLAG(IS_LINUX)
// Whether Unity launcher is running.
bool IsUnityRunning();
#endif // BUILDFLAG(IS_LINUX)
// Tell the application to open a file.
bool OpenFile(const std::string& file_path);
// Tell the application to open a url.
void OpenURL(const std::string& url);
#if BUILDFLAG(IS_MAC)
// Tell the application to create a new window for a tab.
void NewWindowForTab();
// Indicate that the app is now active.
void DidBecomeActive();
// Indicate that the app is no longer active and doesnβt have focus.
void DidResignActive();
#endif // BUILDFLAG(IS_MAC)
// Tell the application that application is activated with visible/invisible
// windows.
void Activate(bool has_visible_windows);
bool IsEmojiPanelSupported();
// Tell the application the loading has been done.
void WillFinishLaunching();
void DidFinishLaunching(base::Value::Dict launch_info);
void OnAccessibilitySupportChanged();
void PreMainMessageLoopRun();
void PreCreateThreads();
// Stores the supplied |quit_closure|, to be run when the last Browser
// instance is destroyed.
void SetMainMessageLoopQuitClosure(base::OnceClosure quit_closure);
void AddObserver(BrowserObserver* obs) { observers_.AddObserver(obs); }
void RemoveObserver(BrowserObserver* obs) { observers_.RemoveObserver(obs); }
#if BUILDFLAG(IS_MAC)
// Returns whether secure input is enabled
bool IsSecureKeyboardEntryEnabled();
void SetSecureKeyboardEntryEnabled(bool enabled);
#endif
bool is_shutting_down() const { return is_shutdown_; }
bool is_quitting() const { return is_quitting_; }
bool is_ready() const { return is_ready_; }
v8::Local<v8::Value> WhenReady(v8::Isolate* isolate);
protected:
// Returns the version of application bundle or executable file.
std::string GetExecutableFileVersion() const;
// Returns the name of application bundle or executable file.
std::string GetExecutableFileProductName() const;
// Send the will-quit message and then shutdown the application.
void NotifyAndShutdown();
// Send the before-quit message and start closing windows.
bool HandleBeforeQuit();
bool is_quitting_ = false;
private:
// WindowListObserver implementations:
void OnWindowCloseCancelled(NativeWindow* window) override;
void OnWindowAllClosed() override;
// Observers of the browser.
base::ObserverList<BrowserObserver> observers_;
// Tracks tasks requesting file icons.
base::CancelableTaskTracker cancelable_task_tracker_;
// Whether `app.exit()` has been called
bool is_exiting_ = false;
// Whether "ready" event has been emitted.
bool is_ready_ = false;
// The browser is being shutdown.
bool is_shutdown_ = false;
// Null until/unless the default main message loop is running.
base::OnceClosure quit_main_message_loop_;
int badge_count_ = 0;
std::unique_ptr<gin_helper::Promise<void>> ready_promise_;
#if BUILDFLAG(IS_MAC)
std::unique_ptr<ui::ScopedPasswordInputEnabler> password_input_enabler_;
base::Time last_dock_show_;
#endif
base::Value::Dict about_panel_options_;
#if BUILDFLAG(IS_WIN)
void UpdateBadgeContents(HWND hwnd,
const absl::optional<std::string>& badge_content,
const std::string& badge_alt_string);
// In charge of running taskbar related APIs.
TaskbarHost taskbar_host_;
#endif
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_BROWSER_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 37,560 |
[Bug]: Open at login with setLoginItemSettings in MAS build is not working
|
### 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
16.0.6
### What operating system are you using?
macOS
### Operating System Version
Version 13.2 (22D49)
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Setting app to open at login with setLoginItemSettings api should work both locally and with MAS build.
Locally the app is added to login items but when i build it for MAS this doesn't work.
### Actual Behavior
Setting app to open at login with setLoginItemSettings api works locally but doesn't work in MAS build.
In MAS build the app is not added to login items.
<img width="477" alt="image" src="https://user-images.githubusercontent.com/17458685/224576455-a9145dfc-7121-4097-9fe4-a472f0c2ead4.png">
### Testcase Gist URL
_No response_
### Additional Information
According to docs https://www.electronjs.org/docs/latest/api/app#appsetloginitemsettingssettings-macos-windows setting login item in MAS build should work by using the following API
```js
app.setLoginItemSettings({
openAtLogin: openAtLogin,
})
```
In the docs on limitations of MAS build there is no mention of any limitation of using above API https://www.electronjs.org/docs/latest/tutorial/mac-app-store-submission-guide#limitations-of-mas-build
Here is possible related issue and PRs:
- https://github.com/electron/electron/issues/7312
- https://github.com/electron/electron/pull/11144
- https://github.com/electron/electron/pull/10856
|
https://github.com/electron/electron/issues/37560
|
https://github.com/electron/electron/pull/37244
|
6d0d350e138494cd68dd3d4fa73b2719da4575bf
|
f7b1c75c72a8dcab4157408f92bd3771606d8029
| 2023-03-12T22:11:32Z |
c++
| 2023-10-16T16:25:11Z |
shell/browser/browser_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/browser.h"
#include <memory>
#include <string>
#include <utility>
#include "base/apple/bridging.h"
#include "base/apple/bundle_locations.h"
#include "base/apple/scoped_cftyperef.h"
#include "base/i18n/rtl.h"
#include "base/mac/mac_util.h"
#include "base/mac/mac_util.mm"
#include "base/strings/string_number_conversions.h"
#include "base/strings/sys_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "net/base/mac/url_conversions.h"
#include "shell/browser/badging/badge_manager.h"
#include "shell/browser/mac/dict_util.h"
#include "shell/browser/mac/electron_application.h"
#include "shell/browser/mac/electron_application_delegate.h"
#include "shell/browser/native_window.h"
#include "shell/browser/window_list.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/application_info.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_helper/arguments.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/platform_util.h"
#include "ui/base/resource/resource_scale_factor.h"
#include "ui/gfx/image/image.h"
#include "url/gurl.h"
namespace electron {
namespace {
NSString* GetAppPathForProtocol(const GURL& url) {
NSURL* ns_url = [NSURL
URLWithString:base::SysUTF8ToNSString(url.possibly_invalid_spec())];
base::apple::ScopedCFTypeRef<CFErrorRef> out_err;
base::apple::ScopedCFTypeRef<CFURLRef> openingApp(
LSCopyDefaultApplicationURLForURL(base::apple::NSToCFPtrCast(ns_url),
kLSRolesAll, out_err.InitializeInto()));
if (out_err) {
// likely kLSApplicationNotFoundErr
return nullptr;
}
NSString* app_path = [base::apple::CFToNSPtrCast(openingApp.get()) path];
return app_path;
}
gfx::Image GetApplicationIconForProtocol(NSString* _Nonnull app_path) {
NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile:app_path];
gfx::Image icon(image);
return icon;
}
std::u16string GetAppDisplayNameForProtocol(NSString* app_path) {
NSString* app_display_name =
[[NSFileManager defaultManager] displayNameAtPath:app_path];
return base::SysNSStringToUTF16(app_display_name);
}
#if !IS_MAS_BUILD()
bool CheckLoginItemStatus(bool* is_hidden) {
base::mac::LoginItemsFileList login_items;
if (!login_items.Initialize())
return false;
base::apple::ScopedCFTypeRef<LSSharedFileListItemRef> item(
login_items.GetLoginItemForMainApp());
if (!item.get())
return false;
if (is_hidden)
*is_hidden = base::mac::IsHiddenLoginItem(item);
return true;
}
#endif
} // namespace
v8::Local<v8::Promise> Browser::GetApplicationInfoForProtocol(
v8::Isolate* isolate,
const GURL& url) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
NSString* ns_app_path = GetAppPathForProtocol(url);
if (!ns_app_path) {
promise.RejectWithErrorMessage(
"Unable to retrieve installation path to app");
return handle;
}
std::u16string app_path = base::SysNSStringToUTF16(ns_app_path);
std::u16string app_display_name = GetAppDisplayNameForProtocol(ns_app_path);
gfx::Image app_icon = GetApplicationIconForProtocol(ns_app_path);
dict.Set("name", app_display_name);
dict.Set("path", app_path);
dict.Set("icon", app_icon);
promise.Resolve(dict);
return handle;
}
void Browser::SetShutdownHandler(base::RepeatingCallback<bool()> handler) {
[[AtomApplication sharedApplication] setShutdownHandler:std::move(handler)];
}
void Browser::Focus(gin::Arguments* args) {
gin_helper::Dictionary opts;
bool steal_focus = false;
if (args->GetNext(&opts)) {
gin_helper::ErrorThrower thrower(args->isolate());
if (!opts.Get("steal", &steal_focus)) {
thrower.ThrowError(
"Expected options object to contain a 'steal' boolean property");
return;
}
}
[[AtomApplication sharedApplication] activateIgnoringOtherApps:steal_focus];
}
void Browser::Hide() {
[[AtomApplication sharedApplication] hide:nil];
}
bool Browser::IsHidden() {
return [[AtomApplication sharedApplication] isHidden];
}
void Browser::Show() {
[[AtomApplication sharedApplication] unhide:nil];
}
void Browser::AddRecentDocument(const base::FilePath& path) {
NSString* path_string = base::apple::FilePathToNSString(path);
if (!path_string)
return;
NSURL* u = [NSURL fileURLWithPath:path_string];
if (!u)
return;
[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:u];
}
void Browser::ClearRecentDocuments() {
[[NSDocumentController sharedDocumentController] clearRecentDocuments:nil];
}
bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args) {
NSString* identifier = [base::apple::MainBundle() bundleIdentifier];
if (!identifier)
return false;
if (!Browser::IsDefaultProtocolClient(protocol, args))
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
CFStringRef protocol_cf = base::apple::NSToCFPtrCast(protocol_ns);
// TODO(codebytere): Use -[NSWorkspace URLForApplicationToOpenURL:] instead
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
CFArrayRef bundleList = LSCopyAllHandlersForURLScheme(protocol_cf);
#pragma clang diagnostic pop
if (!bundleList) {
return false;
}
// On macOS, we can't query the default, but the handlers list seems to put
// Apple's defaults first, so we'll use the first option that isn't our bundle
CFStringRef other = nil;
for (CFIndex i = 0; i < CFArrayGetCount(bundleList); ++i) {
other =
base::apple::CFCast<CFStringRef>(CFArrayGetValueAtIndex(bundleList, i));
if (![identifier isEqualToString:(__bridge NSString*)other]) {
break;
}
}
// No other app was found set it to none instead of setting it back to itself.
if ([identifier isEqualToString:(__bridge NSString*)other]) {
other = base::apple::NSToCFPtrCast(@"None");
}
OSStatus return_code = LSSetDefaultHandlerForURLScheme(protocol_cf, other);
return return_code == noErr;
}
bool Browser::SetAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args) {
if (protocol.empty())
return false;
NSString* identifier = [base::apple::MainBundle() bundleIdentifier];
if (!identifier)
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
OSStatus return_code =
LSSetDefaultHandlerForURLScheme(base::apple::NSToCFPtrCast(protocol_ns),
base::apple::NSToCFPtrCast(identifier));
return return_code == noErr;
}
bool Browser::IsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args) {
if (protocol.empty())
return false;
NSString* identifier = [base::apple::MainBundle() bundleIdentifier];
if (!identifier)
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
// TODO(codebytere): Use -[NSWorkspace URLForApplicationToOpenURL:] instead
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
base::apple::ScopedCFTypeRef<CFStringRef> bundleId(
LSCopyDefaultHandlerForURLScheme(
base::apple::NSToCFPtrCast(protocol_ns)));
#pragma clang diagnostic pop
if (!bundleId)
return false;
// Ensure the comparison is case-insensitive
// as LS does not persist the case of the bundle id.
NSComparisonResult result =
[base::apple::CFToNSPtrCast(bundleId) caseInsensitiveCompare:identifier];
return result == NSOrderedSame;
}
std::u16string Browser::GetApplicationNameForProtocol(const GURL& url) {
NSString* app_path = GetAppPathForProtocol(url);
if (!app_path) {
return std::u16string();
}
std::u16string app_display_name = GetAppDisplayNameForProtocol(app_path);
return app_display_name;
}
bool Browser::SetBadgeCount(absl::optional<int> count) {
DockSetBadgeText(!count.has_value() || count.value() != 0
? badging::BadgeManager::GetBadgeString(count)
: "");
if (count.has_value()) {
badge_count_ = count.value();
} else {
badge_count_ = 0;
}
return true;
}
void Browser::SetUserActivity(const std::string& type,
base::Value::Dict user_info,
gin::Arguments* args) {
std::string url_string;
args->GetNext(&url_string);
[[AtomApplication sharedApplication]
setCurrentActivity:base::SysUTF8ToNSString(type)
withUserInfo:DictionaryValueToNSDictionary(std::move(user_info))
withWebpageURL:net::NSURLWithGURL(GURL(url_string))];
}
std::string Browser::GetCurrentActivityType() {
NSUserActivity* userActivity =
[[AtomApplication sharedApplication] getCurrentActivity];
return base::SysNSStringToUTF8(userActivity.activityType);
}
void Browser::InvalidateCurrentActivity() {
[[AtomApplication sharedApplication] invalidateCurrentActivity];
}
void Browser::ResignCurrentActivity() {
[[AtomApplication sharedApplication] resignCurrentActivity];
}
void Browser::UpdateCurrentActivity(const std::string& type,
base::Value::Dict user_info) {
[[AtomApplication sharedApplication]
updateCurrentActivity:base::SysUTF8ToNSString(type)
withUserInfo:DictionaryValueToNSDictionary(
std::move(user_info))];
}
bool Browser::WillContinueUserActivity(const std::string& type) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnWillContinueUserActivity(&prevent_default, type);
return prevent_default;
}
void Browser::DidFailToContinueUserActivity(const std::string& type,
const std::string& error) {
for (BrowserObserver& observer : observers_)
observer.OnDidFailToContinueUserActivity(type, error);
}
bool Browser::ContinueUserActivity(const std::string& type,
base::Value::Dict user_info,
base::Value::Dict details) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnContinueUserActivity(&prevent_default, type, user_info.Clone(),
details.Clone());
return prevent_default;
}
void Browser::UserActivityWasContinued(const std::string& type,
base::Value::Dict user_info) {
for (BrowserObserver& observer : observers_)
observer.OnUserActivityWasContinued(type, user_info.Clone());
}
bool Browser::UpdateUserActivityState(const std::string& type,
base::Value::Dict user_info) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnUpdateUserActivityState(&prevent_default, type,
user_info.Clone());
return prevent_default;
}
// Modified from chrome/browser/ui/cocoa/l10n_util.mm.
void Browser::ApplyForcedRTL() {
NSUserDefaults* defaults = NSUserDefaults.standardUserDefaults;
auto dir = base::i18n::GetForcedTextDirection();
// An Electron app should respect RTL behavior of application locale over
// system locale.
auto should_be_rtl = dir == base::i18n::RIGHT_TO_LEFT || IsAppRTL();
auto should_be_ltr = dir == base::i18n::LEFT_TO_RIGHT || !IsAppRTL();
// -registerDefaults: won't do the trick here because these defaults exist
// (in the global domain) to reflect the system locale. They need to be set
// in Chrome's domain to supersede the system value.
if (should_be_rtl) {
[defaults setBool:YES forKey:@"AppleTextDirection"];
[defaults setBool:YES forKey:@"NSForceRightToLeftWritingDirection"];
} else if (should_be_ltr) {
[defaults setBool:YES forKey:@"AppleTextDirection"];
[defaults setBool:NO forKey:@"NSForceRightToLeftWritingDirection"];
} else {
[defaults removeObjectForKey:@"AppleTextDirection"];
[defaults removeObjectForKey:@"NSForceRightToLeftWritingDirection"];
}
}
Browser::LoginItemSettings Browser::GetLoginItemSettings(
const LoginItemSettings& options) {
LoginItemSettings settings;
#if IS_MAS_BUILD()
settings.open_at_login = platform_util::GetLoginItemEnabled();
#else
settings.open_at_login = CheckLoginItemStatus(&settings.open_as_hidden);
settings.restore_state = base::mac::WasLaunchedAsLoginItemRestoreState();
settings.opened_at_login = base::mac::WasLaunchedAsLoginOrResumeItem();
settings.opened_as_hidden = base::mac::WasLaunchedAsHiddenLoginItem();
#endif
return settings;
}
void Browser::SetLoginItemSettings(LoginItemSettings settings) {
#if IS_MAS_BUILD()
if (!platform_util::SetLoginItemEnabled(settings.open_at_login)) {
LOG(ERROR) << "Unable to set login item enabled on sandboxed app.";
}
#else
if (settings.open_at_login) {
base::mac::AddToLoginItems(base::apple::MainBundlePath(),
settings.open_as_hidden);
} else {
base::mac::RemoveFromLoginItems(base::apple::MainBundlePath());
}
#endif
}
std::string Browser::GetExecutableFileVersion() const {
return GetApplicationVersion();
}
std::string Browser::GetExecutableFileProductName() const {
return GetApplicationName();
}
int Browser::DockBounce(BounceType type) {
return [[AtomApplication sharedApplication]
requestUserAttention:static_cast<NSRequestUserAttentionType>(type)];
}
void Browser::DockCancelBounce(int request_id) {
[[AtomApplication sharedApplication] cancelUserAttentionRequest:request_id];
}
void Browser::DockSetBadgeText(const std::string& label) {
NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
[tile setBadgeLabel:base::SysUTF8ToNSString(label)];
}
void Browser::DockDownloadFinished(const std::string& filePath) {
[[NSDistributedNotificationCenter defaultCenter]
postNotificationName:@"com.apple.DownloadFileFinished"
object:base::SysUTF8ToNSString(filePath)];
}
std::string Browser::DockGetBadgeText() {
NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
return base::SysNSStringToUTF8([tile badgeLabel]);
}
void Browser::DockHide() {
// Transforming application state from UIElement to Foreground is an
// asynchronous operation, and unfortunately there is currently no way to know
// when it is finished.
// So if we call DockHide => DockShow => DockHide => DockShow in a very short
// time, we would trigger a bug of macOS that, there would be multiple dock
// icons of the app left in system.
// To work around this, we make sure DockHide does nothing if it is called
// immediately after DockShow. After some experiments, 1 second seems to be
// a proper interval.
if (!last_dock_show_.is_null() &&
base::Time::Now() - last_dock_show_ < base::Seconds(1)) {
return;
}
for (auto* const& window : WindowList::GetWindows())
[window->GetNativeWindow().GetNativeNSWindow() setCanHide:NO];
ProcessSerialNumber psn = {0, kCurrentProcess};
TransformProcessType(&psn, kProcessTransformToUIElementApplication);
}
bool Browser::DockIsVisible() {
// Because DockShow has a slight delay this may not be true immediately
// after that call.
return ([[NSRunningApplication currentApplication] activationPolicy] ==
NSApplicationActivationPolicyRegular);
}
v8::Local<v8::Promise> Browser::DockShow(v8::Isolate* isolate) {
last_dock_show_ = base::Time::Now();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
BOOL active = [[NSRunningApplication currentApplication] isActive];
ProcessSerialNumber psn = {0, kCurrentProcess};
if (active) {
// Workaround buggy behavior of TransformProcessType.
// http://stackoverflow.com/questions/7596643/
NSArray* runningApps = [NSRunningApplication
runningApplicationsWithBundleIdentifier:@"com.apple.dock"];
for (NSRunningApplication* app in runningApps) {
[app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
break;
}
__block gin_helper::Promise<void> p = std::move(promise);
dispatch_time_t one_ms = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
dispatch_after(one_ms, dispatch_get_main_queue(), ^{
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
dispatch_time_t one_ms_2 = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
dispatch_after(one_ms_2, dispatch_get_main_queue(), ^{
[[NSRunningApplication currentApplication]
activateWithOptions:NSApplicationActivateIgnoringOtherApps];
p.Resolve();
});
});
} else {
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
promise.Resolve();
}
return handle;
}
void Browser::DockSetMenu(ElectronMenuModel* model) {
ElectronApplicationDelegate* delegate =
(ElectronApplicationDelegate*)[NSApp delegate];
[delegate setApplicationDockMenu:model];
}
void Browser::DockSetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) {
gfx::Image image;
if (!icon->IsNull()) {
api::NativeImage* native_image = nullptr;
if (!api::NativeImage::TryConvertNativeImage(isolate, icon, &native_image))
return;
image = native_image->image();
}
// This is needed to avoid a hard CHECK when this fn is called
// before the browser process is ready, since supported scales
// are normally set by ui::ResourceBundle::InitSharedInstance
// during browser process startup.
if (!is_ready())
ui::SetSupportedResourceScaleFactors({ui::k100Percent});
[[AtomApplication sharedApplication]
setApplicationIconImage:image.AsNSImage()];
}
void Browser::ShowAboutPanel() {
NSDictionary* options = DictionaryValueToNSDictionary(about_panel_options_);
// Credits must be a NSAttributedString instead of NSString
NSString* credits = (NSString*)options[@"Credits"];
if (credits != nil) {
NSMutableDictionary* mutable_options = [options mutableCopy];
NSAttributedString* creditString = [[NSAttributedString alloc]
initWithString:credits
attributes:@{NSForegroundColorAttributeName : [NSColor textColor]}];
[mutable_options setValue:creditString forKey:@"Credits"];
options = [NSDictionary dictionaryWithDictionary:mutable_options];
}
[[AtomApplication sharedApplication]
orderFrontStandardAboutPanelWithOptions:options];
}
void Browser::SetAboutPanelOptions(base::Value::Dict options) {
about_panel_options_.clear();
for (const auto pair : options) {
std::string key = pair.first;
if (!key.empty() && pair.second.is_string()) {
key[0] = base::ToUpperASCII(key[0]);
about_panel_options_.Set(key, pair.second.Clone());
}
}
}
void Browser::ShowEmojiPanel() {
[[AtomApplication sharedApplication] orderFrontCharacterPalette:nil];
}
bool Browser::IsEmojiPanelSupported() {
return true;
}
bool Browser::IsSecureKeyboardEntryEnabled() {
return password_input_enabler_.get() != nullptr;
}
void Browser::SetSecureKeyboardEntryEnabled(bool enabled) {
if (enabled) {
password_input_enabler_ =
std::make_unique<ui::ScopedPasswordInputEnabler>();
} else {
password_input_enabler_.reset();
}
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 37,560 |
[Bug]: Open at login with setLoginItemSettings in MAS build is not working
|
### 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
16.0.6
### What operating system are you using?
macOS
### Operating System Version
Version 13.2 (22D49)
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Setting app to open at login with setLoginItemSettings api should work both locally and with MAS build.
Locally the app is added to login items but when i build it for MAS this doesn't work.
### Actual Behavior
Setting app to open at login with setLoginItemSettings api works locally but doesn't work in MAS build.
In MAS build the app is not added to login items.
<img width="477" alt="image" src="https://user-images.githubusercontent.com/17458685/224576455-a9145dfc-7121-4097-9fe4-a472f0c2ead4.png">
### Testcase Gist URL
_No response_
### Additional Information
According to docs https://www.electronjs.org/docs/latest/api/app#appsetloginitemsettingssettings-macos-windows setting login item in MAS build should work by using the following API
```js
app.setLoginItemSettings({
openAtLogin: openAtLogin,
})
```
In the docs on limitations of MAS build there is no mention of any limitation of using above API https://www.electronjs.org/docs/latest/tutorial/mac-app-store-submission-guide#limitations-of-mas-build
Here is possible related issue and PRs:
- https://github.com/electron/electron/issues/7312
- https://github.com/electron/electron/pull/11144
- https://github.com/electron/electron/pull/10856
|
https://github.com/electron/electron/issues/37560
|
https://github.com/electron/electron/pull/37244
|
6d0d350e138494cd68dd3d4fa73b2719da4575bf
|
f7b1c75c72a8dcab4157408f92bd3771606d8029
| 2023-03-12T22:11:32Z |
c++
| 2023-10-16T16:25:11Z |
shell/common/platform_util.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_PLATFORM_UTIL_H_
#define ELECTRON_SHELL_COMMON_PLATFORM_UTIL_H_
#include <string>
#include "base/files/file_path.h"
#include "base/functional/callback_forward.h"
#include "build/build_config.h"
class GURL;
namespace platform_util {
typedef base::OnceCallback<void(const std::string&)> OpenCallback;
// Show the given file in a file manager. If possible, select the file.
// Must be called from the UI thread.
void ShowItemInFolder(const base::FilePath& full_path);
// Open the given file in the desktop's default manner.
// Must be called from the UI thread.
void OpenPath(const base::FilePath& full_path, OpenCallback callback);
struct OpenExternalOptions {
bool activate = true;
base::FilePath working_dir;
bool log_usage = false;
};
// Open the given external protocol URL in the desktop's default manner.
// (For example, mailto: URLs in the default mail user agent.)
void OpenExternal(const GURL& url,
const OpenExternalOptions& options,
OpenCallback callback);
// Move a file to trash, asynchronously.
void TrashItem(const base::FilePath& full_path,
base::OnceCallback<void(bool, const std::string&)> callback);
void Beep();
#if BUILDFLAG(IS_WIN)
// SHGetFolderPath calls not covered by Chromium
bool GetFolderPath(int key, base::FilePath* result);
#endif
#if BUILDFLAG(IS_MAC)
bool GetLoginItemEnabled();
bool SetLoginItemEnabled(bool enabled);
#endif
#if BUILDFLAG(IS_LINUX)
// Returns a success flag.
// Unlike libgtkui, does *not* use "chromium-browser.desktop" as a fallback.
bool GetDesktopName(std::string* setme);
// The XDG application ID must match the name of the desktop entry file without
// the .desktop extension.
std::string GetXdgAppId();
#endif
} // namespace platform_util
#endif // ELECTRON_SHELL_COMMON_PLATFORM_UTIL_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 37,560 |
[Bug]: Open at login with setLoginItemSettings in MAS build is not working
|
### 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
16.0.6
### What operating system are you using?
macOS
### Operating System Version
Version 13.2 (22D49)
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Setting app to open at login with setLoginItemSettings api should work both locally and with MAS build.
Locally the app is added to login items but when i build it for MAS this doesn't work.
### Actual Behavior
Setting app to open at login with setLoginItemSettings api works locally but doesn't work in MAS build.
In MAS build the app is not added to login items.
<img width="477" alt="image" src="https://user-images.githubusercontent.com/17458685/224576455-a9145dfc-7121-4097-9fe4-a472f0c2ead4.png">
### Testcase Gist URL
_No response_
### Additional Information
According to docs https://www.electronjs.org/docs/latest/api/app#appsetloginitemsettingssettings-macos-windows setting login item in MAS build should work by using the following API
```js
app.setLoginItemSettings({
openAtLogin: openAtLogin,
})
```
In the docs on limitations of MAS build there is no mention of any limitation of using above API https://www.electronjs.org/docs/latest/tutorial/mac-app-store-submission-guide#limitations-of-mas-build
Here is possible related issue and PRs:
- https://github.com/electron/electron/issues/7312
- https://github.com/electron/electron/pull/11144
- https://github.com/electron/electron/pull/10856
|
https://github.com/electron/electron/issues/37560
|
https://github.com/electron/electron/pull/37244
|
6d0d350e138494cd68dd3d4fa73b2719da4575bf
|
f7b1c75c72a8dcab4157408f92bd3771606d8029
| 2023-03-12T22:11:32Z |
c++
| 2023-10-16T16:25:11Z |
shell/common/platform_util_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/common/platform_util.h"
#include <string>
#include <utility>
#import <Carbon/Carbon.h>
#import <Cocoa/Cocoa.h>
#import <ServiceManagement/ServiceManagement.h>
#include "base/apple/foundation_util.h"
#include "base/apple/osstatus_logging.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/callback.h"
#include "base/logging.h"
#include "base/mac/scoped_aedesc.h"
#include "base/strings/stringprintf.h"
#include "base/strings/sys_string_conversions.h"
#include "net/base/mac/url_conversions.h"
#include "ui/views/widget/widget.h"
#include "url/gurl.h"
namespace {
// This may be called from a global dispatch queue, the methods used here are
// thread safe, including LSGetApplicationForURL (> 10.2) and
// NSWorkspace#openURLs.
std::string OpenURL(NSURL* ns_url, bool activate) {
CFURLRef cf_url = (__bridge CFURLRef)(ns_url);
CFURLRef ref =
LSCopyDefaultApplicationURLForURL(cf_url, kLSRolesAll, nullptr);
// If no application could be found, nullptr is returned and outError
// (if not nullptr) is populated with kLSApplicationNotFoundErr.
if (ref == nullptr)
return "No application in the Launch Services database matches the input "
"criteria.";
NSUInteger launchOptions = NSWorkspaceLaunchDefault;
if (!activate)
launchOptions |= NSWorkspaceLaunchWithoutActivation;
bool opened = [[NSWorkspace sharedWorkspace] openURLs:@[ ns_url ]
withAppBundleIdentifier:nil
options:launchOptions
additionalEventParamDescriptor:nil
launchIdentifiers:nil];
if (!opened)
return "Failed to open URL";
return "";
}
NSString* GetLoginHelperBundleIdentifier() {
return [[[NSBundle mainBundle] bundleIdentifier]
stringByAppendingString:@".loginhelper"];
}
std::string OpenPathOnThread(const base::FilePath& full_path) {
NSString* path_string = base::SysUTF8ToNSString(full_path.value());
NSURL* url = [NSURL fileURLWithPath:path_string];
if (!url)
return "Invalid path";
const NSWorkspaceLaunchOptions launch_options =
NSWorkspaceLaunchAsync | NSWorkspaceLaunchWithErrorPresentation;
BOOL success = [[NSWorkspace sharedWorkspace] openURLs:@[ url ]
withAppBundleIdentifier:nil
options:launch_options
additionalEventParamDescriptor:nil
launchIdentifiers:nil];
return success ? "" : "Failed to open path";
}
} // namespace
namespace platform_util {
void ShowItemInFolder(const base::FilePath& path) {
// The API only takes absolute path.
base::FilePath full_path =
path.IsAbsolute() ? path : base::MakeAbsoluteFilePath(path);
DCHECK([NSThread isMainThread]);
NSString* path_string = base::SysUTF8ToNSString(full_path.value());
if (!path_string || ![[NSWorkspace sharedWorkspace] selectFile:path_string
inFileViewerRootedAtPath:@""]) {
LOG(WARNING) << "NSWorkspace failed to select file " << full_path.value();
}
}
void OpenPath(const base::FilePath& full_path, OpenCallback callback) {
std::move(callback).Run(OpenPathOnThread(full_path));
}
void OpenExternal(const GURL& url,
const OpenExternalOptions& options,
OpenCallback callback) {
DCHECK([NSThread isMainThread]);
NSURL* ns_url = net::NSURLWithGURL(url);
if (!ns_url) {
std::move(callback).Run("Invalid URL");
return;
}
bool activate = options.activate;
__block OpenCallback c = std::move(callback);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
__block std::string error = OpenURL(ns_url, activate);
dispatch_async(dispatch_get_main_queue(), ^{
std::move(c).Run(error);
});
});
}
bool MoveItemToTrashWithError(const base::FilePath& full_path,
bool delete_on_fail,
std::string* error) {
NSString* path_string = base::SysUTF8ToNSString(full_path.value());
if (!path_string) {
*error = "Invalid file path: " + full_path.value();
LOG(WARNING) << *error;
return false;
}
NSURL* url = [NSURL fileURLWithPath:path_string];
NSError* err = nil;
BOOL did_trash = [[NSFileManager defaultManager] trashItemAtURL:url
resultingItemURL:nil
error:&err];
if (delete_on_fail) {
// Some volumes may not support a Trash folder or it may be disabled
// so these methods will report failure by returning NO or nil and
// an NSError with NSFeatureUnsupportedError.
// Handle this by deleting the item as a fallback.
if (!did_trash && [err code] == NSFeatureUnsupportedError) {
did_trash = [[NSFileManager defaultManager] removeItemAtURL:url
error:&err];
}
}
if (!did_trash) {
*error = base::SysNSStringToUTF8([err localizedDescription]);
LOG(WARNING) << "NSWorkspace failed to move file " << full_path.value()
<< " to trash: " << *error;
}
return did_trash;
}
namespace internal {
bool PlatformTrashItem(const base::FilePath& full_path, std::string* error) {
return MoveItemToTrashWithError(full_path, false, error);
}
} // namespace internal
void Beep() {
NSBeep();
}
bool GetLoginItemEnabled() {
BOOL enabled = NO;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
// SMJobCopyDictionary does not work in sandbox (see rdar://13626319)
CFArrayRef jobs = SMCopyAllJobDictionaries(kSMDomainUserLaunchd);
#pragma clang diagnostic pop
NSArray* jobs_ = CFBridgingRelease(jobs);
NSString* identifier = GetLoginHelperBundleIdentifier();
if (jobs_ && [jobs_ count] > 0) {
for (NSDictionary* job in jobs_) {
if ([identifier isEqualToString:[job objectForKey:@"Label"]]) {
enabled = [[job objectForKey:@"OnDemand"] boolValue];
break;
}
}
}
return enabled;
}
bool SetLoginItemEnabled(bool enabled) {
NSString* identifier = GetLoginHelperBundleIdentifier();
return SMLoginItemSetEnabled((__bridge CFStringRef)identifier, enabled);
}
} // namespace platform_util
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 37,560 |
[Bug]: Open at login with setLoginItemSettings in MAS build is not working
|
### 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
16.0.6
### What operating system are you using?
macOS
### Operating System Version
Version 13.2 (22D49)
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Setting app to open at login with setLoginItemSettings api should work both locally and with MAS build.
Locally the app is added to login items but when i build it for MAS this doesn't work.
### Actual Behavior
Setting app to open at login with setLoginItemSettings api works locally but doesn't work in MAS build.
In MAS build the app is not added to login items.
<img width="477" alt="image" src="https://user-images.githubusercontent.com/17458685/224576455-a9145dfc-7121-4097-9fe4-a472f0c2ead4.png">
### Testcase Gist URL
_No response_
### Additional Information
According to docs https://www.electronjs.org/docs/latest/api/app#appsetloginitemsettingssettings-macos-windows setting login item in MAS build should work by using the following API
```js
app.setLoginItemSettings({
openAtLogin: openAtLogin,
})
```
In the docs on limitations of MAS build there is no mention of any limitation of using above API https://www.electronjs.org/docs/latest/tutorial/mac-app-store-submission-guide#limitations-of-mas-build
Here is possible related issue and PRs:
- https://github.com/electron/electron/issues/7312
- https://github.com/electron/electron/pull/11144
- https://github.com/electron/electron/pull/10856
|
https://github.com/electron/electron/issues/37560
|
https://github.com/electron/electron/pull/37244
|
6d0d350e138494cd68dd3d4fa73b2719da4575bf
|
f7b1c75c72a8dcab4157408f92bd3771606d8029
| 2023-03-12T22:11:32Z |
c++
| 2023-10-16T16:25:11Z |
spec/api-app-spec.ts
|
import { assert, expect } from 'chai';
import * as cp from 'node:child_process';
import * as https from 'node:https';
import * as http from 'node:http';
import * as net from 'node:net';
import * as fs from 'fs-extra';
import * as path from 'node:path';
import { promisify } from 'node:util';
import { app, BrowserWindow, Menu, session, net as electronNet, WebContents } from 'electron/main';
import { closeWindow, closeAllWindows } from './lib/window-helpers';
import { ifdescribe, ifit, listen, waitUntil } from './lib/spec-helpers';
import { expectDeprecationMessages } from './lib/deprecate-helpers';
import { once } from 'node:events';
import split = require('split')
const fixturesPath = path.resolve(__dirname, 'fixtures');
describe('electron module', () => {
it('does not expose internal modules to require', () => {
expect(() => {
require('clipboard');
}).to.throw(/Cannot find module 'clipboard'/);
});
describe('require("electron")', () => {
it('always returns the internal electron module', () => {
require('electron');
});
});
});
describe('app module', () => {
let server: https.Server;
let secureUrl: string;
const certPath = path.join(fixturesPath, 'certificates');
before(async () => {
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
};
server = https.createServer(options, (req, res) => {
if ((req as any).client.authorized) {
res.writeHead(200);
res.end('<title>authorized</title>');
} else {
res.writeHead(401);
res.end('<title>denied</title>');
}
});
secureUrl = (await listen(server)).url;
});
after(done => {
server.close(() => done());
});
describe('app.getVersion()', () => {
it('returns the version field of package.json', () => {
expect(app.getVersion()).to.equal('0.1.0');
});
});
describe('app.setVersion(version)', () => {
it('overrides the version', () => {
expect(app.getVersion()).to.equal('0.1.0');
app.setVersion('test-version');
expect(app.getVersion()).to.equal('test-version');
app.setVersion('0.1.0');
});
});
describe('app name APIs', () => {
it('with properties', () => {
it('returns the name field of package.json', () => {
expect(app.name).to.equal('Electron Test Main');
});
it('overrides the name', () => {
expect(app.name).to.equal('Electron Test Main');
app.name = 'electron-test-name';
expect(app.name).to.equal('electron-test-name');
app.name = 'Electron Test Main';
});
});
it('with functions', () => {
it('returns the name field of package.json', () => {
expect(app.getName()).to.equal('Electron Test Main');
});
it('overrides the name', () => {
expect(app.getName()).to.equal('Electron Test Main');
app.setName('electron-test-name');
expect(app.getName()).to.equal('electron-test-name');
app.setName('Electron Test Main');
});
});
});
describe('app.getLocale()', () => {
it('should not be empty', () => {
expect(app.getLocale()).to.not.equal('');
});
});
describe('app.getSystemLocale()', () => {
it('should not be empty', () => {
expect(app.getSystemLocale()).to.not.equal('');
});
});
describe('app.getPreferredSystemLanguages()', () => {
ifit(process.platform !== 'linux')('should not be empty', () => {
expect(app.getPreferredSystemLanguages().length).to.not.equal(0);
});
ifit(process.platform === 'linux')('should be empty or contain C entry', () => {
const languages = app.getPreferredSystemLanguages();
if (languages.length) {
expect(languages).to.not.include('C');
}
});
});
describe('app.getLocaleCountryCode()', () => {
it('should be empty or have length of two', () => {
const localeCountryCode = app.getLocaleCountryCode();
expect(localeCountryCode).to.be.a('string');
expect(localeCountryCode.length).to.be.oneOf([0, 2]);
});
});
describe('app.isPackaged', () => {
it('should be false during tests', () => {
expect(app.isPackaged).to.equal(false);
});
});
ifdescribe(process.platform === 'darwin')('app.isInApplicationsFolder()', () => {
it('should be false during tests', () => {
expect(app.isInApplicationsFolder()).to.equal(false);
});
});
describe('app.exit(exitCode)', () => {
let appProcess: cp.ChildProcess | null = null;
afterEach(() => {
if (appProcess) appProcess.kill();
});
it('emits a process exit event with the code', async () => {
const appPath = path.join(fixturesPath, 'api', 'quit-app');
const electronPath = process.execPath;
let output = '';
appProcess = cp.spawn(electronPath, [appPath]);
if (appProcess && appProcess.stdout) {
appProcess.stdout.on('data', data => { output += data; });
}
const [code] = await once(appProcess, 'exit');
if (process.platform !== 'win32') {
expect(output).to.include('Exit event with code: 123');
}
expect(code).to.equal(123);
});
it('closes all windows', async function () {
const appPath = path.join(fixturesPath, 'api', 'exit-closes-all-windows-app');
const electronPath = process.execPath;
appProcess = cp.spawn(electronPath, [appPath]);
const [code, signal] = await once(appProcess, 'exit');
expect(signal).to.equal(null, 'exit signal should be null, if you see this please tag @MarshallOfSound');
expect(code).to.equal(123, 'exit code should be 123, if you see this please tag @MarshallOfSound');
});
ifit(['darwin', 'linux'].includes(process.platform))('exits gracefully', async function () {
const electronPath = process.execPath;
const appPath = path.join(fixturesPath, 'api', 'singleton');
appProcess = cp.spawn(electronPath, [appPath]);
// Singleton will send us greeting data to let us know it's running.
// After that, ask it to exit gracefully and confirm that it does.
if (appProcess && appProcess.stdout) {
appProcess.stdout.on('data', () => appProcess!.kill());
}
const [code, signal] = await once(appProcess, 'exit');
const message = `code:\n${code}\nsignal:\n${signal}`;
expect(code).to.equal(0, message);
expect(signal).to.equal(null, message);
});
});
ifdescribe(process.platform === 'darwin')('app.setActivationPolicy', () => {
it('throws an error on invalid application policies', () => {
expect(() => {
app.setActivationPolicy('terrible' as any);
}).to.throw(/Invalid activation policy: must be one of 'regular', 'accessory', or 'prohibited'/);
});
});
describe('app.requestSingleInstanceLock', () => {
interface SingleInstanceLockTestArgs {
args: string[];
expectedAdditionalData: unknown;
}
it('prevents the second launch of app', async function () {
this.timeout(120000);
const appPath = path.join(fixturesPath, 'api', 'singleton-data');
const first = cp.spawn(process.execPath, [appPath]);
await once(first.stdout, 'data');
// Start second app when received output.
const second = cp.spawn(process.execPath, [appPath]);
const [code2] = await once(second, 'exit');
expect(code2).to.equal(1);
const [code1] = await once(first, 'exit');
expect(code1).to.equal(0);
});
it('returns true when setting non-existent user data folder', async function () {
const appPath = path.join(fixturesPath, 'api', 'singleton-userdata');
const instance = cp.spawn(process.execPath, [appPath]);
const [code] = await once(instance, 'exit');
expect(code).to.equal(0);
});
async function testArgumentPassing (testArgs: SingleInstanceLockTestArgs) {
const appPath = path.join(fixturesPath, 'api', 'singleton-data');
const first = cp.spawn(process.execPath, [appPath, ...testArgs.args]);
const firstExited = once(first, 'exit');
// Wait for the first app to boot.
const firstStdoutLines = first.stdout.pipe(split());
while ((await once(firstStdoutLines, 'data')).toString() !== 'started') {
// wait.
}
const additionalDataPromise = once(firstStdoutLines, 'data');
const secondInstanceArgs = [process.execPath, appPath, ...testArgs.args, '--some-switch', 'some-arg'];
const second = cp.spawn(secondInstanceArgs[0], secondInstanceArgs.slice(1));
const secondExited = once(second, 'exit');
const [code2] = await secondExited;
expect(code2).to.equal(1);
const [code1] = await firstExited;
expect(code1).to.equal(0);
const dataFromSecondInstance = await additionalDataPromise;
const [args, additionalData] = dataFromSecondInstance[0].toString('ascii').split('||');
const secondInstanceArgsReceived: string[] = JSON.parse(args.toString('ascii'));
const secondInstanceDataReceived = JSON.parse(additionalData.toString('ascii'));
// Ensure secondInstanceArgs is a subset of secondInstanceArgsReceived
for (const arg of secondInstanceArgs) {
expect(secondInstanceArgsReceived).to.include(arg,
`argument ${arg} is missing from received second args`);
}
expect(secondInstanceDataReceived).to.be.deep.equal(testArgs.expectedAdditionalData,
`received data ${JSON.stringify(secondInstanceDataReceived)} is not equal to expected data ${JSON.stringify(testArgs.expectedAdditionalData)}.`);
}
it('passes arguments to the second-instance event no additional data', async () => {
await testArgumentPassing({
args: [],
expectedAdditionalData: null
});
});
it('sends and receives JSON object data', async () => {
const expectedAdditionalData = {
level: 1,
testkey: 'testvalue1',
inner: {
level: 2,
testkey: 'testvalue2'
}
};
await testArgumentPassing({
args: ['--send-data'],
expectedAdditionalData
});
});
it('sends and receives numerical data', async () => {
await testArgumentPassing({
args: ['--send-data', '--data-content=2'],
expectedAdditionalData: 2
});
});
it('sends and receives string data', async () => {
await testArgumentPassing({
args: ['--send-data', '--data-content="data"'],
expectedAdditionalData: 'data'
});
});
it('sends and receives boolean data', async () => {
await testArgumentPassing({
args: ['--send-data', '--data-content=false'],
expectedAdditionalData: false
});
});
it('sends and receives array data', async () => {
await testArgumentPassing({
args: ['--send-data', '--data-content=[2, 3, 4]'],
expectedAdditionalData: [2, 3, 4]
});
});
it('sends and receives mixed array data', async () => {
await testArgumentPassing({
args: ['--send-data', '--data-content=["2", true, 4]'],
expectedAdditionalData: ['2', true, 4]
});
});
it('sends and receives null data', async () => {
await testArgumentPassing({
args: ['--send-data', '--data-content=null'],
expectedAdditionalData: null
});
});
it('cannot send or receive undefined data', async () => {
try {
await testArgumentPassing({
args: ['--send-ack', '--ack-content="undefined"', '--prevent-default', '--send-data', '--data-content="undefined"'],
expectedAdditionalData: undefined
});
assert(false);
} catch {
// This is expected.
}
});
});
describe('app.relaunch', () => {
let server: net.Server | null = null;
const socketPath = process.platform === 'win32' ? '\\\\.\\pipe\\electron-app-relaunch' : '/tmp/electron-app-relaunch';
beforeEach(done => {
fs.unlink(socketPath, () => {
server = net.createServer();
server.listen(socketPath);
done();
});
});
afterEach((done) => {
server!.close(() => {
if (process.platform === 'win32') {
done();
} else {
fs.unlink(socketPath, () => done());
}
});
});
it('relaunches the app', function (done) {
this.timeout(120000);
let state = 'none';
server!.once('error', error => done(error));
server!.on('connection', client => {
client.once('data', data => {
if (String(data) === '--first' && state === 'none') {
state = 'first-launch';
} else if (String(data) === '--second' && state === 'first-launch') {
state = 'second-launch';
} else if (String(data) === '--third' && state === 'second-launch') {
done();
} else {
done(`Unexpected state: "${state}", data: "${data}"`);
}
});
});
const appPath = path.join(fixturesPath, 'api', 'relaunch');
const child = cp.spawn(process.execPath, [appPath, '--first']);
child.stdout.on('data', (c) => console.log(c.toString()));
child.stderr.on('data', (c) => console.log(c.toString()));
child.on('exit', (code, signal) => {
if (code !== 0) {
console.log(`Process exited with code "${code}" signal "${signal}"`);
}
});
});
});
ifdescribe(process.platform === 'darwin')('app.setUserActivity(type, userInfo)', () => {
it('sets the current activity', () => {
app.setUserActivity('com.electron.testActivity', { testData: '123' });
expect(app.getCurrentActivityType()).to.equal('com.electron.testActivity');
});
});
describe('certificate-error event', () => {
afterEach(closeAllWindows);
it('is emitted when visiting a server with a self-signed cert', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL(secureUrl);
await once(app, 'certificate-error');
});
describe('when denied', () => {
before(() => {
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
callback(false);
});
});
after(() => {
app.removeAllListeners('certificate-error');
});
it('causes did-fail-load', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL(secureUrl);
await once(w.webContents, 'did-fail-load');
});
});
});
// xdescribe('app.importCertificate', () => {
// let w = null
// before(function () {
// if (process.platform !== 'linux') {
// this.skip()
// }
// })
// afterEach(() => closeWindow(w).then(() => { w = null }))
// it('can import certificate into platform cert store', done => {
// const options = {
// certificate: path.join(certPath, 'client.p12'),
// password: 'electron'
// }
// w = new BrowserWindow({
// show: false,
// webPreferences: {
// nodeIntegration: true
// }
// })
// w.webContents.on('did-finish-load', () => {
// expect(w.webContents.getTitle()).to.equal('authorized')
// done()
// })
// ipcRenderer.once('select-client-certificate', (event, webContentsId, list) => {
// expect(webContentsId).to.equal(w.webContents.id)
// expect(list).to.have.lengthOf(1)
// expect(list[0]).to.deep.equal({
// issuerName: 'Intermediate CA',
// subjectName: 'Client Cert',
// issuer: { commonName: 'Intermediate CA' },
// subject: { commonName: 'Client Cert' }
// })
// event.sender.send('client-certificate-response', list[0])
// })
// app.importCertificate(options, result => {
// expect(result).toNotExist()
// ipcRenderer.sendSync('set-client-certificate-option', false)
// w.loadURL(secureUrl)
// })
// })
// })
describe('BrowserWindow events', () => {
let w: BrowserWindow = null as any;
afterEach(() => {
closeWindow(w).then(() => { w = null as any; });
});
it('should emit browser-window-focus event when window is focused', async () => {
const emitted = once(app, 'browser-window-focus') as Promise<[any, BrowserWindow]>;
w = new BrowserWindow({ show: false });
w.emit('focus');
const [, window] = await emitted;
expect(window.id).to.equal(w.id);
});
it('should emit browser-window-blur event when window is blurred', async () => {
const emitted = once(app, 'browser-window-blur') as Promise<[any, BrowserWindow]>;
w = new BrowserWindow({ show: false });
w.emit('blur');
const [, window] = await emitted;
expect(window.id).to.equal(w.id);
});
it('should emit browser-window-created event when window is created', async () => {
const emitted = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>;
w = new BrowserWindow({ show: false });
const [, window] = await emitted;
expect(window.id).to.equal(w.id);
});
it('should emit web-contents-created event when a webContents is created', async () => {
const emitted = once(app, 'web-contents-created') as Promise<[any, WebContents]>;
w = new BrowserWindow({ show: false });
const [, webContents] = await emitted;
expect(webContents.id).to.equal(w.webContents.id);
});
// FIXME: re-enable this test on win32.
ifit(process.platform !== 'win32')('should emit renderer-process-crashed event when renderer crashes', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
await w.loadURL('about:blank');
expectDeprecationMessages(async () => {
const emitted = once(app, 'renderer-process-crashed') as Promise<[any, WebContents, boolean]>;
w.webContents.executeJavaScript('process.crash()');
const [, webContents, killed] = await emitted;
expect(webContents).to.equal(w.webContents);
expect(killed).to.be.false();
}, '\'renderer-process-crashed event\' is deprecated and will be removed. Please use \'render-process-gone event\' instead.');
});
// FIXME: re-enable this test on win32.
ifit(process.platform !== 'win32')('should emit render-process-gone event when renderer crashes', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
await w.loadURL('about:blank');
const emitted = once(app, 'render-process-gone') as Promise<[any, WebContents, Electron.RenderProcessGoneDetails]>;
w.webContents.executeJavaScript('process.crash()');
const [, webContents, details] = await emitted;
expect(webContents).to.equal(w.webContents);
expect(details.reason).to.be.oneOf(['crashed', 'abnormal-exit']);
});
});
describe('app.badgeCount', () => {
const platformIsNotSupported =
(process.platform === 'win32') ||
(process.platform === 'linux' && !app.isUnityRunning());
const expectedBadgeCount = 42;
after(() => { app.badgeCount = 0; });
ifdescribe(!platformIsNotSupported)('on supported platform', () => {
describe('with properties', () => {
it('sets a badge count', function () {
app.badgeCount = expectedBadgeCount;
expect(app.badgeCount).to.equal(expectedBadgeCount);
});
});
describe('with functions', () => {
it('sets a numerical badge count', function () {
app.setBadgeCount(expectedBadgeCount);
expect(app.getBadgeCount()).to.equal(expectedBadgeCount);
});
it('sets an non numeric (dot) badge count', function () {
app.setBadgeCount();
// Badge count should be zero when non numeric (dot) is requested
expect(app.getBadgeCount()).to.equal(0);
});
});
});
ifdescribe(process.platform !== 'win32' && platformIsNotSupported)('on unsupported platform', () => {
describe('with properties', () => {
it('does not set a badge count', function () {
app.badgeCount = 9999;
expect(app.badgeCount).to.equal(0);
});
});
describe('with functions', () => {
it('does not set a badge count)', function () {
app.setBadgeCount(9999);
expect(app.getBadgeCount()).to.equal(0);
});
});
});
});
ifdescribe(process.platform !== 'linux' && !process.mas)('app.get/setLoginItemSettings API', function () {
const updateExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe');
const processStartArgs = [
'--processStart', `"${path.basename(process.execPath)}"`,
'--process-start-args', '"--hidden"'
];
const regAddArgs = [
'ADD',
'HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run',
'/v',
'additionalEntry',
'/t',
'REG_BINARY',
'/f',
'/d'
];
beforeEach(() => {
app.setLoginItemSettings({ openAtLogin: false });
app.setLoginItemSettings({ openAtLogin: false, path: updateExe, args: processStartArgs });
app.setLoginItemSettings({ name: 'additionalEntry', openAtLogin: false });
});
afterEach(() => {
app.setLoginItemSettings({ openAtLogin: false });
app.setLoginItemSettings({ openAtLogin: false, path: updateExe, args: processStartArgs });
app.setLoginItemSettings({ name: 'additionalEntry', openAtLogin: false });
});
ifit(process.platform !== 'win32')('sets and returns the app as a login item', function () {
app.setLoginItemSettings({ openAtLogin: true });
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: true,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false
});
});
ifit(process.platform === 'win32')('sets and returns the app as a login item (windows)', function () {
app.setLoginItemSettings({ openAtLogin: true, enabled: true });
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: true,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false,
executableWillLaunchAtLogin: true,
launchItems: [{
name: 'electron.app.Electron',
path: process.execPath,
args: [],
scope: 'user',
enabled: true
}]
});
app.setLoginItemSettings({ openAtLogin: false });
app.setLoginItemSettings({ openAtLogin: true, enabled: false });
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: true,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false,
executableWillLaunchAtLogin: false,
launchItems: [{
name: 'electron.app.Electron',
path: process.execPath,
args: [],
scope: 'user',
enabled: false
}]
});
});
ifit(process.platform !== 'win32')('adds a login item that loads in hidden mode', function () {
app.setLoginItemSettings({ openAtLogin: true, openAsHidden: true });
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: true,
openAsHidden: process.platform === 'darwin' && !process.mas, // Only available on macOS
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false
});
});
ifit(process.platform === 'win32')('adds a login item that loads in hidden mode (windows)', function () {
app.setLoginItemSettings({ openAtLogin: true, openAsHidden: true });
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: true,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false,
executableWillLaunchAtLogin: true,
launchItems: [{
name: 'electron.app.Electron',
path: process.execPath,
args: [],
scope: 'user',
enabled: true
}]
});
});
it('correctly sets and unsets the LoginItem', function () {
expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
app.setLoginItemSettings({ openAtLogin: true });
expect(app.getLoginItemSettings().openAtLogin).to.equal(true);
app.setLoginItemSettings({ openAtLogin: false });
expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
});
ifit(process.platform === 'darwin')('correctly sets and unsets the LoginItem as hidden', function () {
expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
expect(app.getLoginItemSettings().openAsHidden).to.equal(false);
app.setLoginItemSettings({ openAtLogin: true, openAsHidden: true });
expect(app.getLoginItemSettings().openAtLogin).to.equal(true);
expect(app.getLoginItemSettings().openAsHidden).to.equal(true);
app.setLoginItemSettings({ openAtLogin: true, openAsHidden: false });
expect(app.getLoginItemSettings().openAtLogin).to.equal(true);
expect(app.getLoginItemSettings().openAsHidden).to.equal(false);
});
ifit(process.platform === 'win32')('allows you to pass a custom executable and arguments', function () {
app.setLoginItemSettings({ openAtLogin: true, path: updateExe, args: processStartArgs, enabled: true });
expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
const openAtLoginTrueEnabledTrue = app.getLoginItemSettings({
path: updateExe,
args: processStartArgs
});
expect(openAtLoginTrueEnabledTrue.openAtLogin).to.equal(true);
expect(openAtLoginTrueEnabledTrue.executableWillLaunchAtLogin).to.equal(true);
app.setLoginItemSettings({ openAtLogin: true, path: updateExe, args: processStartArgs, enabled: false });
const openAtLoginTrueEnabledFalse = app.getLoginItemSettings({
path: updateExe,
args: processStartArgs
});
expect(openAtLoginTrueEnabledFalse.openAtLogin).to.equal(true);
expect(openAtLoginTrueEnabledFalse.executableWillLaunchAtLogin).to.equal(false);
app.setLoginItemSettings({ openAtLogin: false, path: updateExe, args: processStartArgs, enabled: false });
const openAtLoginFalseEnabledFalse = app.getLoginItemSettings({
path: updateExe,
args: processStartArgs
});
expect(openAtLoginFalseEnabledFalse.openAtLogin).to.equal(false);
expect(openAtLoginFalseEnabledFalse.executableWillLaunchAtLogin).to.equal(false);
});
ifit(process.platform === 'win32')('allows you to pass a custom name', function () {
app.setLoginItemSettings({ openAtLogin: true });
app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: false });
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: true,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false,
executableWillLaunchAtLogin: true,
launchItems: [{
name: 'additionalEntry',
path: process.execPath,
args: [],
scope: 'user',
enabled: false
}, {
name: 'electron.app.Electron',
path: process.execPath,
args: [],
scope: 'user',
enabled: true
}]
});
app.setLoginItemSettings({ openAtLogin: false, name: 'additionalEntry' });
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: true,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false,
executableWillLaunchAtLogin: true,
launchItems: [{
name: 'electron.app.Electron',
path: process.execPath,
args: [],
scope: 'user',
enabled: true
}]
});
});
ifit(process.platform === 'win32')('finds launch items independent of args', function () {
app.setLoginItemSettings({ openAtLogin: true, args: ['arg1'] });
app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: false, args: ['arg2'] });
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: false,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false,
executableWillLaunchAtLogin: true,
launchItems: [{
name: 'additionalEntry',
path: process.execPath,
args: ['arg2'],
scope: 'user',
enabled: false
}, {
name: 'electron.app.Electron',
path: process.execPath,
args: ['arg1'],
scope: 'user',
enabled: true
}]
});
});
ifit(process.platform === 'win32')('finds launch items independent of path quotation or casing', function () {
const expectation = {
openAtLogin: false,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false,
executableWillLaunchAtLogin: true,
launchItems: [{
name: 'additionalEntry',
path: 'C:\\electron\\myapp.exe',
args: ['arg1'],
scope: 'user',
enabled: true
}]
};
app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: true, path: 'C:\\electron\\myapp.exe', args: ['arg1'] });
expect(app.getLoginItemSettings({ path: '"C:\\electron\\MYAPP.exe"' })).to.deep.equal(expectation);
app.setLoginItemSettings({ openAtLogin: false, name: 'additionalEntry' });
app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: true, path: '"C:\\electron\\MYAPP.exe"', args: ['arg1'] });
expect(app.getLoginItemSettings({ path: 'C:\\electron\\myapp.exe' })).to.deep.equal({
...expectation,
launchItems: [
{
name: 'additionalEntry',
path: 'C:\\electron\\MYAPP.exe',
args: ['arg1'],
scope: 'user',
enabled: true
}
]
});
});
ifit(process.platform === 'win32')('detects disabled by TaskManager', async function () {
app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: true, args: ['arg1'] });
const appProcess = cp.spawn('reg', [...regAddArgs, '030000000000000000000000']);
await once(appProcess, 'exit');
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: false,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false,
executableWillLaunchAtLogin: false,
launchItems: [{
name: 'additionalEntry',
path: process.execPath,
args: ['arg1'],
scope: 'user',
enabled: false
}]
});
});
ifit(process.platform === 'win32')('detects enabled by TaskManager', async function () {
const expectation = {
openAtLogin: false,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false,
executableWillLaunchAtLogin: true,
launchItems: [{
name: 'additionalEntry',
path: process.execPath,
args: ['arg1'],
scope: 'user',
enabled: true
}]
};
app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: false, args: ['arg1'] });
let appProcess = cp.spawn('reg', [...regAddArgs, '020000000000000000000000']);
await once(appProcess, 'exit');
expect(app.getLoginItemSettings()).to.deep.equal(expectation);
app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: false, args: ['arg1'] });
appProcess = cp.spawn('reg', [...regAddArgs, '000000000000000000000000']);
await once(appProcess, 'exit');
expect(app.getLoginItemSettings()).to.deep.equal(expectation);
});
});
ifdescribe(process.platform !== 'linux')('accessibilitySupportEnabled property', () => {
it('with properties', () => {
it('can set accessibility support enabled', () => {
expect(app.accessibilitySupportEnabled).to.eql(false);
app.accessibilitySupportEnabled = true;
expect(app.accessibilitySupportEnabled).to.eql(true);
});
});
it('with functions', () => {
it('can set accessibility support enabled', () => {
expect(app.isAccessibilitySupportEnabled()).to.eql(false);
app.setAccessibilitySupportEnabled(true);
expect(app.isAccessibilitySupportEnabled()).to.eql(true);
});
});
});
describe('getAppPath', () => {
it('works for directories with package.json', async () => {
const { appPath } = await runTestApp('app-path');
expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path'));
});
it('works for directories with index.js', async () => {
const { appPath } = await runTestApp('app-path/lib');
expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
});
it('works for files without extension', async () => {
const { appPath } = await runTestApp('app-path/lib/index');
expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
});
it('works for files', async () => {
const { appPath } = await runTestApp('app-path/lib/index.js');
expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
});
});
describe('getPath(name)', () => {
it('returns paths that exist', () => {
const paths = [
fs.existsSync(app.getPath('exe')),
fs.existsSync(app.getPath('home')),
fs.existsSync(app.getPath('temp'))
];
expect(paths).to.deep.equal([true, true, true]);
});
it('throws an error when the name is invalid', () => {
expect(() => {
app.getPath('does-not-exist' as any);
}).to.throw(/Failed to get 'does-not-exist' path/);
});
it('returns the overridden path', () => {
app.setPath('music', __dirname);
expect(app.getPath('music')).to.equal(__dirname);
});
if (process.platform === 'win32') {
it('gets the folder for recent files', () => {
const recent = app.getPath('recent');
// We expect that one of our test machines have overridden this
// to be something crazy, it'll always include the word "Recent"
// unless people have been registry-hacking like crazy
expect(recent).to.include('Recent');
});
it('can override the recent files path', () => {
app.setPath('recent', 'C:\\fake-path');
expect(app.getPath('recent')).to.equal('C:\\fake-path');
});
}
it('uses the app name in getPath(userData)', () => {
expect(app.getPath('userData')).to.include(app.name);
});
});
describe('setPath(name, path)', () => {
it('throws when a relative path is passed', () => {
const badPath = 'hey/hi/hello';
expect(() => {
app.setPath('music', badPath);
}).to.throw(/Path must be absolute/);
});
it('does not create a new directory by default', () => {
const badPath = path.join(__dirname, 'music');
expect(fs.existsSync(badPath)).to.be.false();
app.setPath('music', badPath);
expect(fs.existsSync(badPath)).to.be.false();
expect(() => { app.getPath(badPath as any); }).to.throw();
});
describe('sessionData', () => {
const appPath = path.join(__dirname, 'fixtures', 'apps', 'set-path');
const appName = fs.readJsonSync(path.join(appPath, 'package.json')).name;
const userDataPath = path.join(app.getPath('appData'), appName);
const tempBrowserDataPath = path.join(app.getPath('temp'), appName);
const sessionFiles = [
'Preferences',
'Code Cache',
'Local Storage',
'IndexedDB',
'Service Worker'
];
const hasSessionFiles = (dir: string) => {
for (const file of sessionFiles) {
if (!fs.existsSync(path.join(dir, file))) {
return false;
}
}
return true;
};
beforeEach(() => {
fs.removeSync(userDataPath);
fs.removeSync(tempBrowserDataPath);
});
it('writes to userData by default', () => {
expect(hasSessionFiles(userDataPath)).to.equal(false);
cp.spawnSync(process.execPath, [appPath]);
expect(hasSessionFiles(userDataPath)).to.equal(true);
});
it('can be changed', () => {
expect(hasSessionFiles(userDataPath)).to.equal(false);
cp.spawnSync(process.execPath, [appPath, 'sessionData', tempBrowserDataPath]);
expect(hasSessionFiles(userDataPath)).to.equal(false);
expect(hasSessionFiles(tempBrowserDataPath)).to.equal(true);
});
it('changing userData affects default sessionData', () => {
expect(hasSessionFiles(userDataPath)).to.equal(false);
cp.spawnSync(process.execPath, [appPath, 'userData', tempBrowserDataPath]);
expect(hasSessionFiles(userDataPath)).to.equal(false);
expect(hasSessionFiles(tempBrowserDataPath)).to.equal(true);
});
});
});
describe('setAppLogsPath(path)', () => {
it('throws when a relative path is passed', () => {
const badPath = 'hey/hi/hello';
expect(() => {
app.setAppLogsPath(badPath);
}).to.throw(/Path must be absolute/);
});
});
ifdescribe(process.platform !== 'linux')('select-client-certificate event', () => {
let w: BrowserWindow;
before(function () {
session.fromPartition('empty-certificate').setCertificateVerifyProc((req, cb) => { cb(0); });
});
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'empty-certificate'
}
});
});
afterEach(() => closeWindow(w).then(() => { w = null as any; }));
after(() => session.fromPartition('empty-certificate').setCertificateVerifyProc(null));
it('can respond with empty certificate list', async () => {
app.once('select-client-certificate', function (event, webContents, url, list, callback) {
console.log('select-client-certificate emitted');
event.preventDefault();
callback();
});
await w.webContents.loadURL(secureUrl);
expect(w.webContents.getTitle()).to.equal('denied');
});
});
ifdescribe(process.platform === 'win32')('setAsDefaultProtocolClient(protocol, path, args)', () => {
const protocol = 'electron-test';
const updateExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe');
const processStartArgs = [
'--processStart', `"${path.basename(process.execPath)}"`,
'--process-start-args', '"--hidden"'
];
let Winreg: any;
let classesKey: any;
before(function () {
Winreg = require('winreg');
classesKey = new Winreg({
hive: Winreg.HKCU,
key: '\\Software\\Classes\\'
});
});
after(function (done) {
if (process.platform !== 'win32') {
done();
} else {
const protocolKey = new Winreg({
hive: Winreg.HKCU,
key: `\\Software\\Classes\\${protocol}`
});
// The last test leaves the registry dirty,
// delete the protocol key for those of us who test at home
protocolKey.destroy(() => done());
}
});
beforeEach(() => {
app.removeAsDefaultProtocolClient(protocol);
app.removeAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
});
afterEach(() => {
app.removeAsDefaultProtocolClient(protocol);
expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
app.removeAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(false);
});
it('sets the app as the default protocol client', () => {
expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
app.setAsDefaultProtocolClient(protocol);
expect(app.isDefaultProtocolClient(protocol)).to.equal(true);
});
it('allows a custom path and args to be specified', () => {
expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(false);
app.setAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(true);
expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
});
it('creates a registry entry for the protocol class', async () => {
app.setAsDefaultProtocolClient(protocol);
const keys = await promisify(classesKey.keys).call(classesKey) as any[];
const exists = keys.some(key => key.key.includes(protocol));
expect(exists).to.equal(true);
});
it('completely removes a registry entry for the protocol class', async () => {
app.setAsDefaultProtocolClient(protocol);
app.removeAsDefaultProtocolClient(protocol);
const keys = await promisify(classesKey.keys).call(classesKey) as any[];
const exists = keys.some(key => key.key.includes(protocol));
expect(exists).to.equal(false);
});
it('only unsets a class registry key if it contains other data', async () => {
app.setAsDefaultProtocolClient(protocol);
const protocolKey = new Winreg({
hive: Winreg.HKCU,
key: `\\Software\\Classes\\${protocol}`
});
await promisify(protocolKey.set).call(protocolKey, 'test-value', 'REG_BINARY', '123');
app.removeAsDefaultProtocolClient(protocol);
const keys = await promisify(classesKey.keys).call(classesKey) as any[];
const exists = keys.some(key => key.key.includes(protocol));
expect(exists).to.equal(true);
});
it('sets the default client such that getApplicationNameForProtocol returns Electron', () => {
app.setAsDefaultProtocolClient(protocol);
expect(app.getApplicationNameForProtocol(`${protocol}://`)).to.equal('Electron');
});
});
describe('getApplicationNameForProtocol()', () => {
// TODO: Linux CI doesn't have registered http & https handlers
ifit(!(process.env.CI && process.platform === 'linux'))('returns application names for common protocols', function () {
// We can't expect particular app names here, but these protocols should
// at least have _something_ registered. Except on our Linux CI
// environment apparently.
const protocols = [
'http://',
'https://'
];
for (const protocol of protocols) {
expect(app.getApplicationNameForProtocol(protocol)).to.not.equal('');
}
});
it('returns an empty string for a bogus protocol', () => {
expect(app.getApplicationNameForProtocol('bogus-protocol://')).to.equal('');
});
});
ifdescribe(process.platform !== 'linux')('getApplicationInfoForProtocol()', () => {
it('returns promise rejection for a bogus protocol', async function () {
await expect(
app.getApplicationInfoForProtocol('bogus-protocol://')
).to.eventually.be.rejectedWith(
'Unable to retrieve installation path to app'
);
});
it('returns resolved promise with appPath, displayName and icon', async function () {
const appInfo = await app.getApplicationInfoForProtocol('https://');
expect(appInfo.path).not.to.be.undefined();
expect(appInfo.name).not.to.be.undefined();
expect(appInfo.icon).not.to.be.undefined();
});
});
describe('isDefaultProtocolClient()', () => {
it('returns false for a bogus protocol', () => {
expect(app.isDefaultProtocolClient('bogus-protocol://')).to.equal(false);
});
});
ifdescribe(process.platform === 'win32')('app launch through uri', () => {
it('does not launch for argument following a URL', async () => {
const appPath = path.join(fixturesPath, 'api', 'quit-app');
// App should exit with non 123 code.
const first = cp.spawn(process.execPath, [appPath, 'electron-test:?', 'abc']);
const [code] = await once(first, 'exit');
expect(code).to.not.equal(123);
});
it('launches successfully for argument following a file path', async () => {
const appPath = path.join(fixturesPath, 'api', 'quit-app');
// App should exit with code 123.
const first = cp.spawn(process.execPath, [appPath, 'e:\\abc', 'abc']);
const [code] = await once(first, 'exit');
expect(code).to.equal(123);
});
it('launches successfully for multiple URIs following --', async () => {
const appPath = path.join(fixturesPath, 'api', 'quit-app');
// App should exit with code 123.
const first = cp.spawn(process.execPath, [appPath, '--', 'http://electronjs.org', 'electron-test://testdata']);
const [code] = await once(first, 'exit');
expect(code).to.equal(123);
});
});
// FIXME Get these specs running on Linux CI
ifdescribe(process.platform !== 'linux')('getFileIcon() API', () => {
const iconPath = path.join(__dirname, 'fixtures/assets/icon.ico');
const sizes = {
small: 16,
normal: 32,
large: process.platform === 'win32' ? 32 : 48
};
it('fetches a non-empty icon', async () => {
const icon = await app.getFileIcon(iconPath);
expect(icon.isEmpty()).to.equal(false);
});
it('fetches normal icon size by default', async () => {
const icon = await app.getFileIcon(iconPath);
const size = icon.getSize();
expect(size.height).to.equal(sizes.normal);
expect(size.width).to.equal(sizes.normal);
});
describe('size option', () => {
it('fetches a small icon', async () => {
const icon = await app.getFileIcon(iconPath, { size: 'small' });
const size = icon.getSize();
expect(size.height).to.equal(sizes.small);
expect(size.width).to.equal(sizes.small);
});
it('fetches a normal icon', async () => {
const icon = await app.getFileIcon(iconPath, { size: 'normal' });
const size = icon.getSize();
expect(size.height).to.equal(sizes.normal);
expect(size.width).to.equal(sizes.normal);
});
it('fetches a large icon', async () => {
// macOS does not support large icons
if (process.platform === 'darwin') return;
const icon = await app.getFileIcon(iconPath, { size: 'large' });
const size = icon.getSize();
expect(size.height).to.equal(sizes.large);
expect(size.width).to.equal(sizes.large);
});
});
});
describe('getAppMetrics() API', () => {
it('returns memory and cpu stats of all running electron processes', () => {
const appMetrics = app.getAppMetrics();
expect(appMetrics).to.be.an('array').and.have.lengthOf.at.least(1, 'App memory info object is not > 0');
const types = [];
for (const entry of appMetrics) {
expect(entry.pid).to.be.above(0, 'pid is not > 0');
expect(entry.type).to.be.a('string').that.does.not.equal('');
expect(entry.creationTime).to.be.a('number').that.is.greaterThan(0);
types.push(entry.type);
expect(entry.cpu).to.have.ownProperty('percentCPUUsage').that.is.a('number');
expect(entry.cpu).to.have.ownProperty('idleWakeupsPerSecond').that.is.a('number');
expect(entry.memory).to.have.property('workingSetSize').that.is.greaterThan(0);
expect(entry.memory).to.have.property('peakWorkingSetSize').that.is.greaterThan(0);
if (entry.type === 'Utility' || entry.type === 'GPU') {
expect(entry.serviceName).to.be.a('string').that.does.not.equal('');
}
if (entry.type === 'Utility') {
expect(entry).to.have.property('name').that.is.a('string');
}
if (process.platform === 'win32') {
expect(entry.memory).to.have.property('privateBytes').that.is.greaterThan(0);
}
if (process.platform !== 'linux') {
expect(entry.sandboxed).to.be.a('boolean');
}
if (process.platform === 'win32') {
expect(entry.integrityLevel).to.be.a('string');
}
}
if (process.platform === 'darwin') {
expect(types).to.include('GPU');
}
expect(types).to.include('Browser');
});
});
describe('getGPUFeatureStatus() API', () => {
it('returns the graphic features statuses', () => {
const features = app.getGPUFeatureStatus();
expect(features).to.have.ownProperty('webgl').that.is.a('string');
expect(features).to.have.ownProperty('gpu_compositing').that.is.a('string');
});
});
// FIXME https://github.com/electron/electron/issues/24224
ifdescribe(process.platform !== 'linux')('getGPUInfo() API', () => {
const appPath = path.join(fixturesPath, 'api', 'gpu-info.js');
const getGPUInfo = async (type: string) => {
const appProcess = cp.spawn(process.execPath, [appPath, type]);
let gpuInfoData = '';
let errorData = '';
appProcess.stdout.on('data', (data) => {
gpuInfoData += data;
});
appProcess.stderr.on('data', (data) => {
errorData += data;
});
const [exitCode] = await once(appProcess, 'exit');
if (exitCode === 0) {
try {
const [, json] = /HERE COMES THE JSON: (.+) AND THERE IT WAS/.exec(gpuInfoData)!;
// return info data on successful exit
return JSON.parse(json);
} catch (e) {
console.error('Failed to interpret the following as JSON:');
console.error(gpuInfoData);
throw e;
}
} else {
// return error if not clean exit
throw new Error(errorData);
}
};
const verifyBasicGPUInfo = async (gpuInfo: any) => {
// Devices information is always present in the available info.
expect(gpuInfo).to.have.ownProperty('gpuDevice')
.that.is.an('array')
.and.does.not.equal([]);
const device = gpuInfo.gpuDevice[0];
expect(device).to.be.an('object')
.and.to.have.property('deviceId')
.that.is.a('number')
.not.lessThan(0);
};
it('succeeds with basic GPUInfo', async () => {
const gpuInfo = await getGPUInfo('basic');
await verifyBasicGPUInfo(gpuInfo);
});
it('succeeds with complete GPUInfo', async () => {
const completeInfo = await getGPUInfo('complete');
if (process.platform === 'linux') {
// For linux and macOS complete info is same as basic info
await verifyBasicGPUInfo(completeInfo);
const basicInfo = await getGPUInfo('basic');
expect(completeInfo).to.deep.equal(basicInfo);
} else {
// Gl version is present in the complete info.
expect(completeInfo).to.have.ownProperty('auxAttributes')
.that.is.an('object');
if (completeInfo.gpuDevice.active) {
expect(completeInfo.auxAttributes).to.have.ownProperty('glVersion')
.that.is.a('string')
.and.does.not.equal([]);
}
}
});
it('fails for invalid info_type', () => {
const invalidType = 'invalid';
const expectedErrorMessage = "Invalid info type. Use 'basic' or 'complete'";
return expect(app.getGPUInfo(invalidType as any)).to.eventually.be.rejectedWith(expectedErrorMessage);
});
});
ifdescribe(!(process.platform === 'linux' && (process.arch === 'arm64' || process.arch === 'arm')))('sandbox options', () => {
// Our ARM tests are run on VSTS rather than CircleCI, and the Docker
// setup on VSTS disallows syscalls that Chrome requires for setting up
// sandboxing.
// See:
// - https://docs.docker.com/engine/security/seccomp/#significant-syscalls-blocked-by-the-default-profile
// - https://chromium.googlesource.com/chromium/src/+/70.0.3538.124/sandbox/linux/services/credentials.cc#292
// - https://github.com/docker/docker-ce/blob/ba7dfc59ccfe97c79ee0d1379894b35417b40bca/components/engine/profiles/seccomp/seccomp_default.go#L497
// - https://blog.jessfraz.com/post/how-to-use-new-docker-seccomp-profiles/
//
// Adding `--cap-add SYS_ADMIN` or `--security-opt seccomp=unconfined`
// to the Docker invocation allows the syscalls that Chrome needs, but
// are probably more permissive than we'd like.
let appProcess: cp.ChildProcess = null as any;
let server: net.Server = null as any;
const socketPath = process.platform === 'win32' ? '\\\\.\\pipe\\electron-mixed-sandbox' : '/tmp/electron-mixed-sandbox';
beforeEach(function (done) {
fs.unlink(socketPath, () => {
server = net.createServer();
server.listen(socketPath);
done();
});
});
afterEach(done => {
if (appProcess != null) appProcess.kill();
if (server) {
server.close(() => {
if (process.platform === 'win32') {
done();
} else {
fs.unlink(socketPath, () => done());
}
});
} else {
done();
}
});
describe('when app.enableSandbox() is called', () => {
it('adds --enable-sandbox to all renderer processes', done => {
const appPath = path.join(fixturesPath, 'api', 'mixed-sandbox-app');
appProcess = cp.spawn(process.execPath, [appPath, '--app-enable-sandbox'], { stdio: 'inherit' });
server.once('error', error => { done(error); });
server.on('connection', client => {
client.once('data', (data) => {
const argv = JSON.parse(data.toString());
expect(argv.sandbox).to.include('--enable-sandbox');
expect(argv.sandbox).to.not.include('--no-sandbox');
expect(argv.noSandbox).to.include('--enable-sandbox');
expect(argv.noSandbox).to.not.include('--no-sandbox');
expect(argv.noSandboxDevtools).to.equal(true);
expect(argv.sandboxDevtools).to.equal(true);
done();
});
});
});
});
describe('when the app is launched with --enable-sandbox', () => {
it('adds --enable-sandbox to all renderer processes', done => {
const appPath = path.join(fixturesPath, 'api', 'mixed-sandbox-app');
appProcess = cp.spawn(process.execPath, [appPath, '--enable-sandbox'], { stdio: 'inherit' });
server.once('error', error => { done(error); });
server.on('connection', client => {
client.once('data', data => {
const argv = JSON.parse(data.toString());
expect(argv.sandbox).to.include('--enable-sandbox');
expect(argv.sandbox).to.not.include('--no-sandbox');
expect(argv.noSandbox).to.include('--enable-sandbox');
expect(argv.noSandbox).to.not.include('--no-sandbox');
expect(argv.noSandboxDevtools).to.equal(true);
expect(argv.sandboxDevtools).to.equal(true);
done();
});
});
});
});
});
describe('disableDomainBlockingFor3DAPIs() API', () => {
it('throws when called after app is ready', () => {
expect(() => {
app.disableDomainBlockingFor3DAPIs();
}).to.throw(/before app is ready/);
});
});
ifdescribe(process.platform === 'darwin')('app hide and show API', () => {
describe('app.isHidden', () => {
it('returns true when the app is hidden', async () => {
app.hide();
await expect(
waitUntil(() => app.isHidden())
).to.eventually.be.fulfilled();
});
it('returns false when the app is shown', async () => {
app.show();
await expect(
waitUntil(() => !app.isHidden())
).to.eventually.be.fulfilled();
});
});
});
ifdescribe(process.platform === 'darwin')('dock APIs', () => {
after(async () => {
await app.dock.show();
});
describe('dock.setMenu', () => {
it('can be retrieved via dock.getMenu', () => {
expect(app.dock.getMenu()).to.equal(null);
const menu = new Menu();
app.dock.setMenu(menu);
expect(app.dock.getMenu()).to.equal(menu);
});
it('keeps references to the menu', () => {
app.dock.setMenu(new Menu());
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
});
});
describe('dock.setIcon', () => {
it('throws a descriptive error for a bad icon path', () => {
const badPath = path.resolve('I', 'Do', 'Not', 'Exist');
expect(() => {
app.dock.setIcon(badPath);
}).to.throw(/Failed to load image from path (.+)/);
});
});
describe('dock.bounce', () => {
it('should return -1 for unknown bounce type', () => {
expect(app.dock.bounce('bad type' as any)).to.equal(-1);
});
it('should return a positive number for informational type', () => {
const appHasFocus = !!BrowserWindow.getFocusedWindow();
if (!appHasFocus) {
expect(app.dock.bounce('informational')).to.be.at.least(0);
}
});
it('should return a positive number for critical type', () => {
const appHasFocus = !!BrowserWindow.getFocusedWindow();
if (!appHasFocus) {
expect(app.dock.bounce('critical')).to.be.at.least(0);
}
});
});
describe('dock.cancelBounce', () => {
it('should not throw', () => {
app.dock.cancelBounce(app.dock.bounce('critical'));
});
});
describe('dock.setBadge', () => {
after(() => {
app.dock.setBadge('');
});
it('should not throw', () => {
app.dock.setBadge('1');
});
it('should be retrievable via getBadge', () => {
app.dock.setBadge('test');
expect(app.dock.getBadge()).to.equal('test');
});
});
describe('dock.hide', () => {
it('should not throw', () => {
app.dock.hide();
expect(app.dock.isVisible()).to.equal(false);
});
});
// Note that dock.show tests should run after dock.hide tests, to work
// around a bug of macOS.
// See https://github.com/electron/electron/pull/25269 for more.
describe('dock.show', () => {
it('should not throw', () => {
return app.dock.show().then(() => {
expect(app.dock.isVisible()).to.equal(true);
});
});
it('returns a Promise', () => {
expect(app.dock.show()).to.be.a('promise');
});
it('eventually fulfills', async () => {
await expect(app.dock.show()).to.eventually.be.fulfilled.equal(undefined);
});
});
});
describe('whenReady', () => {
it('returns a Promise', () => {
expect(app.whenReady()).to.be.a('promise');
});
it('becomes fulfilled if the app is already ready', async () => {
expect(app.isReady()).to.equal(true);
await expect(app.whenReady()).to.be.eventually.fulfilled.equal(undefined);
});
});
describe('app.applicationMenu', () => {
it('has the applicationMenu property', () => {
expect(app).to.have.property('applicationMenu');
});
});
describe('commandLine.hasSwitch', () => {
it('returns true when present', () => {
app.commandLine.appendSwitch('foobar1');
expect(app.commandLine.hasSwitch('foobar1')).to.equal(true);
});
it('returns false when not present', () => {
expect(app.commandLine.hasSwitch('foobar2')).to.equal(false);
});
});
describe('commandLine.hasSwitch (existing argv)', () => {
it('returns true when present', async () => {
const { hasSwitch } = await runTestApp('command-line', '--foobar');
expect(hasSwitch).to.equal(true);
});
it('returns false when not present', async () => {
const { hasSwitch } = await runTestApp('command-line');
expect(hasSwitch).to.equal(false);
});
});
describe('commandLine.getSwitchValue', () => {
it('returns the value when present', () => {
app.commandLine.appendSwitch('foobar', 'æøΓ₯ΓΌ');
expect(app.commandLine.getSwitchValue('foobar')).to.equal('æøΓ₯ΓΌ');
});
it('returns an empty string when present without value', () => {
app.commandLine.appendSwitch('foobar1');
expect(app.commandLine.getSwitchValue('foobar1')).to.equal('');
});
it('returns an empty string when not present', () => {
expect(app.commandLine.getSwitchValue('foobar2')).to.equal('');
});
});
describe('commandLine.getSwitchValue (existing argv)', () => {
it('returns the value when present', async () => {
const { getSwitchValue } = await runTestApp('command-line', '--foobar=test');
expect(getSwitchValue).to.equal('test');
});
it('returns an empty string when present without value', async () => {
const { getSwitchValue } = await runTestApp('command-line', '--foobar');
expect(getSwitchValue).to.equal('');
});
it('returns an empty string when not present', async () => {
const { getSwitchValue } = await runTestApp('command-line');
expect(getSwitchValue).to.equal('');
});
});
describe('commandLine.removeSwitch', () => {
it('no-ops a non-existent switch', async () => {
expect(app.commandLine.hasSwitch('foobar3')).to.equal(false);
app.commandLine.removeSwitch('foobar3');
expect(app.commandLine.hasSwitch('foobar3')).to.equal(false);
});
it('removes an existing switch', async () => {
app.commandLine.appendSwitch('foobar3', 'test');
expect(app.commandLine.hasSwitch('foobar3')).to.equal(true);
app.commandLine.removeSwitch('foobar3');
expect(app.commandLine.hasSwitch('foobar3')).to.equal(false);
});
});
ifdescribe(process.platform === 'darwin')('app.setSecureKeyboardEntryEnabled', () => {
it('changes Secure Keyboard Entry is enabled', () => {
app.setSecureKeyboardEntryEnabled(true);
expect(app.isSecureKeyboardEntryEnabled()).to.equal(true);
app.setSecureKeyboardEntryEnabled(false);
expect(app.isSecureKeyboardEntryEnabled()).to.equal(false);
});
});
describe('configureHostResolver', () => {
after(() => {
// Returns to the default configuration.
app.configureHostResolver({});
});
it('fails on bad arguments', () => {
expect(() => {
(app.configureHostResolver as any)();
}).to.throw();
expect(() => {
app.configureHostResolver({
secureDnsMode: 'notAValidValue' as any
});
}).to.throw();
expect(() => {
app.configureHostResolver({
secureDnsServers: [123 as any]
});
}).to.throw();
});
it('affects dns lookup behavior', async () => {
// 1. resolve a domain name to check that things are working
await expect(new Promise((resolve, reject) => {
electronNet.request({
method: 'HEAD',
url: 'https://www.electronjs.org'
}).on('response', resolve)
.on('error', reject)
.end();
})).to.eventually.be.fulfilled();
// 2. change the host resolver configuration to something that will
// always fail
app.configureHostResolver({
secureDnsMode: 'secure',
secureDnsServers: ['https://127.0.0.1:1234']
});
// 3. check that resolving domain names now fails
await expect(new Promise((resolve, reject) => {
electronNet.request({
method: 'HEAD',
// Needs to be a slightly different domain to above, otherwise the
// response will come from the cache.
url: 'https://electronjs.org'
}).on('response', resolve)
.on('error', reject)
.end();
})).to.eventually.be.rejectedWith(/ERR_NAME_NOT_RESOLVED/);
});
});
describe('about panel', () => {
it('app.setAboutPanelOptions() does not crash', () => {
app.setAboutPanelOptions({
applicationName: 'electron!!',
version: '1.2.3'
});
});
it('app.showAboutPanel() does not crash & runs asynchronously', () => {
app.showAboutPanel();
});
});
});
describe('default behavior', () => {
describe('application menu', () => {
it('creates the default menu if the app does not set it', async () => {
const result = await runTestApp('default-menu');
expect(result).to.equal(false);
});
it('does not create the default menu if the app sets a custom menu', async () => {
const result = await runTestApp('default-menu', '--custom-menu');
expect(result).to.equal(true);
});
it('does not create the default menu if the app sets a null menu', async () => {
const result = await runTestApp('default-menu', '--null-menu');
expect(result).to.equal(true);
});
});
describe('window-all-closed', () => {
afterEach(closeAllWindows);
it('quits when the app does not handle the event', async () => {
const result = await runTestApp('window-all-closed');
expect(result).to.equal(false);
});
it('does not quit when the app handles the event', async () => {
const result = await runTestApp('window-all-closed', '--handle-event');
expect(result).to.equal(true);
});
it('should omit closed windows from getAllWindows', async () => {
const w = new BrowserWindow({ show: false });
const len = new Promise(resolve => {
app.on('window-all-closed', () => {
resolve(BrowserWindow.getAllWindows().length);
});
});
w.close();
expect(await len).to.equal(0);
});
});
describe('user agent fallback', () => {
let initialValue: string;
before(() => {
initialValue = app.userAgentFallback!;
});
it('should have a reasonable default', () => {
expect(initialValue).to.include(`Electron/${process.versions.electron}`);
expect(initialValue).to.include(`Chrome/${process.versions.chrome}`);
});
it('should be overridable', () => {
app.userAgentFallback = 'test-agent/123';
expect(app.userAgentFallback).to.equal('test-agent/123');
});
it('should be restorable', () => {
app.userAgentFallback = 'test-agent/123';
app.userAgentFallback = '';
expect(app.userAgentFallback).to.equal(initialValue);
});
});
describe('login event', () => {
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((request, response) => {
if (request.headers.authorization) {
return response.end('ok');
}
response
.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' })
.end();
});
serverUrl = (await listen(server)).url;
});
it('should emit a login event on app when a WebContents hits a 401', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL(serverUrl);
const [, webContents] = await once(app, 'login') as [any, WebContents];
expect(webContents).to.equal(w.webContents);
});
});
describe('running under ARM64 translation', () => {
it('does not throw an error', () => {
if (process.platform === 'darwin' || process.platform === 'win32') {
expect(app.runningUnderARM64Translation).not.to.be.undefined();
expect(() => {
return app.runningUnderARM64Translation;
}).not.to.throw();
} else {
expect(app.runningUnderARM64Translation).to.be.undefined();
}
});
});
});
async function runTestApp (name: string, ...args: any[]) {
const appPath = path.join(fixturesPath, 'api', name);
const electronPath = process.execPath;
const appProcess = cp.spawn(electronPath, [appPath, ...args]);
let output = '';
appProcess.stdout.on('data', (data) => { output += data; });
await once(appProcess.stdout, 'end');
return JSON.parse(output);
}
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 37,560 |
[Bug]: Open at login with setLoginItemSettings in MAS build is not working
|
### 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
16.0.6
### What operating system are you using?
macOS
### Operating System Version
Version 13.2 (22D49)
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Setting app to open at login with setLoginItemSettings api should work both locally and with MAS build.
Locally the app is added to login items but when i build it for MAS this doesn't work.
### Actual Behavior
Setting app to open at login with setLoginItemSettings api works locally but doesn't work in MAS build.
In MAS build the app is not added to login items.
<img width="477" alt="image" src="https://user-images.githubusercontent.com/17458685/224576455-a9145dfc-7121-4097-9fe4-a472f0c2ead4.png">
### Testcase Gist URL
_No response_
### Additional Information
According to docs https://www.electronjs.org/docs/latest/api/app#appsetloginitemsettingssettings-macos-windows setting login item in MAS build should work by using the following API
```js
app.setLoginItemSettings({
openAtLogin: openAtLogin,
})
```
In the docs on limitations of MAS build there is no mention of any limitation of using above API https://www.electronjs.org/docs/latest/tutorial/mac-app-store-submission-guide#limitations-of-mas-build
Here is possible related issue and PRs:
- https://github.com/electron/electron/issues/7312
- https://github.com/electron/electron/pull/11144
- https://github.com/electron/electron/pull/10856
|
https://github.com/electron/electron/issues/37560
|
https://github.com/electron/electron/pull/37244
|
6d0d350e138494cd68dd3d4fa73b2719da4575bf
|
f7b1c75c72a8dcab4157408f92bd3771606d8029
| 2023-03-12T22:11:32Z |
c++
| 2023-10-16T16:25:11Z |
docs/api/app.md
|
# app
> Control your application's event lifecycle.
Process: [Main](../glossary.md#main-process)
The following example shows how to quit the application when the last window is
closed:
```js
const { app } = require('electron')
app.on('window-all-closed', () => {
app.quit()
})
```
## Events
The `app` object emits the following events:
### Event: 'will-finish-launching'
Emitted when the application has finished basic startup. On Windows and Linux,
the `will-finish-launching` event is the same as the `ready` event; on macOS,
this event represents the `applicationWillFinishLaunching` notification of
`NSApplication`.
In most cases, you should do everything in the `ready` event handler.
### Event: 'ready'
Returns:
* `event` Event
* `launchInfo` Record<string, any> | [NotificationResponse](structures/notification-response.md) _macOS_
Emitted once, when Electron has finished initializing. On macOS, `launchInfo`
holds the `userInfo` of the [`NSUserNotification`](https://developer.apple.com/documentation/foundation/nsusernotification)
or information from [`UNNotificationResponse`](https://developer.apple.com/documentation/usernotifications/unnotificationresponse)
that was used to open the application, if it was launched from Notification Center.
You can also call `app.isReady()` to check if this event has already fired and `app.whenReady()`
to get a Promise that is fulfilled when Electron is initialized.
### Event: 'window-all-closed'
Emitted when all windows have been closed.
If you do not subscribe to this event and all windows are closed, the default
behavior is to quit the app; however, if you subscribe, you control whether the
app quits or not. If the user pressed `Cmd + Q`, or the developer called
`app.quit()`, Electron will first try to close all the windows and then emit the
`will-quit` event, and in this case the `window-all-closed` event would not be
emitted.
### Event: 'before-quit'
Returns:
* `event` Event
Emitted before the application starts closing its windows.
Calling `event.preventDefault()` will prevent the default behavior, which is
terminating the application.
**Note:** If application quit was initiated by `autoUpdater.quitAndInstall()`,
then `before-quit` is emitted _after_ emitting `close` event on all windows and
closing them.
**Note:** On Windows, this event will not be emitted if the app is closed due
to a shutdown/restart of the system or a user logout.
### Event: 'will-quit'
Returns:
* `event` Event
Emitted when all windows have been closed and the application will quit.
Calling `event.preventDefault()` will prevent the default behavior, which is
terminating the application.
See the description of the `window-all-closed` event for the differences between
the `will-quit` and `window-all-closed` events.
**Note:** On Windows, this event will not be emitted if the app is closed due
to a shutdown/restart of the system or a user logout.
### Event: 'quit'
Returns:
* `event` Event
* `exitCode` Integer
Emitted when the application is quitting.
**Note:** On Windows, this event will not be emitted if the app is closed due
to a shutdown/restart of the system or a user logout.
### Event: 'open-file' _macOS_
Returns:
* `event` Event
* `path` string
Emitted when the user wants to open a file with the application. The `open-file`
event is usually emitted when the application is already open and the OS wants
to reuse the application to open the file. `open-file` is also emitted when a
file is dropped onto the dock and the application is not yet running. Make sure
to listen for the `open-file` event very early in your application startup to
handle this case (even before the `ready` event is emitted).
You should call `event.preventDefault()` if you want to handle this event.
On Windows, you have to parse `process.argv` (in the main process) to get the
filepath.
### Event: 'open-url' _macOS_
Returns:
* `event` Event
* `url` string
Emitted when the user wants to open a URL with the application. Your application's
`Info.plist` file must define the URL scheme within the `CFBundleURLTypes` key, and
set `NSPrincipalClass` to `AtomApplication`.
As with the `open-file` event, be sure to register a listener for the `open-url`
event early in your application startup to detect if the application is being opened to handle a URL.
If you register the listener in response to a `ready` event, you'll miss URLs that trigger the launch of your application.
### Event: 'activate' _macOS_
Returns:
* `event` Event
* `hasVisibleWindows` boolean
Emitted when the application is activated. Various actions can trigger
this event, such as launching the application for the first time, attempting
to re-launch the application when it's already running, or clicking on the
application's dock or taskbar icon.
### Event: 'did-become-active' _macOS_
Returns:
* `event` Event
Emitted when the application becomes active. This differs from the `activate` event in
that `did-become-active` is emitted every time the app becomes active, not only
when Dock icon is clicked or application is re-launched. It is also emitted when a user
switches to the app via the macOS App Switcher.
### Event: 'did-resign-active' _macOS_
Returns:
* `event` Event
Emitted when the app is no longer active and doesnβt have focus. This can be triggered,
for example, by clicking on another application or by using the macOS App Switcher to
switch to another application.
### Event: 'continue-activity' _macOS_
Returns:
* `event` Event
* `type` string - A string identifying the activity. Maps to
[`NSUserActivity.activityType`][activity-type].
* `userInfo` unknown - Contains app-specific state stored by the activity on
another device.
* `details` Object
* `webpageURL` string (optional) - A string identifying the URL of the webpage accessed by the activity on another device, if available.
Emitted during [Handoff][handoff] when an activity from a different device wants
to be resumed. You should call `event.preventDefault()` if you want to handle
this event.
A user activity can be continued only in an app that has the same developer Team
ID as the activity's source app and that supports the activity's type.
Supported activity types are specified in the app's `Info.plist` under the
`NSUserActivityTypes` key.
### Event: 'will-continue-activity' _macOS_
Returns:
* `event` Event
* `type` string - A string identifying the activity. Maps to
[`NSUserActivity.activityType`][activity-type].
Emitted during [Handoff][handoff] before an activity from a different device wants
to be resumed. You should call `event.preventDefault()` if you want to handle
this event.
### Event: 'continue-activity-error' _macOS_
Returns:
* `event` Event
* `type` string - A string identifying the activity. Maps to
[`NSUserActivity.activityType`][activity-type].
* `error` string - A string with the error's localized description.
Emitted during [Handoff][handoff] when an activity from a different device
fails to be resumed.
### Event: 'activity-was-continued' _macOS_
Returns:
* `event` Event
* `type` string - A string identifying the activity. Maps to
[`NSUserActivity.activityType`][activity-type].
* `userInfo` unknown - Contains app-specific state stored by the activity.
Emitted during [Handoff][handoff] after an activity from this device was successfully
resumed on another one.
### Event: 'update-activity-state' _macOS_
Returns:
* `event` Event
* `type` string - A string identifying the activity. Maps to
[`NSUserActivity.activityType`][activity-type].
* `userInfo` unknown - Contains app-specific state stored by the activity.
Emitted when [Handoff][handoff] is about to be resumed on another device. If you need to update the state to be transferred, you should call `event.preventDefault()` immediately, construct a new `userInfo` dictionary and call `app.updateCurrentActivity()` in a timely manner. Otherwise, the operation will fail and `continue-activity-error` will be called.
### Event: 'new-window-for-tab' _macOS_
Returns:
* `event` Event
Emitted when the user clicks the native macOS new tab button. The new
tab button is only visible if the current `BrowserWindow` has a
`tabbingIdentifier`
### Event: 'browser-window-blur'
Returns:
* `event` Event
* `window` [BrowserWindow](browser-window.md)
Emitted when a [browserWindow](browser-window.md) gets blurred.
### Event: 'browser-window-focus'
Returns:
* `event` Event
* `window` [BrowserWindow](browser-window.md)
Emitted when a [browserWindow](browser-window.md) gets focused.
### Event: 'browser-window-created'
Returns:
* `event` Event
* `window` [BrowserWindow](browser-window.md)
Emitted when a new [browserWindow](browser-window.md) is created.
### Event: 'web-contents-created'
Returns:
* `event` Event
* `webContents` [WebContents](web-contents.md)
Emitted when a new [webContents](web-contents.md) is created.
### Event: 'certificate-error'
Returns:
* `event` Event
* `webContents` [WebContents](web-contents.md)
* `url` string
* `error` string - The error code
* `certificate` [Certificate](structures/certificate.md)
* `callback` Function
* `isTrusted` boolean - Whether to consider the certificate as trusted
* `isMainFrame` boolean
Emitted when failed to verify the `certificate` for `url`, to trust the
certificate you should prevent the default behavior with
`event.preventDefault()` and call `callback(true)`.
```js
const { app } = require('electron')
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
if (url === 'https://github.com') {
// Verification logic.
event.preventDefault()
callback(true)
} else {
callback(false)
}
})
```
### Event: 'select-client-certificate'
Returns:
* `event` Event
* `webContents` [WebContents](web-contents.md)
* `url` URL
* `certificateList` [Certificate[]](structures/certificate.md)
* `callback` Function
* `certificate` [Certificate](structures/certificate.md) (optional)
Emitted when a client certificate is requested.
The `url` corresponds to the navigation entry requesting the client certificate
and `callback` can be called with an entry filtered from the list. Using
`event.preventDefault()` prevents the application from using the first
certificate from the store.
```js
const { app } = require('electron')
app.on('select-client-certificate', (event, webContents, url, list, callback) => {
event.preventDefault()
callback(list[0])
})
```
### Event: 'login'
Returns:
* `event` Event
* `webContents` [WebContents](web-contents.md)
* `authenticationResponseDetails` Object
* `url` URL
* `authInfo` Object
* `isProxy` boolean
* `scheme` string
* `host` string
* `port` Integer
* `realm` string
* `callback` Function
* `username` string (optional)
* `password` string (optional)
Emitted when `webContents` wants to do basic auth.
The default behavior is to cancel all authentications. To override this you
should prevent the default behavior with `event.preventDefault()` and call
`callback(username, password)` with the credentials.
```js
const { app } = require('electron')
app.on('login', (event, webContents, details, authInfo, callback) => {
event.preventDefault()
callback('username', 'secret')
})
```
If `callback` is called without a username or password, the authentication
request will be cancelled and the authentication error will be returned to the
page.
### Event: 'gpu-info-update'
Emitted whenever there is a GPU info update.
### Event: 'gpu-process-crashed' _Deprecated_
Returns:
* `event` Event
* `killed` boolean
Emitted when the GPU process crashes or is killed.
**Deprecated:** This event is superceded by the `child-process-gone` event
which contains more information about why the child process disappeared. It
isn't always because it crashed. The `killed` boolean can be replaced by
checking `reason === 'killed'` when you switch to that event.
### Event: 'renderer-process-crashed' _Deprecated_
Returns:
* `event` Event
* `webContents` [WebContents](web-contents.md)
* `killed` boolean
Emitted when the renderer process of `webContents` crashes or is killed.
**Deprecated:** This event is superceded by the `render-process-gone` event
which contains more information about why the render process disappeared. It
isn't always because it crashed. The `killed` boolean can be replaced by
checking `reason === 'killed'` when you switch to that event.
### Event: 'render-process-gone'
Returns:
* `event` Event
* `webContents` [WebContents](web-contents.md)
* `details` [RenderProcessGoneDetails](structures/render-process-gone-details.md)
Emitted when the renderer process unexpectedly disappears. This is normally
because it was crashed or killed.
### Event: 'child-process-gone'
Returns:
* `event` Event
* `details` Object
* `type` string - Process type. One of the following values:
* `Utility`
* `Zygote`
* `Sandbox helper`
* `GPU`
* `Pepper Plugin`
* `Pepper Plugin Broker`
* `Unknown`
* `reason` string - The reason the child process is gone. Possible values:
* `clean-exit` - Process exited with an exit code of zero
* `abnormal-exit` - Process exited with a non-zero exit code
* `killed` - Process was sent a SIGTERM or otherwise killed externally
* `crashed` - Process crashed
* `oom` - Process ran out of memory
* `launch-failed` - Process never successfully launched
* `integrity-failure` - Windows code integrity checks failed
* `exitCode` number - The exit code for the process
(e.g. status from waitpid if on posix, from GetExitCodeProcess on Windows).
* `serviceName` string (optional) - The non-localized name of the process.
* `name` string (optional) - The name of the process.
Examples for utility: `Audio Service`, `Content Decryption Module Service`, `Network Service`, `Video Capture`, etc.
Emitted when the child process unexpectedly disappears. This is normally
because it was crashed or killed. It does not include renderer processes.
### Event: 'accessibility-support-changed' _macOS_ _Windows_
Returns:
* `event` Event
* `accessibilitySupportEnabled` boolean - `true` when Chrome's accessibility
support is enabled, `false` otherwise.
Emitted when Chrome's accessibility support changes. This event fires when
assistive technologies, such as screen readers, are enabled or disabled.
See https://www.chromium.org/developers/design-documents/accessibility for more
details.
### Event: 'session-created'
Returns:
* `session` [Session](session.md)
Emitted when Electron has created a new `session`.
```js
const { app } = require('electron')
app.on('session-created', (session) => {
console.log(session)
})
```
### Event: 'second-instance'
Returns:
* `event` Event
* `argv` string[] - An array of the second instance's command line arguments
* `workingDirectory` string - The second instance's working directory
* `additionalData` unknown - A JSON object of additional data passed from the second instance
This event will be emitted inside the primary instance of your application
when a second instance has been executed and calls `app.requestSingleInstanceLock()`.
`argv` is an Array of the second instance's command line arguments,
and `workingDirectory` is its current working directory. Usually
applications respond to this by making their primary window focused and
non-minimized.
**Note:** `argv` will not be exactly the same list of arguments as those passed
to the second instance. The order might change and additional arguments might be appended.
If you need to maintain the exact same arguments, it's advised to use `additionalData` instead.
**Note:** If the second instance is started by a different user than the first, the `argv` array will not include the arguments.
This event is guaranteed to be emitted after the `ready` event of `app`
gets emitted.
**Note:** Extra command line arguments might be added by Chromium,
such as `--original-process-start-time`.
## Methods
The `app` object has the following methods:
**Note:** Some methods are only available on specific operating systems and are
labeled as such.
### `app.quit()`
Try to close all windows. The `before-quit` event will be emitted first. If all
windows are successfully closed, the `will-quit` event will be emitted and by
default the application will terminate.
This method guarantees that all `beforeunload` and `unload` event handlers are
correctly executed. It is possible that a window cancels the quitting by
returning `false` in the `beforeunload` event handler.
### `app.exit([exitCode])`
* `exitCode` Integer (optional)
Exits immediately with `exitCode`. `exitCode` defaults to 0.
All windows will be closed immediately without asking the user, and the `before-quit`
and `will-quit` events will not be emitted.
### `app.relaunch([options])`
* `options` Object (optional)
* `args` string[] (optional)
* `execPath` string (optional)
Relaunches the app when current instance exits.
By default, the new instance will use the same working directory and command line
arguments with current instance. When `args` is specified, the `args` will be
passed as command line arguments instead. When `execPath` is specified, the
`execPath` will be executed for relaunch instead of current app.
Note that this method does not quit the app when executed, you have to call
`app.quit` or `app.exit` after calling `app.relaunch` to make the app restart.
When `app.relaunch` is called for multiple times, multiple instances will be
started after current instance exited.
An example of restarting current instance immediately and adding a new command
line argument to the new instance:
```js
const { app } = require('electron')
app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) })
app.exit(0)
```
### `app.isReady()`
Returns `boolean` - `true` if Electron has finished initializing, `false` otherwise.
See also `app.whenReady()`.
### `app.whenReady()`
Returns `Promise<void>` - fulfilled when Electron is initialized.
May be used as a convenient alternative to checking `app.isReady()`
and subscribing to the `ready` event if the app is not ready yet.
### `app.focus([options])`
* `options` Object (optional)
* `steal` boolean _macOS_ - Make the receiver the active app even if another app is
currently active.
On Linux, focuses on the first visible window. On macOS, makes the application
the active app. On Windows, focuses on the application's first window.
You should seek to use the `steal` option as sparingly as possible.
### `app.hide()` _macOS_
Hides all application windows without minimizing them.
### `app.isHidden()` _macOS_
Returns `boolean` - `true` if the applicationβincluding all of its windowsβis hidden (e.g. with `Command-H`), `false` otherwise.
### `app.show()` _macOS_
Shows application windows after they were hidden. Does not automatically focus
them.
### `app.setAppLogsPath([path])`
* `path` string (optional) - A custom path for your logs. Must be absolute.
Sets or creates a directory your app's logs which can then be manipulated with `app.getPath()` or `app.setPath(pathName, newPath)`.
Calling `app.setAppLogsPath()` without a `path` parameter will result in this directory being set to `~/Library/Logs/YourAppName` on _macOS_, and inside the `userData` directory on _Linux_ and _Windows_.
### `app.getAppPath()`
Returns `string` - The current application directory.
### `app.getPath(name)`
* `name` string - You can request the following paths by the name:
* `home` User's home directory.
* `appData` Per-user application data directory, which by default points to:
* `%APPDATA%` on Windows
* `$XDG_CONFIG_HOME` or `~/.config` on Linux
* `~/Library/Application Support` on macOS
* `userData` The directory for storing your app's configuration files, which
by default is the `appData` directory appended with your app's name. By
convention files storing user data should be written to this directory, and
it is not recommended to write large files here because some environments
may backup this directory to cloud storage.
* `sessionData` The directory for storing data generated by `Session`, such
as localStorage, cookies, disk cache, downloaded dictionaries, network
state, devtools files. By default this points to `userData`. Chromium may
write very large disk cache here, so if your app does not rely on browser
storage like localStorage or cookies to save user data, it is recommended
to set this directory to other locations to avoid polluting the `userData`
directory.
* `temp` Temporary directory.
* `exe` The current executable file.
* `module` The `libchromiumcontent` library.
* `desktop` The current user's Desktop directory.
* `documents` Directory for a user's "My Documents".
* `downloads` Directory for a user's downloads.
* `music` Directory for a user's music.
* `pictures` Directory for a user's pictures.
* `videos` Directory for a user's videos.
* `recent` Directory for the user's recent files (Windows only).
* `logs` Directory for your app's log folder.
* `crashDumps` Directory where crash dumps are stored.
Returns `string` - A path to a special directory or file associated with `name`. On
failure, an `Error` is thrown.
If `app.getPath('logs')` is called without called `app.setAppLogsPath()` being called first, a default log directory will be created equivalent to calling `app.setAppLogsPath()` without a `path` parameter.
### `app.getFileIcon(path[, options])`
* `path` string
* `options` Object (optional)
* `size` string
* `small` - 16x16
* `normal` - 32x32
* `large` - 48x48 on _Linux_, 32x32 on _Windows_, unsupported on _macOS_.
Returns `Promise<NativeImage>` - fulfilled with the app's icon, which is a [NativeImage](native-image.md).
Fetches a path's associated icon.
On _Windows_, there a 2 kinds of icons:
* Icons associated with certain file extensions, like `.mp3`, `.png`, etc.
* Icons inside the file itself, like `.exe`, `.dll`, `.ico`.
On _Linux_ and _macOS_, icons depend on the application associated with file mime type.
### `app.setPath(name, path)`
* `name` string
* `path` string
Overrides the `path` to a special directory or file associated with `name`.
If the path specifies a directory that does not exist, an `Error` is thrown.
In that case, the directory should be created with `fs.mkdirSync` or similar.
You can only override paths of a `name` defined in `app.getPath`.
By default, web pages' cookies and caches will be stored under the `sessionData`
directory. If you want to change this location, you have to override the
`sessionData` path before the `ready` event of the `app` module is emitted.
### `app.getVersion()`
Returns `string` - The version of the loaded application. If no version is found in the
application's `package.json` file, the version of the current bundle or
executable is returned.
### `app.getName()`
Returns `string` - The current application's name, which is the name in the application's
`package.json` file.
Usually the `name` field of `package.json` is a short lowercase name, according
to the npm modules spec. You should usually also specify a `productName`
field, which is your application's full capitalized name, and which will be
preferred over `name` by Electron.
### `app.setName(name)`
* `name` string
Overrides the current application's name.
**Note:** This function overrides the name used internally by Electron; it does not affect the name that the OS uses.
### `app.getLocale()`
Returns `string` - The current application locale, fetched using Chromium's `l10n_util` library.
Possible return values are documented [here](https://source.chromium.org/chromium/chromium/src/+/main:ui/base/l10n/l10n_util.cc).
To set the locale, you'll want to use a command line switch at app startup, which may be found [here](command-line-switches.md).
**Note:** When distributing your packaged app, you have to also ship the
`locales` folder.
**Note:** This API must be called after the `ready` event is emitted.
**Note:** To see example return values of this API compared to other locale and language APIs, see [`app.getPreferredSystemLanguages()`](#appgetpreferredsystemlanguages).
### `app.getLocaleCountryCode()`
Returns `string` - User operating system's locale two-letter [ISO 3166](https://www.iso.org/iso-3166-country-codes.html) country code. The value is taken from native OS APIs.
**Note:** When unable to detect locale country code, it returns empty string.
### `app.getSystemLocale()`
Returns `string` - The current system locale. On Windows and Linux, it is fetched using Chromium's `i18n` library. On macOS, `[NSLocale currentLocale]` is used instead. To get the user's current system language, which is not always the same as the locale, it is better to use [`app.getPreferredSystemLanguages()`](#appgetpreferredsystemlanguages).
Different operating systems also use the regional data differently:
* Windows 11 uses the regional format for numbers, dates, and times.
* macOS Monterey uses the region for formatting numbers, dates, times, and for selecting the currency symbol to use.
Therefore, this API can be used for purposes such as choosing a format for rendering dates and times in a calendar app, especially when the developer wants the format to be consistent with the OS.
**Note:** This API must be called after the `ready` event is emitted.
**Note:** To see example return values of this API compared to other locale and language APIs, see [`app.getPreferredSystemLanguages()`](#appgetpreferredsystemlanguages).
### `app.getPreferredSystemLanguages()`
Returns `string[]` - The user's preferred system languages from most preferred to least preferred, including the country codes if applicable. A user can modify and add to this list on Windows or macOS through the Language and Region settings.
The API uses `GlobalizationPreferences` (with a fallback to `GetSystemPreferredUILanguages`) on Windows, `\[NSLocale preferredLanguages\]` on macOS, and `g_get_language_names` on Linux.
This API can be used for purposes such as deciding what language to present the application in.
Here are some examples of return values of the various language and locale APIs with different configurations:
On Windows, given application locale is German, the regional format is Finnish (Finland), and the preferred system languages from most to least preferred are French (Canada), English (US), Simplified Chinese (China), Finnish, and Spanish (Latin America):
```js
app.getLocale() // 'de'
app.getSystemLocale() // 'fi-FI'
app.getPreferredSystemLanguages() // ['fr-CA', 'en-US', 'zh-Hans-CN', 'fi', 'es-419']
```
On macOS, given the application locale is German, the region is Finland, and the preferred system languages from most to least preferred are French (Canada), English (US), Simplified Chinese, and Spanish (Latin America):
```js
app.getLocale() // 'de'
app.getSystemLocale() // 'fr-FI'
app.getPreferredSystemLanguages() // ['fr-CA', 'en-US', 'zh-Hans-FI', 'es-419']
```
Both the available languages and regions and the possible return values differ between the two operating systems.
As can be seen with the example above, on Windows, it is possible that a preferred system language has no country code, and that one of the preferred system languages corresponds with the language used for the regional format. On macOS, the region serves more as a default country code: the user doesn't need to have Finnish as a preferred language to use Finland as the region,and the country code `FI` is used as the country code for preferred system languages that do not have associated countries in the language name.
### `app.addRecentDocument(path)` _macOS_ _Windows_
* `path` string
Adds `path` to the recent documents list.
This list is managed by the OS. On Windows, you can visit the list from the task
bar, and on macOS, you can visit it from dock menu.
### `app.clearRecentDocuments()` _macOS_ _Windows_
Clears the recent documents list.
### `app.setAsDefaultProtocolClient(protocol[, path, args])`
* `protocol` string - The name of your protocol, without `://`. For example,
if you want your app to handle `electron://` links, call this method with
`electron` as the parameter.
* `path` string (optional) _Windows_ - The path to the Electron executable.
Defaults to `process.execPath`
* `args` string[] (optional) _Windows_ - Arguments passed to the executable.
Defaults to an empty array
Returns `boolean` - Whether the call succeeded.
Sets the current executable as the default handler for a protocol (aka URI
scheme). It allows you to integrate your app deeper into the operating system.
Once registered, all links with `your-protocol://` will be opened with the
current executable. The whole link, including protocol, will be passed to your
application as a parameter.
**Note:** On macOS, you can only register protocols that have been added to
your app's `info.plist`, which cannot be modified at runtime. However, you can
change the file during build time via [Electron Forge][electron-forge],
[Electron Packager][electron-packager], or by editing `info.plist` with a text
editor. Please refer to [Apple's documentation][CFBundleURLTypes] for details.
**Note:** In a Windows Store environment (when packaged as an `appx`) this API
will return `true` for all calls but the registry key it sets won't be accessible
by other applications. In order to register your Windows Store application
as a default protocol handler you must [declare the protocol in your manifest](https://learn.microsoft.com/en-us/uwp/schemas/appxpackage/uapmanifestschema/element-uap-protocol).
The API uses the Windows Registry and `LSSetDefaultHandlerForURLScheme` internally.
### `app.removeAsDefaultProtocolClient(protocol[, path, args])` _macOS_ _Windows_
* `protocol` string - The name of your protocol, without `://`.
* `path` string (optional) _Windows_ - Defaults to `process.execPath`
* `args` string[] (optional) _Windows_ - Defaults to an empty array
Returns `boolean` - Whether the call succeeded.
This method checks if the current executable as the default handler for a
protocol (aka URI scheme). If so, it will remove the app as the default handler.
### `app.isDefaultProtocolClient(protocol[, path, args])`
* `protocol` string - The name of your protocol, without `://`.
* `path` string (optional) _Windows_ - Defaults to `process.execPath`
* `args` string[] (optional) _Windows_ - Defaults to an empty array
Returns `boolean` - Whether the current executable is the default handler for a
protocol (aka URI scheme).
**Note:** On macOS, you can use this method to check if the app has been
registered as the default protocol handler for a protocol. You can also verify
this by checking `~/Library/Preferences/com.apple.LaunchServices.plist` on the
macOS machine. Please refer to
[Apple's documentation][LSCopyDefaultHandlerForURLScheme] for details.
The API uses the Windows Registry and `LSCopyDefaultHandlerForURLScheme` internally.
### `app.getApplicationNameForProtocol(url)`
* `url` string - a URL with the protocol name to check. Unlike the other
methods in this family, this accepts an entire URL, including `://` at a
minimum (e.g. `https://`).
Returns `string` - Name of the application handling the protocol, or an empty
string if there is no handler. For instance, if Electron is the default
handler of the URL, this could be `Electron` on Windows and Mac. However,
don't rely on the precise format which is not guaranteed to remain unchanged.
Expect a different format on Linux, possibly with a `.desktop` suffix.
This method returns the application name of the default handler for the protocol
(aka URI scheme) of a URL.
### `app.getApplicationInfoForProtocol(url)` _macOS_ _Windows_
* `url` string - a URL with the protocol name to check. Unlike the other
methods in this family, this accepts an entire URL, including `://` at a
minimum (e.g. `https://`).
Returns `Promise<Object>` - Resolve with an object containing the following:
* `icon` NativeImage - the display icon of the app handling the protocol.
* `path` string - installation path of the app handling the protocol.
* `name` string - display name of the app handling the protocol.
This method returns a promise that contains the application name, icon and path of the default handler for the protocol
(aka URI scheme) of a URL.
### `app.setUserTasks(tasks)` _Windows_
* `tasks` [Task[]](structures/task.md) - Array of `Task` objects
Adds `tasks` to the [Tasks][tasks] category of the Jump List on Windows.
`tasks` is an array of [`Task`](structures/task.md) objects.
Returns `boolean` - Whether the call succeeded.
**Note:** If you'd like to customize the Jump List even more use
`app.setJumpList(categories)` instead.
### `app.getJumpListSettings()` _Windows_
Returns `Object`:
* `minItems` Integer - The minimum number of items that will be shown in the
Jump List (for a more detailed description of this value see the
[MSDN docs][JumpListBeginListMSDN]).
* `removedItems` [JumpListItem[]](structures/jump-list-item.md) - Array of `JumpListItem`
objects that correspond to items that the user has explicitly removed from custom categories in the
Jump List. These items must not be re-added to the Jump List in the **next**
call to `app.setJumpList()`, Windows will not display any custom category
that contains any of the removed items.
### `app.setJumpList(categories)` _Windows_
* `categories` [JumpListCategory[]](structures/jump-list-category.md) | `null` - Array of `JumpListCategory` objects.
Returns `string`
Sets or removes a custom Jump List for the application, and returns one of the
following strings:
* `ok` - Nothing went wrong.
* `error` - One or more errors occurred, enable runtime logging to figure out
the likely cause.
* `invalidSeparatorError` - An attempt was made to add a separator to a
custom category in the Jump List. Separators are only allowed in the
standard `Tasks` category.
* `fileTypeRegistrationError` - An attempt was made to add a file link to
the Jump List for a file type the app isn't registered to handle.
* `customCategoryAccessDeniedError` - Custom categories can't be added to the
Jump List due to user privacy or group policy settings.
If `categories` is `null` the previously set custom Jump List (if any) will be
replaced by the standard Jump List for the app (managed by Windows).
**Note:** If a `JumpListCategory` object has neither the `type` nor the `name`
property set then its `type` is assumed to be `tasks`. If the `name` property
is set but the `type` property is omitted then the `type` is assumed to be
`custom`.
**Note:** Users can remove items from custom categories, and Windows will not
allow a removed item to be added back into a custom category until **after**
the next successful call to `app.setJumpList(categories)`. Any attempt to
re-add a removed item to a custom category earlier than that will result in the
entire custom category being omitted from the Jump List. The list of removed
items can be obtained using `app.getJumpListSettings()`.
**Note:** The maximum length of a Jump List item's `description` property is
260 characters. Beyond this limit, the item will not be added to the Jump
List, nor will it be displayed.
Here's a very simple example of creating a custom Jump List:
```js
const { app } = require('electron')
app.setJumpList([
{
type: 'custom',
name: 'Recent Projects',
items: [
{ type: 'file', path: 'C:\\Projects\\project1.proj' },
{ type: 'file', path: 'C:\\Projects\\project2.proj' }
]
},
{ // has a name so `type` is assumed to be "custom"
name: 'Tools',
items: [
{
type: 'task',
title: 'Tool A',
program: process.execPath,
args: '--run-tool-a',
iconPath: process.execPath,
iconIndex: 0,
description: 'Runs Tool A'
},
{
type: 'task',
title: 'Tool B',
program: process.execPath,
args: '--run-tool-b',
iconPath: process.execPath,
iconIndex: 0,
description: 'Runs Tool B'
}
]
},
{ type: 'frequent' },
{ // has no name and no type so `type` is assumed to be "tasks"
items: [
{
type: 'task',
title: 'New Project',
program: process.execPath,
args: '--new-project',
description: 'Create a new project.'
},
{ type: 'separator' },
{
type: 'task',
title: 'Recover Project',
program: process.execPath,
args: '--recover-project',
description: 'Recover Project'
}
]
}
])
```
### `app.requestSingleInstanceLock([additionalData])`
* `additionalData` Record<any, any> (optional) - A JSON object containing additional data to send to the first instance.
Returns `boolean`
The return value of this method indicates whether or not this instance of your
application successfully obtained the lock. If it failed to obtain the lock,
you can assume that another instance of your application is already running with
the lock and exit immediately.
I.e. This method returns `true` if your process is the primary instance of your
application and your app should continue loading. It returns `false` if your
process should immediately quit as it has sent its parameters to another
instance that has already acquired the lock.
On macOS, the system enforces single instance automatically when users try to open
a second instance of your app in Finder, and the `open-file` and `open-url`
events will be emitted for that. However when users start your app in command
line, the system's single instance mechanism will be bypassed, and you have to
use this method to ensure single instance.
An example of activating the window of primary instance when a second instance
starts:
```js
const { app, BrowserWindow } = require('electron')
let myWindow = null
const additionalData = { myKey: 'myValue' }
const gotTheLock = app.requestSingleInstanceLock(additionalData)
if (!gotTheLock) {
app.quit()
} else {
app.on('second-instance', (event, commandLine, workingDirectory, additionalData) => {
// Print out data received from the second instance.
console.log(additionalData)
// Someone tried to run a second instance, we should focus our window.
if (myWindow) {
if (myWindow.isMinimized()) myWindow.restore()
myWindow.focus()
}
})
app.whenReady().then(() => {
myWindow = new BrowserWindow({})
myWindow.loadURL('https://electronjs.org')
})
}
```
### `app.hasSingleInstanceLock()`
Returns `boolean`
This method returns whether or not this instance of your app is currently
holding the single instance lock. You can request the lock with
`app.requestSingleInstanceLock()` and release with
`app.releaseSingleInstanceLock()`
### `app.releaseSingleInstanceLock()`
Releases all locks that were created by `requestSingleInstanceLock`. This will
allow multiple instances of the application to once again run side by side.
### `app.setUserActivity(type, userInfo[, webpageURL])` _macOS_
* `type` string - Uniquely identifies the activity. Maps to
[`NSUserActivity.activityType`][activity-type].
* `userInfo` any - App-specific state to store for use by another device.
* `webpageURL` string (optional) - The webpage to load in a browser if no suitable app is
installed on the resuming device. The scheme must be `http` or `https`.
Creates an `NSUserActivity` and sets it as the current activity. The activity
is eligible for [Handoff][handoff] to another device afterward.
### `app.getCurrentActivityType()` _macOS_
Returns `string` - The type of the currently running activity.
### `app.invalidateCurrentActivity()` _macOS_
Invalidates the current [Handoff][handoff] user activity.
### `app.resignCurrentActivity()` _macOS_
Marks the current [Handoff][handoff] user activity as inactive without invalidating it.
### `app.updateCurrentActivity(type, userInfo)` _macOS_
* `type` string - Uniquely identifies the activity. Maps to
[`NSUserActivity.activityType`][activity-type].
* `userInfo` any - App-specific state to store for use by another device.
Updates the current activity if its type matches `type`, merging the entries from
`userInfo` into its current `userInfo` dictionary.
### `app.setAppUserModelId(id)` _Windows_
* `id` string
Changes the [Application User Model ID][app-user-model-id] to `id`.
### `app.setActivationPolicy(policy)` _macOS_
* `policy` string - Can be 'regular', 'accessory', or 'prohibited'.
Sets the activation policy for a given app.
Activation policy types:
* 'regular' - The application is an ordinary app that appears in the Dock and may have a user interface.
* 'accessory' - The application doesnβt appear in the Dock and doesnβt have a menu bar, but it may be activated programmatically or by clicking on one of its windows.
* 'prohibited' - The application doesnβt appear in the Dock and may not create windows or be activated.
### `app.importCertificate(options, callback)` _Linux_
* `options` Object
* `certificate` string - Path for the pkcs12 file.
* `password` string - Passphrase for the certificate.
* `callback` Function
* `result` Integer - Result of import.
Imports the certificate in pkcs12 format into the platform certificate store.
`callback` is called with the `result` of import operation, a value of `0`
indicates success while any other value indicates failure according to Chromium [net_error_list](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h).
### `app.configureHostResolver(options)`
* `options` Object
* `enableBuiltInResolver` boolean (optional) - Whether the built-in host
resolver is used in preference to getaddrinfo. When enabled, the built-in
resolver will attempt to use the system's DNS settings to do DNS lookups
itself. Enabled by default on macOS, disabled by default on Windows and
Linux.
* `secureDnsMode` string (optional) - Can be 'off', 'automatic' or 'secure'.
Configures the DNS-over-HTTP mode. When 'off', no DoH lookups will be
performed. When 'automatic', DoH lookups will be performed first if DoH is
available, and insecure DNS lookups will be performed as a fallback. When
'secure', only DoH lookups will be performed. Defaults to 'automatic'.
* `secureDnsServers` string[] (optional) - A list of DNS-over-HTTP
server templates. See [RFC8484 Β§ 3][] for details on the template format.
Most servers support the POST method; the template for such servers is
simply a URI. Note that for [some DNS providers][doh-providers], the
resolver will automatically upgrade to DoH unless DoH is explicitly
disabled, even if there are no DoH servers provided in this list.
* `enableAdditionalDnsQueryTypes` boolean (optional) - Controls whether additional DNS
query types, e.g. HTTPS (DNS type 65) will be allowed besides the
traditional A and AAAA queries when a request is being made via insecure
DNS. Has no effect on Secure DNS which always allows additional types.
Defaults to true.
Configures host resolution (DNS and DNS-over-HTTPS). By default, the following
resolvers will be used, in order:
1. DNS-over-HTTPS, if the [DNS provider supports it][doh-providers], then
2. the built-in resolver (enabled on macOS only by default), then
3. the system's resolver (e.g. `getaddrinfo`).
This can be configured to either restrict usage of non-encrypted DNS
(`secureDnsMode: "secure"`), or disable DNS-over-HTTPS (`secureDnsMode:
"off"`). It is also possible to enable or disable the built-in resolver.
To disable insecure DNS, you can specify a `secureDnsMode` of `"secure"`. If you do
so, you should make sure to provide a list of DNS-over-HTTPS servers to use, in
case the user's DNS configuration does not include a provider that supports
DoH.
```js
const { app } = require('electron')
app.whenReady().then(() => {
app.configureHostResolver({
secureDnsMode: 'secure',
secureDnsServers: [
'https://cloudflare-dns.com/dns-query'
]
})
})
```
This API must be called after the `ready` event is emitted.
[doh-providers]: https://source.chromium.org/chromium/chromium/src/+/main:net/dns/public/doh_provider_entry.cc;l=31?q=%22DohProviderEntry::GetList()%22&ss=chromium%2Fchromium%2Fsrc
[RFC8484 Β§ 3]: https://datatracker.ietf.org/doc/html/rfc8484#section-3
### `app.disableHardwareAcceleration()`
Disables hardware acceleration for current app.
This method can only be called before app is ready.
### `app.disableDomainBlockingFor3DAPIs()`
By default, Chromium disables 3D APIs (e.g. WebGL) until restart on a per
domain basis if the GPU processes crashes too frequently. This function
disables that behavior.
This method can only be called before app is ready.
### `app.getAppMetrics()`
Returns [`ProcessMetric[]`](structures/process-metric.md): Array of `ProcessMetric` objects that correspond to memory and CPU usage statistics of all the processes associated with the app.
### `app.getGPUFeatureStatus()`
Returns [`GPUFeatureStatus`](structures/gpu-feature-status.md) - The Graphics Feature Status from `chrome://gpu/`.
**Note:** This information is only usable after the `gpu-info-update` event is emitted.
### `app.getGPUInfo(infoType)`
* `infoType` string - Can be `basic` or `complete`.
Returns `Promise<unknown>`
For `infoType` equal to `complete`:
Promise is fulfilled with `Object` containing all the GPU Information as in [chromium's GPUInfo object](https://chromium.googlesource.com/chromium/src/+/4178e190e9da409b055e5dff469911ec6f6b716f/gpu/config/gpu_info.cc). This includes the version and driver information that's shown on `chrome://gpu` page.
For `infoType` equal to `basic`:
Promise is fulfilled with `Object` containing fewer attributes than when requested with `complete`. Here's an example of basic response:
```js
{
auxAttributes:
{
amdSwitchable: true,
canSupportThreadedTextureMailbox: false,
directComposition: false,
directRendering: true,
glResetNotificationStrategy: 0,
inProcessGpu: true,
initializationTime: 0,
jpegDecodeAcceleratorSupported: false,
optimus: false,
passthroughCmdDecoder: false,
sandboxed: false,
softwareRendering: false,
supportsOverlays: false,
videoDecodeAcceleratorFlags: 0
},
gpuDevice:
[{ active: true, deviceId: 26657, vendorId: 4098 },
{ active: false, deviceId: 3366, vendorId: 32902 }],
machineModelName: 'MacBookPro',
machineModelVersion: '11.5'
}
```
Using `basic` should be preferred if only basic information like `vendorId` or `deviceId` is needed.
### `app.setBadgeCount([count])` _Linux_ _macOS_
* `count` Integer (optional) - If a value is provided, set the badge to the provided value otherwise, on macOS, display a plain white dot (e.g. unknown number of notifications). On Linux, if a value is not provided the badge will not display.
Returns `boolean` - Whether the call succeeded.
Sets the counter badge for current app. Setting the count to `0` will hide the
badge.
On macOS, it shows on the dock icon. On Linux, it only works for Unity launcher.
**Note:** Unity launcher requires a `.desktop` file to work. For more information,
please read the [Unity integration documentation][unity-requirement].
**Note:** On macOS, you need to ensure that your application has the permission
to display notifications for this method to work.
### `app.getBadgeCount()` _Linux_ _macOS_
Returns `Integer` - The current value displayed in the counter badge.
### `app.isUnityRunning()` _Linux_
Returns `boolean` - Whether the current desktop environment is Unity launcher.
### `app.getLoginItemSettings([options])` _macOS_ _Windows_
* `options` Object (optional)
* `path` string (optional) _Windows_ - The executable path to compare against.
Defaults to `process.execPath`.
* `args` string[] (optional) _Windows_ - The command-line arguments to compare
against. Defaults to an empty array.
If you provided `path` and `args` options to `app.setLoginItemSettings`, then you
need to pass the same arguments here for `openAtLogin` to be set correctly.
Returns `Object`:
* `openAtLogin` boolean - `true` if the app is set to open at login.
* `openAsHidden` boolean _macOS_ - `true` if the app is set to open as hidden at login.
This setting is not available on [MAS builds][mas-builds].
* `wasOpenedAtLogin` boolean _macOS_ - `true` if the app was opened at login
automatically. This setting is not available on [MAS builds][mas-builds].
* `wasOpenedAsHidden` boolean _macOS_ - `true` if the app was opened as a hidden login
item. This indicates that the app should not open any windows at startup.
This setting is not available on [MAS builds][mas-builds].
* `restoreState` boolean _macOS_ - `true` if the app was opened as a login item that
should restore the state from the previous session. This indicates that the
app should restore the windows that were open the last time the app was
closed. This setting is not available on [MAS builds][mas-builds].
* `executableWillLaunchAtLogin` boolean _Windows_ - `true` if app is set to open at login and its run key is not deactivated. This differs from `openAtLogin` as it ignores the `args` option, this property will be true if the given executable would be launched at login with **any** arguments.
* `launchItems` Object[] _Windows_
* `name` string _Windows_ - name value of a registry entry.
* `path` string _Windows_ - The executable to an app that corresponds to a registry entry.
* `args` string[] _Windows_ - the command-line arguments to pass to the executable.
* `scope` string _Windows_ - one of `user` or `machine`. Indicates whether the registry entry is under `HKEY_CURRENT USER` or `HKEY_LOCAL_MACHINE`.
* `enabled` boolean _Windows_ - `true` if the app registry key is startup approved and therefore shows as `enabled` in Task Manager and Windows settings.
### `app.setLoginItemSettings(settings)` _macOS_ _Windows_
* `settings` Object
* `openAtLogin` boolean (optional) - `true` to open the app at login, `false` to remove
the app as a login item. Defaults to `false`.
* `openAsHidden` boolean (optional) _macOS_ - `true` to open the app as hidden. Defaults to
`false`. The user can edit this setting from the System Preferences so
`app.getLoginItemSettings().wasOpenedAsHidden` should be checked when the app
is opened to know the current value. This setting is not available on [MAS builds][mas-builds].
* `path` string (optional) _Windows_ - The executable to launch at login.
Defaults to `process.execPath`.
* `args` string[] (optional) _Windows_ - The command-line arguments to pass to
the executable. Defaults to an empty array. Take care to wrap paths in
quotes.
* `enabled` boolean (optional) _Windows_ - `true` will change the startup approved registry key and `enable / disable` the App in Task Manager and Windows Settings.
Defaults to `true`.
* `name` string (optional) _Windows_ - value name to write into registry. Defaults to the app's AppUserModelId().
Set the app's login item settings.
To work with Electron's `autoUpdater` on Windows, which uses [Squirrel][Squirrel-Windows],
you'll want to set the launch path to Update.exe, and pass arguments that specify your
application name. For example:
``` js
const { app } = require('electron')
const path = require('node:path')
const appFolder = path.dirname(process.execPath)
const updateExe = path.resolve(appFolder, '..', 'Update.exe')
const exeName = path.basename(process.execPath)
app.setLoginItemSettings({
openAtLogin: true,
path: updateExe,
args: [
'--processStart', `"${exeName}"`,
'--process-start-args', '"--hidden"'
]
})
```
### `app.isAccessibilitySupportEnabled()` _macOS_ _Windows_
Returns `boolean` - `true` if Chrome's accessibility support is enabled,
`false` otherwise. This API will return `true` if the use of assistive
technologies, such as screen readers, has been detected. See
https://www.chromium.org/developers/design-documents/accessibility for more
details.
### `app.setAccessibilitySupportEnabled(enabled)` _macOS_ _Windows_
* `enabled` boolean - Enable or disable [accessibility tree](https://developers.google.com/web/fundamentals/accessibility/semantics-builtin/the-accessibility-tree) rendering
Manually enables Chrome's accessibility support, allowing to expose accessibility switch to users in application settings. See [Chromium's accessibility docs](https://www.chromium.org/developers/design-documents/accessibility) for more
details. Disabled by default.
This API must be called after the `ready` event is emitted.
**Note:** Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default.
### `app.showAboutPanel()`
Show the app's about panel options. These options can be overridden with `app.setAboutPanelOptions(options)`. This function runs asynchronously.
### `app.setAboutPanelOptions(options)`
* `options` Object
* `applicationName` string (optional) - The app's name.
* `applicationVersion` string (optional) - The app's version.
* `copyright` string (optional) - Copyright information.
* `version` string (optional) _macOS_ - The app's build version number.
* `credits` string (optional) _macOS_ _Windows_ - Credit information.
* `authors` string[] (optional) _Linux_ - List of app authors.
* `website` string (optional) _Linux_ - The app's website.
* `iconPath` string (optional) _Linux_ _Windows_ - Path to the app's icon in a JPEG or PNG file format. On Linux, will be shown as 64x64 pixels while retaining aspect ratio.
Set the about panel options. This will override the values defined in the app's `.plist` file on macOS. See the [Apple docs][about-panel-options] for more details. On Linux, values must be set in order to be shown; there are no defaults.
If you do not set `credits` but still wish to surface them in your app, AppKit will look for a file named "Credits.html", "Credits.rtf", and "Credits.rtfd", in that order, in the bundle returned by the NSBundle class method main. The first file found is used, and if none is found, the info area is left blank. See Apple [documentation](https://developer.apple.com/documentation/appkit/nsaboutpaneloptioncredits?language=objc) for more information.
### `app.isEmojiPanelSupported()`
Returns `boolean` - whether or not the current OS version allows for native emoji pickers.
### `app.showEmojiPanel()` _macOS_ _Windows_
Show the platform's native emoji picker.
### `app.startAccessingSecurityScopedResource(bookmarkData)` _mas_
* `bookmarkData` string - The base64 encoded security scoped bookmark data returned by the `dialog.showOpenDialog` or `dialog.showSaveDialog` methods.
Returns `Function` - This function **must** be called once you have finished accessing the security scoped file. If you do not remember to stop accessing the bookmark, [kernel resources will be leaked](https://developer.apple.com/reference/foundation/nsurl/1417051-startaccessingsecurityscopedreso?language=objc) and your app will lose its ability to reach outside the sandbox completely, until your app is restarted.
```js
const { app, dialog } = require('electron')
const fs = require('node:fs')
let filepath
let bookmark
dialog.showOpenDialog(null, { securityScopedBookmarks: true }).then(({ filePaths, bookmarks }) => {
filepath = filePaths[0]
bookmark = bookmarks[0]
fs.readFileSync(filepath)
})
// ... restart app ...
const stopAccessingSecurityScopedResource = app.startAccessingSecurityScopedResource(bookmark)
fs.readFileSync(filepath)
stopAccessingSecurityScopedResource()
```
Start accessing a security scoped resource. With this method Electron applications that are packaged for the Mac App Store may reach outside their sandbox to access files chosen by the user. See [Apple's documentation](https://developer.apple.com/library/content/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16) for a description of how this system works.
### `app.enableSandbox()`
Enables full sandbox mode on the app. This means that all renderers will be launched sandboxed, regardless of the value of the `sandbox` flag in [`WebPreferences`](structures/web-preferences.md).
This method can only be called before app is ready.
### `app.isInApplicationsFolder()` _macOS_
Returns `boolean` - Whether the application is currently running from the
systems Application folder. Use in combination with `app.moveToApplicationsFolder()`
### `app.moveToApplicationsFolder([options])` _macOS_
* `options` Object (optional)
* `conflictHandler` Function\<boolean> (optional) - A handler for potential conflict in move failure.
* `conflictType` string - The type of move conflict encountered by the handler; can be `exists` or `existsAndRunning`, where `exists` means that an app of the same name is present in the Applications directory and `existsAndRunning` means both that it exists and that it's presently running.
Returns `boolean` - Whether the move was successful. Please note that if
the move is successful, your application will quit and relaunch.
No confirmation dialog will be presented by default. If you wish to allow
the user to confirm the operation, you may do so using the
[`dialog`](dialog.md) API.
**NOTE:** This method throws errors if anything other than the user causes the
move to fail. For instance if the user cancels the authorization dialog, this
method returns false. If we fail to perform the copy, then this method will
throw an error. The message in the error should be informative and tell
you exactly what went wrong.
By default, if an app of the same name as the one being moved exists in the Applications directory and is _not_ running, the existing app will be trashed and the active app moved into its place. If it _is_ running, the preexisting running app will assume focus and the previously active app will quit itself. This behavior can be changed by providing the optional conflict handler, where the boolean returned by the handler determines whether or not the move conflict is resolved with default behavior. i.e. returning `false` will ensure no further action is taken, returning `true` will result in the default behavior and the method continuing.
For example:
```js
const { app, dialog } = require('electron')
app.moveToApplicationsFolder({
conflictHandler: (conflictType) => {
if (conflictType === 'exists') {
return dialog.showMessageBoxSync({
type: 'question',
buttons: ['Halt Move', 'Continue Move'],
defaultId: 0,
message: 'An app of this name already exists'
}) === 1
}
}
})
```
Would mean that if an app already exists in the user directory, if the user chooses to 'Continue Move' then the function would continue with its default behavior and the existing app will be trashed and the active app moved into its place.
### `app.isSecureKeyboardEntryEnabled()` _macOS_
Returns `boolean` - whether `Secure Keyboard Entry` is enabled.
By default this API will return `false`.
### `app.setSecureKeyboardEntryEnabled(enabled)` _macOS_
* `enabled` boolean - Enable or disable `Secure Keyboard Entry`
Set the `Secure Keyboard Entry` is enabled in your application.
By using this API, important information such as password and other sensitive information can be prevented from being intercepted by other processes.
See [Apple's documentation](https://developer.apple.com/library/archive/technotes/tn2150/_index.html) for more
details.
**Note:** Enable `Secure Keyboard Entry` only when it is needed and disable it when it is no longer needed.
## Properties
### `app.accessibilitySupportEnabled` _macOS_ _Windows_
A `boolean` property that's `true` if Chrome's accessibility support is enabled, `false` otherwise. This property will be `true` if the use of assistive technologies, such as screen readers, has been detected. Setting this property to `true` manually enables Chrome's accessibility support, allowing developers to expose accessibility switch to users in application settings.
See [Chromium's accessibility docs](https://www.chromium.org/developers/design-documents/accessibility) for more details. Disabled by default.
This API must be called after the `ready` event is emitted.
**Note:** Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default.
### `app.applicationMenu`
A `Menu | null` property that returns [`Menu`](menu.md) if one has been set and `null` otherwise.
Users can pass a [Menu](menu.md) to set this property.
### `app.badgeCount` _Linux_ _macOS_
An `Integer` property that returns the badge count for current app. Setting the count to `0` will hide the badge.
On macOS, setting this with any nonzero integer shows on the dock icon. On Linux, this property only works for Unity launcher.
**Note:** Unity launcher requires a `.desktop` file to work. For more information,
please read the [Unity integration documentation][unity-requirement].
**Note:** On macOS, you need to ensure that your application has the permission
to display notifications for this property to take effect.
### `app.commandLine` _Readonly_
A [`CommandLine`](./command-line.md) object that allows you to read and manipulate the
command line arguments that Chromium uses.
### `app.dock` _macOS_ _Readonly_
A [`Dock`](./dock.md) `| undefined` object that allows you to perform actions on your app icon in the user's
dock on macOS.
### `app.isPackaged` _Readonly_
A `boolean` property that returns `true` if the app is packaged, `false` otherwise. For many apps, this property can be used to distinguish development and production environments.
[tasks]:https://learn.microsoft.com/en-us/windows/win32/shell/taskbar-extensions#tasks
[app-user-model-id]: https://learn.microsoft.com/en-us/windows/win32/shell/appids
[electron-forge]: https://www.electronforge.io/
[electron-packager]: https://github.com/electron/electron-packager
[CFBundleURLTypes]: https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115
[LSCopyDefaultHandlerForURLScheme]: https://developer.apple.com/documentation/coreservices/1441725-lscopydefaulthandlerforurlscheme?language=objc
[handoff]: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/Handoff/HandoffFundamentals/HandoffFundamentals.html
[activity-type]: https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSUserActivity_Class/index.html#//apple_ref/occ/instp/NSUserActivity/activityType
[unity-requirement]: https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles#Adding_shortcuts_to_a_launcher
[mas-builds]: ../tutorial/mac-app-store-submission-guide.md
[Squirrel-Windows]: https://github.com/Squirrel/Squirrel.Windows
[JumpListBeginListMSDN]: https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-icustomdestinationlist-beginlist
[about-panel-options]: https://developer.apple.com/reference/appkit/nsapplication/1428479-orderfrontstandardaboutpanelwith?language=objc
### `app.name`
A `string` property that indicates the current application's name, which is the name in the application's `package.json` file.
Usually the `name` field of `package.json` is a short lowercase name, according
to the npm modules spec. You should usually also specify a `productName`
field, which is your application's full capitalized name, and which will be
preferred over `name` by Electron.
### `app.userAgentFallback`
A `string` which is the user agent string Electron will use as a global fallback.
This is the user agent that will be used when no user agent is set at the
`webContents` or `session` level. It is useful for ensuring that your entire
app has the same user agent. Set to a custom value as early as possible
in your app's initialization to ensure that your overridden value is used.
### `app.runningUnderARM64Translation` _Readonly_ _macOS_ _Windows_
A `boolean` which when `true` indicates that the app is currently running under
an ARM64 translator (like the macOS
[Rosetta Translator Environment](https://en.wikipedia.org/wiki/Rosetta_(software))
or Windows [WOW](https://en.wikipedia.org/wiki/Windows_on_Windows)).
You can use this property to prompt users to download the arm64 version of
your application when they are mistakenly running the x64 version under Rosetta or WOW.
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 37,560 |
[Bug]: Open at login with setLoginItemSettings in MAS build is not working
|
### 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
16.0.6
### What operating system are you using?
macOS
### Operating System Version
Version 13.2 (22D49)
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Setting app to open at login with setLoginItemSettings api should work both locally and with MAS build.
Locally the app is added to login items but when i build it for MAS this doesn't work.
### Actual Behavior
Setting app to open at login with setLoginItemSettings api works locally but doesn't work in MAS build.
In MAS build the app is not added to login items.
<img width="477" alt="image" src="https://user-images.githubusercontent.com/17458685/224576455-a9145dfc-7121-4097-9fe4-a472f0c2ead4.png">
### Testcase Gist URL
_No response_
### Additional Information
According to docs https://www.electronjs.org/docs/latest/api/app#appsetloginitemsettingssettings-macos-windows setting login item in MAS build should work by using the following API
```js
app.setLoginItemSettings({
openAtLogin: openAtLogin,
})
```
In the docs on limitations of MAS build there is no mention of any limitation of using above API https://www.electronjs.org/docs/latest/tutorial/mac-app-store-submission-guide#limitations-of-mas-build
Here is possible related issue and PRs:
- https://github.com/electron/electron/issues/7312
- https://github.com/electron/electron/pull/11144
- https://github.com/electron/electron/pull/10856
|
https://github.com/electron/electron/issues/37560
|
https://github.com/electron/electron/pull/37244
|
6d0d350e138494cd68dd3d4fa73b2719da4575bf
|
f7b1c75c72a8dcab4157408f92bd3771606d8029
| 2023-03-12T22:11:32Z |
c++
| 2023-10-16T16:25:11Z |
shell/browser/api/electron_api_app.cc
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_app.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/command_line.h"
#include "base/containers/fixed_flat_map.h"
#include "base/containers/span.h"
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/callback_helpers.h"
#include "base/path_service.h"
#include "base/system/sys_info.h"
#include "base/values.h"
#include "base/win/windows_version.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/icon_manager.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_paths.h"
#include "content/browser/gpu/compositor_util.h" // nogncheck
#include "content/browser/gpu/gpu_data_manager_impl.h" // nogncheck
#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/browser_child_process_host.h"
#include "content/public/browser/child_process_data.h"
#include "content/public/browser/client_certificate_delegate.h"
#include "content/public/browser/gpu_data_manager.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/common/content_switches.h"
#include "crypto/crypto_buildflags.h"
#include "media/audio/audio_manager.h"
#include "net/dns/public/dns_over_https_config.h"
#include "net/dns/public/dns_over_https_server_config.h"
#include "net/dns/public/util.h"
#include "net/ssl/client_cert_identity.h"
#include "net/ssl/ssl_cert_request_info.h"
#include "net/ssl/ssl_private_key.h"
#include "sandbox/policy/switches.h"
#include "services/network/network_service.h"
#include "shell/app/command_line_args.h"
#include "shell/browser/api/electron_api_menu.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/api/electron_api_utility_process.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/api/gpuinfo_manager.h"
#include "shell/browser/browser_process_impl.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/javascript_environment.h"
#include "shell/browser/login_handler.h"
#include "shell/browser/relauncher.h"
#include "shell/common/application_info.h"
#include "shell/common/electron_command_line.h"
#include "shell/common/electron_paths.h"
#include "shell/common/gin_converters/base_converter.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/language_util.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/platform_util.h"
#include "shell/common/thread_restrictions.h"
#include "shell/common/v8_value_serializer.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/gfx/image/image.h"
#if BUILDFLAG(IS_WIN)
#include "base/strings/utf_string_conversions.h"
#include "shell/browser/ui/win/jump_list.h"
#endif
#if BUILDFLAG(IS_MAC)
#include <CoreFoundation/CoreFoundation.h>
#include "shell/browser/ui/cocoa/electron_bundle_mover.h"
#endif
using electron::Browser;
namespace gin {
#if BUILDFLAG(IS_WIN)
template <>
struct Converter<electron::ProcessIntegrityLevel> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
electron::ProcessIntegrityLevel value) {
switch (value) {
case electron::ProcessIntegrityLevel::kUntrusted:
return StringToV8(isolate, "untrusted");
case electron::ProcessIntegrityLevel::kLow:
return StringToV8(isolate, "low");
case electron::ProcessIntegrityLevel::kMedium:
return StringToV8(isolate, "medium");
case electron::ProcessIntegrityLevel::kHigh:
return StringToV8(isolate, "high");
default:
return StringToV8(isolate, "unknown");
}
}
};
template <>
struct Converter<Browser::UserTask> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
Browser::UserTask* out) {
gin_helper::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
if (!dict.Get("program", &(out->program)) ||
!dict.Get("title", &(out->title)))
return false;
if (dict.Get("iconPath", &(out->icon_path)) &&
!dict.Get("iconIndex", &(out->icon_index)))
return false;
dict.Get("arguments", &(out->arguments));
dict.Get("description", &(out->description));
dict.Get("workingDirectory", &(out->working_dir));
return true;
}
};
using electron::JumpListCategory;
using electron::JumpListItem;
using electron::JumpListResult;
template <>
struct Converter<JumpListItem::Type> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
JumpListItem::Type* out) {
return FromV8WithLookup(isolate, val, Lookup, out);
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
JumpListItem::Type val) {
for (const auto& [name, item_val] : Lookup)
if (item_val == val)
return gin::ConvertToV8(isolate, name);
return gin::ConvertToV8(isolate, "");
}
private:
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, JumpListItem::Type>({
{"file", JumpListItem::Type::kFile},
{"separator", JumpListItem::Type::kSeparator},
{"task", JumpListItem::Type::kTask},
});
};
template <>
struct Converter<JumpListItem> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
JumpListItem* out) {
gin_helper::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
if (!dict.Get("type", &(out->type)))
return false;
switch (out->type) {
case JumpListItem::Type::kTask:
if (!dict.Get("program", &(out->path)) ||
!dict.Get("title", &(out->title)))
return false;
if (dict.Get("iconPath", &(out->icon_path)) &&
!dict.Get("iconIndex", &(out->icon_index)))
return false;
dict.Get("args", &(out->arguments));
dict.Get("description", &(out->description));
dict.Get("workingDirectory", &(out->working_dir));
return true;
case JumpListItem::Type::kSeparator:
return true;
case JumpListItem::Type::kFile:
return dict.Get("path", &(out->path));
}
assert(false);
return false;
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
const JumpListItem& val) {
auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
dict.Set("type", val.type);
switch (val.type) {
case JumpListItem::Type::kTask:
dict.Set("program", val.path);
dict.Set("args", val.arguments);
dict.Set("title", val.title);
dict.Set("iconPath", val.icon_path);
dict.Set("iconIndex", val.icon_index);
dict.Set("description", val.description);
dict.Set("workingDirectory", val.working_dir);
break;
case JumpListItem::Type::kSeparator:
break;
case JumpListItem::Type::kFile:
dict.Set("path", val.path);
break;
}
return dict.GetHandle();
}
};
template <>
struct Converter<JumpListCategory::Type> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
JumpListCategory::Type* out) {
return FromV8WithLookup(isolate, val, Lookup, out);
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
JumpListCategory::Type val) {
for (const auto& [name, type_val] : Lookup)
if (type_val == val)
return gin::ConvertToV8(isolate, name);
return gin::ConvertToV8(isolate, "");
}
private:
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, JumpListCategory::Type>({
{"custom", JumpListCategory::Type::kCustom},
{"frequent", JumpListCategory::Type::kFrequent},
{"recent", JumpListCategory::Type::kRecent},
{"tasks", JumpListCategory::Type::kTasks},
});
};
template <>
struct Converter<JumpListCategory> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
JumpListCategory* out) {
gin_helper::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
if (dict.Get("name", &(out->name)) && out->name.empty())
return false;
if (!dict.Get("type", &(out->type))) {
if (out->name.empty())
out->type = JumpListCategory::Type::kTasks;
else
out->type = JumpListCategory::Type::kCustom;
}
if ((out->type == JumpListCategory::Type::kTasks) ||
(out->type == JumpListCategory::Type::kCustom)) {
if (!dict.Get("items", &(out->items)))
return false;
}
return true;
}
};
// static
template <>
struct Converter<JumpListResult> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, JumpListResult val) {
std::string result_code;
switch (val) {
case JumpListResult::kSuccess:
result_code = "ok";
break;
case JumpListResult::kArgumentError:
result_code = "argumentError";
break;
case JumpListResult::kGenericError:
result_code = "error";
break;
case JumpListResult::kCustomCategorySeparatorError:
result_code = "invalidSeparatorError";
break;
case JumpListResult::kMissingFileTypeRegistrationError:
result_code = "fileTypeRegistrationError";
break;
case JumpListResult::kCustomCategoryAccessDeniedError:
result_code = "customCategoryAccessDeniedError";
break;
}
return ConvertToV8(isolate, result_code);
}
};
#endif
#if BUILDFLAG(IS_WIN)
template <>
struct Converter<Browser::LaunchItem> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
Browser::LaunchItem* out) {
gin_helper::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
dict.Get("name", &(out->name));
dict.Get("path", &(out->path));
dict.Get("args", &(out->args));
dict.Get("scope", &(out->scope));
dict.Get("enabled", &(out->enabled));
return true;
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
Browser::LaunchItem val) {
auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
dict.Set("name", val.name);
dict.Set("path", val.path);
dict.Set("args", val.args);
dict.Set("scope", val.scope);
dict.Set("enabled", val.enabled);
return dict.GetHandle();
}
};
#endif
template <>
struct Converter<Browser::LoginItemSettings> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
Browser::LoginItemSettings* out) {
gin_helper::Dictionary dict;
if (!ConvertFromV8(isolate, val, &dict))
return false;
dict.Get("openAtLogin", &(out->open_at_login));
dict.Get("openAsHidden", &(out->open_as_hidden));
dict.Get("path", &(out->path));
dict.Get("args", &(out->args));
#if BUILDFLAG(IS_WIN)
dict.Get("enabled", &(out->enabled));
dict.Get("name", &(out->name));
#endif
return true;
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
Browser::LoginItemSettings val) {
auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
dict.Set("openAtLogin", val.open_at_login);
dict.Set("openAsHidden", val.open_as_hidden);
dict.Set("restoreState", val.restore_state);
dict.Set("wasOpenedAtLogin", val.opened_at_login);
dict.Set("wasOpenedAsHidden", val.opened_as_hidden);
#if BUILDFLAG(IS_WIN)
dict.Set("launchItems", val.launch_items);
dict.Set("executableWillLaunchAtLogin",
val.executable_will_launch_at_login);
#endif
return dict.GetHandle();
}
};
template <>
struct Converter<content::CertificateRequestResultType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
content::CertificateRequestResultType* out) {
bool b;
if (!ConvertFromV8(isolate, val, &b))
return false;
*out = b ? content::CERTIFICATE_REQUEST_RESULT_TYPE_CONTINUE
: content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
return true;
}
};
template <>
struct Converter<net::SecureDnsMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
net::SecureDnsMode* out) {
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, net::SecureDnsMode>({
{"automatic", net::SecureDnsMode::kAutomatic},
{"off", net::SecureDnsMode::kOff},
{"secure", net::SecureDnsMode::kSecure},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
} // namespace gin
namespace electron::api {
gin::WrapperInfo App::kWrapperInfo = {gin::kEmbedderNativeGin};
namespace {
IconLoader::IconSize GetIconSizeByString(const std::string& size) {
if (size == "small") {
return IconLoader::IconSize::SMALL;
} else if (size == "large") {
return IconLoader::IconSize::LARGE;
}
return IconLoader::IconSize::NORMAL;
}
// Return the path constant from string.
int GetPathConstant(base::StringPiece name) {
// clang-format off
constexpr auto Lookup = base::MakeFixedFlatMapSorted<base::StringPiece, int>({
{"appData", DIR_APP_DATA},
#if BUILDFLAG(IS_POSIX)
{"cache", base::DIR_CACHE},
#else
{"cache", base::DIR_ROAMING_APP_DATA},
#endif
{"crashDumps", DIR_CRASH_DUMPS},
{"desktop", base::DIR_USER_DESKTOP},
{"documents", chrome::DIR_USER_DOCUMENTS},
{"downloads", chrome::DIR_DEFAULT_DOWNLOADS},
{"exe", base::FILE_EXE},
{"home", base::DIR_HOME},
{"logs", DIR_APP_LOGS},
{"module", base::FILE_MODULE},
{"music", chrome::DIR_USER_MUSIC},
{"pictures", chrome::DIR_USER_PICTURES},
#if BUILDFLAG(IS_WIN)
{"recent", electron::DIR_RECENT},
#endif
{"sessionData", DIR_SESSION_DATA},
{"temp", base::DIR_TEMP},
{"userCache", DIR_USER_CACHE},
{"userData", chrome::DIR_USER_DATA},
{"userDesktop", base::DIR_USER_DESKTOP},
{"videos", chrome::DIR_USER_VIDEOS},
});
// clang-format on
const auto* iter = Lookup.find(name);
return iter != Lookup.end() ? iter->second : -1;
}
bool NotificationCallbackWrapper(
const base::RepeatingCallback<
void(const base::CommandLine& command_line,
const base::FilePath& current_directory,
const std::vector<const uint8_t> additional_data)>& callback,
const base::CommandLine& cmd,
const base::FilePath& cwd,
const std::vector<const uint8_t> additional_data) {
// Make sure the callback is called after app gets ready.
if (Browser::Get()->is_ready()) {
callback.Run(cmd, cwd, std::move(additional_data));
} else {
scoped_refptr<base::SingleThreadTaskRunner> task_runner(
base::SingleThreadTaskRunner::GetCurrentDefault());
// Make a copy of the span so that the data isn't lost.
task_runner->PostTask(FROM_HERE,
base::BindOnce(base::IgnoreResult(callback), cmd, cwd,
std::move(additional_data)));
}
// ProcessSingleton needs to know whether current process is quiting.
return !Browser::Get()->is_shutting_down();
}
void GotPrivateKey(std::shared_ptr<content::ClientCertificateDelegate> delegate,
scoped_refptr<net::X509Certificate> cert,
scoped_refptr<net::SSLPrivateKey> private_key) {
delegate->ContinueWithCertificate(cert, private_key);
}
void OnClientCertificateSelected(
v8::Isolate* isolate,
std::shared_ptr<content::ClientCertificateDelegate> delegate,
std::shared_ptr<net::ClientCertIdentityList> identities,
gin::Arguments* args) {
if (args->Length() == 2) {
delegate->ContinueWithCertificate(nullptr, nullptr);
return;
}
v8::Local<v8::Value> val;
args->GetNext(&val);
if (val->IsNull()) {
delegate->ContinueWithCertificate(nullptr, nullptr);
return;
}
gin_helper::Dictionary cert_data;
if (!gin::ConvertFromV8(isolate, val, &cert_data)) {
gin_helper::ErrorThrower(isolate).ThrowError(
"Must pass valid certificate object.");
return;
}
std::string data;
if (!cert_data.Get("data", &data))
return;
auto certs = net::X509Certificate::CreateCertificateListFromBytes(
base::as_bytes(base::make_span(data.c_str(), data.size())),
net::X509Certificate::FORMAT_AUTO);
if (!certs.empty()) {
scoped_refptr<net::X509Certificate> cert(certs[0].get());
for (auto& identity : *identities) {
scoped_refptr<net::X509Certificate> identity_cert =
identity->certificate();
// Since |cert| was recreated from |data|, it won't include any
// intermediates. That's fine for checking equality, but once a match is
// found then |identity_cert| should be used since it will include the
// intermediates which would otherwise be lost.
if (cert->EqualsExcludingChain(identity_cert.get())) {
net::ClientCertIdentity::SelfOwningAcquirePrivateKey(
std::move(identity), base::BindRepeating(&GotPrivateKey, delegate,
std::move(identity_cert)));
break;
}
}
}
}
#if BUILDFLAG(USE_NSS_CERTS)
int ImportIntoCertStore(CertificateManagerModel* model, base::Value options) {
std::string file_data, cert_path;
std::u16string password;
net::ScopedCERTCertificateList imported_certs;
int rv = -1;
if (const base::Value::Dict* dict = options.GetIfDict(); dict != nullptr) {
if (const std::string* str = dict->FindString("certificate"); str)
cert_path = *str;
if (const std::string* str = dict->FindString("password"); str)
password = base::UTF8ToUTF16(*str);
}
if (!cert_path.empty()) {
if (base::ReadFileToString(base::FilePath(cert_path), &file_data)) {
auto module = model->cert_db()->GetPrivateSlot();
rv = model->ImportFromPKCS12(module.get(), file_data, password, true,
&imported_certs);
if (imported_certs.size() > 1) {
auto it = imported_certs.begin();
++it; // skip first which would be the client certificate.
for (; it != imported_certs.end(); ++it)
rv &= model->SetCertTrust(it->get(), net::CA_CERT,
net::NSSCertDatabase::TRUSTED_SSL);
}
}
}
return rv;
}
#endif
void OnIconDataAvailable(gin_helper::Promise<gfx::Image> promise,
gfx::Image icon) {
if (!icon.IsEmpty()) {
promise.Resolve(icon);
} else {
promise.RejectWithErrorMessage("Failed to get file icon.");
}
}
} // namespace
App::App() {
static_cast<ElectronBrowserClient*>(ElectronBrowserClient::Get())
->set_delegate(this);
Browser::Get()->AddObserver(this);
auto pid = content::ChildProcessHost::kInvalidUniqueID;
auto process_metric = std::make_unique<electron::ProcessMetric>(
content::PROCESS_TYPE_BROWSER, base::GetCurrentProcessHandle(),
base::ProcessMetrics::CreateCurrentProcessMetrics());
app_metrics_[pid] = std::move(process_metric);
}
App::~App() {
static_cast<ElectronBrowserClient*>(ElectronBrowserClient::Get())
->set_delegate(nullptr);
Browser::Get()->RemoveObserver(this);
content::GpuDataManager::GetInstance()->RemoveObserver(this);
content::BrowserChildProcessObserver::Remove(this);
}
void App::OnBeforeQuit(bool* prevent_default) {
if (Emit("before-quit")) {
*prevent_default = true;
}
}
void App::OnWillQuit(bool* prevent_default) {
if (Emit("will-quit")) {
*prevent_default = true;
}
}
void App::OnWindowAllClosed() {
Emit("window-all-closed");
}
void App::OnQuit() {
const int exitCode = ElectronBrowserMainParts::Get()->GetExitCode();
Emit("quit", exitCode);
if (process_singleton_) {
process_singleton_->Cleanup();
process_singleton_.reset();
}
}
void App::OnOpenFile(bool* prevent_default, const std::string& file_path) {
if (Emit("open-file", file_path)) {
*prevent_default = true;
}
}
void App::OnOpenURL(const std::string& url) {
Emit("open-url", url);
}
void App::OnActivate(bool has_visible_windows) {
Emit("activate", has_visible_windows);
}
void App::OnWillFinishLaunching() {
Emit("will-finish-launching");
}
void App::OnFinishLaunching(base::Value::Dict launch_info) {
#if BUILDFLAG(IS_LINUX)
// Set the application name for audio streams shown in external
// applications. Only affects pulseaudio currently.
media::AudioManager::SetGlobalAppName(Browser::Get()->GetName());
#endif
Emit("ready", base::Value(std::move(launch_info)));
}
void App::OnPreMainMessageLoopRun() {
content::BrowserChildProcessObserver::Add(this);
if (process_singleton_ && watch_singleton_socket_on_ready_) {
process_singleton_->StartWatching();
watch_singleton_socket_on_ready_ = false;
}
}
void App::OnPreCreateThreads() {
DCHECK(!content::GpuDataManager::Initialized());
content::GpuDataManager* manager = content::GpuDataManager::GetInstance();
manager->AddObserver(this);
if (disable_hw_acceleration_) {
manager->DisableHardwareAcceleration();
}
if (disable_domain_blocking_for_3DAPIs_) {
content::GpuDataManagerImpl::GetInstance()
->DisableDomainBlockingFor3DAPIsForTesting();
}
}
void App::OnAccessibilitySupportChanged() {
Emit("accessibility-support-changed", IsAccessibilitySupportEnabled());
}
#if BUILDFLAG(IS_MAC)
void App::OnWillContinueUserActivity(bool* prevent_default,
const std::string& type) {
if (Emit("will-continue-activity", type)) {
*prevent_default = true;
}
}
void App::OnDidFailToContinueUserActivity(const std::string& type,
const std::string& error) {
Emit("continue-activity-error", type, error);
}
void App::OnContinueUserActivity(bool* prevent_default,
const std::string& type,
base::Value::Dict user_info,
base::Value::Dict details) {
if (Emit("continue-activity", type, base::Value(std::move(user_info)),
base::Value(std::move(details)))) {
*prevent_default = true;
}
}
void App::OnUserActivityWasContinued(const std::string& type,
base::Value::Dict user_info) {
Emit("activity-was-continued", type, base::Value(std::move(user_info)));
}
void App::OnUpdateUserActivityState(bool* prevent_default,
const std::string& type,
base::Value::Dict user_info) {
if (Emit("update-activity-state", type, base::Value(std::move(user_info)))) {
*prevent_default = true;
}
}
void App::OnNewWindowForTab() {
Emit("new-window-for-tab");
}
void App::OnDidBecomeActive() {
Emit("did-become-active");
}
void App::OnDidResignActive() {
Emit("did-resign-active");
}
#endif
bool App::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) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
content::WebContents* web_contents =
content::WebContents::FromRenderFrameHost(opener);
if (web_contents) {
WebContents* api_web_contents = WebContents::From(web_contents);
// No need to emit any event if the WebContents is not available in JS.
if (api_web_contents) {
api_web_contents->OnCreateWindow(target_url, referrer, frame_name,
disposition, raw_features, body);
}
}
return false;
}
void App::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) {
auto adapted_callback = base::AdaptCallbackForRepeating(std::move(callback));
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
bool prevent_default = Emit(
"certificate-error", WebContents::FromOrCreate(isolate, web_contents),
request_url, net::ErrorToString(cert_error), ssl_info.cert,
adapted_callback, is_main_frame_request);
// Deny the certificate by default.
if (!prevent_default)
adapted_callback.Run(content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY);
}
base::OnceClosure App::SelectClientCertificate(
content::BrowserContext* browser_context,
content::WebContents* web_contents,
net::SSLCertRequestInfo* cert_request_info,
net::ClientCertIdentityList identities,
std::unique_ptr<content::ClientCertificateDelegate> delegate) {
std::shared_ptr<content::ClientCertificateDelegate> shared_delegate(
delegate.release());
// Convert the ClientCertIdentityList to a CertificateList
// to avoid changes in the API.
auto client_certs = net::CertificateList();
for (const std::unique_ptr<net::ClientCertIdentity>& identity : identities)
client_certs.emplace_back(identity->certificate());
auto shared_identities =
std::make_shared<net::ClientCertIdentityList>(std::move(identities));
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
bool prevent_default =
Emit("select-client-certificate",
WebContents::FromOrCreate(isolate, web_contents),
cert_request_info->host_and_port.ToString(), std::move(client_certs),
base::BindOnce(&OnClientCertificateSelected, isolate,
shared_delegate, shared_identities));
// Default to first certificate from the platform store.
if (!prevent_default) {
scoped_refptr<net::X509Certificate> cert =
(*shared_identities)[0]->certificate();
net::ClientCertIdentity::SelfOwningAcquirePrivateKey(
std::move((*shared_identities)[0]),
base::BindRepeating(&GotPrivateKey, shared_delegate, std::move(cert)));
}
return base::OnceClosure();
}
void App::OnGpuInfoUpdate() {
Emit("gpu-info-update");
}
void App::OnGpuProcessCrashed() {
Emit("gpu-process-crashed", true);
}
void App::BrowserChildProcessLaunchedAndConnected(
const content::ChildProcessData& data) {
ChildProcessLaunched(data.process_type, data.id, data.GetProcess().Handle(),
data.metrics_name, base::UTF16ToUTF8(data.name));
}
void App::BrowserChildProcessHostDisconnected(
const content::ChildProcessData& data) {
ChildProcessDisconnected(data.id);
}
void App::BrowserChildProcessCrashed(
const content::ChildProcessData& data,
const content::ChildProcessTerminationInfo& info) {
ChildProcessDisconnected(data.id);
BrowserChildProcessCrashedOrKilled(data, info);
}
void App::BrowserChildProcessKilled(
const content::ChildProcessData& data,
const content::ChildProcessTerminationInfo& info) {
ChildProcessDisconnected(data.id);
BrowserChildProcessCrashedOrKilled(data, info);
}
void App::BrowserChildProcessCrashedOrKilled(
const content::ChildProcessData& data,
const content::ChildProcessTerminationInfo& info) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("type", content::GetProcessTypeNameInEnglish(data.process_type));
details.Set("reason", info.status);
details.Set("exitCode", info.exit_code);
details.Set("serviceName", data.metrics_name);
if (!data.name.empty()) {
details.Set("name", data.name);
}
if (data.process_type == content::PROCESS_TYPE_UTILITY) {
base::ProcessId pid = data.GetProcess().Pid();
auto utility_process_wrapper = UtilityProcessWrapper::FromProcessId(pid);
if (utility_process_wrapper)
utility_process_wrapper->Shutdown(info.exit_code);
}
Emit("child-process-gone", details);
}
void App::RenderProcessReady(content::RenderProcessHost* host) {
ChildProcessLaunched(content::PROCESS_TYPE_RENDERER, host->GetID(),
host->GetProcess().Handle());
}
void App::RenderProcessExited(content::RenderProcessHost* host) {
ChildProcessDisconnected(host->GetID());
}
void App::ChildProcessLaunched(int process_type,
int pid,
base::ProcessHandle handle,
const std::string& service_name,
const std::string& name) {
#if BUILDFLAG(IS_MAC)
auto metrics = base::ProcessMetrics::CreateProcessMetrics(
handle, content::BrowserChildProcessHost::GetPortProvider());
#else
auto metrics = base::ProcessMetrics::CreateProcessMetrics(handle);
#endif
app_metrics_[pid] = std::make_unique<electron::ProcessMetric>(
process_type, handle, std::move(metrics), service_name, name);
}
void App::ChildProcessDisconnected(int pid) {
app_metrics_.erase(pid);
}
base::FilePath App::GetAppPath() const {
return app_path_;
}
void App::SetAppPath(const base::FilePath& app_path) {
app_path_ = app_path;
}
#if !BUILDFLAG(IS_MAC)
void App::SetAppLogsPath(gin_helper::ErrorThrower thrower,
absl::optional<base::FilePath> custom_path) {
if (custom_path.has_value()) {
if (!custom_path->IsAbsolute()) {
thrower.ThrowError("Path must be absolute");
return;
}
{
ScopedAllowBlockingForElectron allow_blocking;
base::PathService::Override(DIR_APP_LOGS, custom_path.value());
}
} else {
base::FilePath path;
if (base::PathService::Get(chrome::DIR_USER_DATA, &path)) {
path = path.Append(base::FilePath::FromUTF8Unsafe("logs"));
{
ScopedAllowBlockingForElectron allow_blocking;
base::PathService::Override(DIR_APP_LOGS, path);
}
}
}
}
#endif
// static
bool App::IsPackaged() {
auto env = base::Environment::Create();
if (env->HasVar("ELECTRON_FORCE_IS_PACKAGED"))
return true;
base::FilePath exe_path;
base::PathService::Get(base::FILE_EXE, &exe_path);
base::FilePath::StringType base_name =
base::ToLowerASCII(exe_path.BaseName().value());
#if BUILDFLAG(IS_WIN)
return base_name != FILE_PATH_LITERAL("electron.exe");
#else
return base_name != FILE_PATH_LITERAL("electron");
#endif
}
base::FilePath App::GetPath(gin_helper::ErrorThrower thrower,
const std::string& name) {
base::FilePath path;
int key = GetPathConstant(name);
if (key < 0 || !base::PathService::Get(key, &path))
thrower.ThrowError("Failed to get '" + name + "' path");
return path;
}
void App::SetPath(gin_helper::ErrorThrower thrower,
const std::string& name,
const base::FilePath& path) {
if (!path.IsAbsolute()) {
thrower.ThrowError("Path must be absolute");
return;
}
int key = GetPathConstant(name);
if (key < 0 || !base::PathService::OverrideAndCreateIfNeeded(
key, path, /* is_absolute = */ true, /* create = */ false))
thrower.ThrowError("Failed to set path");
}
void App::SetDesktopName(const std::string& desktop_name) {
#if BUILDFLAG(IS_LINUX)
auto env = base::Environment::Create();
env->SetVar("CHROME_DESKTOP", desktop_name);
#endif
}
std::string App::GetLocale() {
return g_browser_process->GetApplicationLocale();
}
std::string App::GetSystemLocale(gin_helper::ErrorThrower thrower) const {
if (!Browser::Get()->is_ready()) {
thrower.ThrowError(
"app.getSystemLocale() can only be called "
"after app is ready");
return std::string();
}
return static_cast<BrowserProcessImpl*>(g_browser_process)->GetSystemLocale();
}
std::string App::GetLocaleCountryCode() {
std::string region;
#if BUILDFLAG(IS_WIN)
WCHAR locale_name[LOCALE_NAME_MAX_LENGTH] = {0};
if (GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SISO3166CTRYNAME,
(LPWSTR)&locale_name,
sizeof(locale_name) / sizeof(WCHAR)) ||
GetLocaleInfoEx(LOCALE_NAME_SYSTEM_DEFAULT, LOCALE_SISO3166CTRYNAME,
(LPWSTR)&locale_name,
sizeof(locale_name) / sizeof(WCHAR))) {
base::WideToUTF8(locale_name, wcslen(locale_name), ®ion);
}
#elif BUILDFLAG(IS_MAC)
CFLocaleRef locale = CFLocaleCopyCurrent();
CFStringRef value = CFStringRef(
static_cast<CFTypeRef>(CFLocaleGetValue(locale, kCFLocaleCountryCode)));
if (value != nil) {
char temporaryCString[3];
const CFIndex kCStringSize = sizeof(temporaryCString);
if (CFStringGetCString(value, temporaryCString, kCStringSize,
kCFStringEncodingUTF8)) {
region = temporaryCString;
}
}
#else
const char* locale_ptr = setlocale(LC_TIME, nullptr);
if (!locale_ptr)
locale_ptr = setlocale(LC_NUMERIC, nullptr);
if (locale_ptr) {
std::string locale = locale_ptr;
std::string::size_type rpos = locale.find('.');
if (rpos != std::string::npos)
locale = locale.substr(0, rpos);
rpos = locale.find('_');
if (rpos != std::string::npos && rpos + 1 < locale.size())
region = locale.substr(rpos + 1);
}
#endif
return region.size() == 2 ? region : std::string();
}
void App::OnSecondInstance(const base::CommandLine& cmd,
const base::FilePath& cwd,
const std::vector<const uint8_t> additional_data) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Value> data_value =
DeserializeV8Value(isolate, std::move(additional_data));
Emit("second-instance", cmd.argv(), cwd, data_value);
}
bool App::HasSingleInstanceLock() const {
if (process_singleton_)
return true;
return false;
}
bool App::RequestSingleInstanceLock(gin::Arguments* args) {
if (HasSingleInstanceLock())
return true;
std::string program_name = electron::Browser::Get()->GetName();
base::FilePath user_dir;
base::PathService::Get(chrome::DIR_USER_DATA, &user_dir);
// The user_dir may not have been created yet.
base::CreateDirectoryAndGetError(user_dir, nullptr);
auto cb = base::BindRepeating(&App::OnSecondInstance, base::Unretained(this));
blink::CloneableMessage additional_data_message;
args->GetNext(&additional_data_message);
#if BUILDFLAG(IS_WIN)
bool app_is_sandboxed =
IsSandboxEnabled(base::CommandLine::ForCurrentProcess());
process_singleton_ = std::make_unique<ProcessSingleton>(
program_name, user_dir, additional_data_message.encoded_message,
app_is_sandboxed, base::BindRepeating(NotificationCallbackWrapper, cb));
#else
process_singleton_ = std::make_unique<ProcessSingleton>(
user_dir, additional_data_message.encoded_message,
base::BindRepeating(NotificationCallbackWrapper, cb));
#endif
switch (process_singleton_->NotifyOtherProcessOrCreate()) {
case ProcessSingleton::NotifyResult::PROCESS_NONE:
if (content::BrowserThread::IsThreadInitialized(
content::BrowserThread::IO)) {
process_singleton_->StartWatching();
} else {
watch_singleton_socket_on_ready_ = true;
}
return true;
case ProcessSingleton::NotifyResult::LOCK_ERROR:
case ProcessSingleton::NotifyResult::PROFILE_IN_USE:
case ProcessSingleton::NotifyResult::PROCESS_NOTIFIED: {
process_singleton_.reset();
return false;
}
}
}
void App::ReleaseSingleInstanceLock() {
if (process_singleton_) {
process_singleton_->Cleanup();
process_singleton_.reset();
}
}
bool App::Relaunch(gin::Arguments* js_args) {
// Parse parameters.
bool override_argv = false;
base::FilePath exec_path;
relauncher::StringVector args;
gin_helper::Dictionary options;
if (js_args->GetNext(&options)) {
bool has_exec_path = options.Get("execPath", &exec_path);
bool has_args = options.Get("args", &args);
if (has_exec_path || has_args)
override_argv = true;
}
if (!override_argv) {
const relauncher::StringVector& argv =
electron::ElectronCommandLine::argv();
return relauncher::RelaunchApp(argv);
}
relauncher::StringVector argv;
argv.reserve(1 + args.size());
if (exec_path.empty()) {
base::FilePath current_exe_path;
base::PathService::Get(base::FILE_EXE, ¤t_exe_path);
argv.push_back(current_exe_path.value());
} else {
argv.push_back(exec_path.value());
}
argv.insert(argv.end(), args.begin(), args.end());
return relauncher::RelaunchApp(argv);
}
void App::DisableHardwareAcceleration(gin_helper::ErrorThrower thrower) {
if (Browser::Get()->is_ready()) {
thrower.ThrowError(
"app.disableHardwareAcceleration() can only be called "
"before app is ready");
return;
}
if (content::GpuDataManager::Initialized()) {
content::GpuDataManager::GetInstance()->DisableHardwareAcceleration();
} else {
disable_hw_acceleration_ = true;
}
}
void App::DisableDomainBlockingFor3DAPIs(gin_helper::ErrorThrower thrower) {
if (Browser::Get()->is_ready()) {
thrower.ThrowError(
"app.disableDomainBlockingFor3DAPIs() can only be called "
"before app is ready");
return;
}
if (content::GpuDataManager::Initialized()) {
content::GpuDataManagerImpl::GetInstance()
->DisableDomainBlockingFor3DAPIsForTesting();
} else {
disable_domain_blocking_for_3DAPIs_ = true;
}
}
bool App::IsAccessibilitySupportEnabled() {
auto* ax_state = content::BrowserAccessibilityState::GetInstance();
return ax_state->IsAccessibleBrowser();
}
void App::SetAccessibilitySupportEnabled(gin_helper::ErrorThrower thrower,
bool enabled) {
if (!Browser::Get()->is_ready()) {
thrower.ThrowError(
"app.setAccessibilitySupportEnabled() can only be called "
"after app is ready");
return;
}
auto* ax_state = content::BrowserAccessibilityState::GetInstance();
if (enabled) {
ax_state->OnScreenReaderDetected();
} else {
ax_state->DisableAccessibility();
}
Browser::Get()->OnAccessibilitySupportChanged();
}
Browser::LoginItemSettings App::GetLoginItemSettings(gin::Arguments* args) {
Browser::LoginItemSettings options;
args->GetNext(&options);
return Browser::Get()->GetLoginItemSettings(options);
}
#if BUILDFLAG(USE_NSS_CERTS)
void App::ImportCertificate(gin_helper::ErrorThrower thrower,
base::Value options,
net::CompletionOnceCallback callback) {
if (!options.is_dict()) {
thrower.ThrowTypeError("Expected options to be an object");
return;
}
auto* browser_context = ElectronBrowserContext::From("", false);
if (!certificate_manager_model_) {
CertificateManagerModel::Create(
browser_context,
base::BindOnce(&App::OnCertificateManagerModelCreated,
base::Unretained(this), std::move(options),
std::move(callback)));
return;
}
int rv =
ImportIntoCertStore(certificate_manager_model_.get(), std::move(options));
std::move(callback).Run(rv);
}
void App::OnCertificateManagerModelCreated(
base::Value options,
net::CompletionOnceCallback callback,
std::unique_ptr<CertificateManagerModel> model) {
certificate_manager_model_ = std::move(model);
int rv =
ImportIntoCertStore(certificate_manager_model_.get(), std::move(options));
std::move(callback).Run(rv);
}
#endif
#if BUILDFLAG(IS_WIN)
v8::Local<v8::Value> App::GetJumpListSettings() {
JumpList jump_list(Browser::Get()->GetAppUserModelID());
int min_items = 10;
std::vector<JumpListItem> removed_items;
if (jump_list.Begin(&min_items, &removed_items)) {
// We don't actually want to change anything, so abort the transaction.
jump_list.Abort();
} else {
LOG(ERROR) << "Failed to begin Jump List transaction.";
}
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
dict.Set("minItems", min_items);
dict.Set("removedItems", gin::ConvertToV8(isolate, removed_items));
return dict.GetHandle();
}
JumpListResult App::SetJumpList(v8::Local<v8::Value> val,
gin::Arguments* args) {
std::vector<JumpListCategory> categories;
bool delete_jump_list = val->IsNull();
if (!delete_jump_list &&
!gin::ConvertFromV8(args->isolate(), val, &categories)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Argument must be null or an array of categories");
return JumpListResult::kArgumentError;
}
JumpList jump_list(Browser::Get()->GetAppUserModelID());
if (delete_jump_list) {
return jump_list.Delete() ? JumpListResult::kSuccess
: JumpListResult::kGenericError;
}
// Start a transaction that updates the JumpList of this application.
if (!jump_list.Begin())
return JumpListResult::kGenericError;
JumpListResult result = jump_list.AppendCategories(categories);
// AppendCategories may have failed to add some categories, but it's better
// to have something than nothing so try to commit the changes anyway.
if (!jump_list.Commit()) {
LOG(ERROR) << "Failed to commit changes to custom Jump List.";
// It's more useful to return the earlier error code that might give
// some indication as to why the transaction actually failed, so don't
// overwrite it with a "generic error" code here.
if (result == JumpListResult::kSuccess)
result = JumpListResult::kGenericError;
}
return result;
}
#endif // BUILDFLAG(IS_WIN)
v8::Local<v8::Promise> App::GetFileIcon(const base::FilePath& path,
gin::Arguments* args) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<gfx::Image> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
base::FilePath normalized_path = path.NormalizePathSeparators();
IconLoader::IconSize icon_size;
gin_helper::Dictionary options;
if (!args->GetNext(&options)) {
icon_size = IconLoader::IconSize::NORMAL;
} else {
std::string icon_size_string;
options.Get("size", &icon_size_string);
icon_size = GetIconSizeByString(icon_size_string);
}
auto* icon_manager = ElectronBrowserMainParts::Get()->GetIconManager();
gfx::Image* icon =
icon_manager->LookupIconFromFilepath(normalized_path, icon_size, 1.0f);
if (icon) {
promise.Resolve(*icon);
} else {
icon_manager->LoadIcon(
normalized_path, icon_size, 1.0f,
base::BindOnce(&OnIconDataAvailable, std::move(promise)),
&cancelable_task_tracker_);
}
return handle;
}
std::vector<gin_helper::Dictionary> App::GetAppMetrics(v8::Isolate* isolate) {
std::vector<gin_helper::Dictionary> result;
result.reserve(app_metrics_.size());
int processor_count = base::SysInfo::NumberOfProcessors();
for (const auto& process_metric : app_metrics_) {
auto pid_dict = gin_helper::Dictionary::CreateEmpty(isolate);
auto cpu_dict = gin_helper::Dictionary::CreateEmpty(isolate);
cpu_dict.Set(
"percentCPUUsage",
process_metric.second->metrics->GetPlatformIndependentCPUUsage() /
processor_count);
#if !BUILDFLAG(IS_WIN)
cpu_dict.Set("idleWakeupsPerSecond",
process_metric.second->metrics->GetIdleWakeupsPerSecond());
#else
// Chrome's underlying process_metrics.cc will throw a non-fatal warning
// that this method isn't implemented on Windows, so set it to 0 instead
// of calling it
cpu_dict.Set("idleWakeupsPerSecond", 0);
#endif
pid_dict.Set("cpu", cpu_dict);
pid_dict.Set("pid", process_metric.second->process.Pid());
pid_dict.Set("type", content::GetProcessTypeNameInEnglish(
process_metric.second->type));
pid_dict.Set("creationTime",
process_metric.second->process.CreationTime().ToJsTime());
if (!process_metric.second->service_name.empty()) {
pid_dict.Set("serviceName", process_metric.second->service_name);
}
if (!process_metric.second->name.empty()) {
pid_dict.Set("name", process_metric.second->name);
}
#if !BUILDFLAG(IS_LINUX)
auto memory_info = process_metric.second->GetMemoryInfo();
auto memory_dict = gin_helper::Dictionary::CreateEmpty(isolate);
memory_dict.Set("workingSetSize",
static_cast<double>(memory_info.working_set_size >> 10));
memory_dict.Set(
"peakWorkingSetSize",
static_cast<double>(memory_info.peak_working_set_size >> 10));
#if BUILDFLAG(IS_WIN)
memory_dict.Set("privateBytes",
static_cast<double>(memory_info.private_bytes >> 10));
#endif
pid_dict.Set("memory", memory_dict);
#endif
#if BUILDFLAG(IS_MAC)
pid_dict.Set("sandboxed", process_metric.second->IsSandboxed());
#elif BUILDFLAG(IS_WIN)
auto integrity_level = process_metric.second->GetIntegrityLevel();
auto sandboxed = ProcessMetric::IsSandboxed(integrity_level);
pid_dict.Set("integrityLevel", integrity_level);
pid_dict.Set("sandboxed", sandboxed);
#endif
result.push_back(pid_dict);
}
return result;
}
v8::Local<v8::Value> App::GetGPUFeatureStatus(v8::Isolate* isolate) {
return gin::ConvertToV8(isolate, content::GetFeatureStatus());
}
v8::Local<v8::Promise> App::GetGPUInfo(v8::Isolate* isolate,
const std::string& info_type) {
auto* const gpu_data_manager = content::GpuDataManagerImpl::GetInstance();
gin_helper::Promise<base::Value> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (info_type != "basic" && info_type != "complete") {
promise.RejectWithErrorMessage(
"Invalid info type. Use 'basic' or 'complete'");
return handle;
}
std::string reason;
if (!gpu_data_manager->GpuAccessAllowed(&reason)) {
promise.RejectWithErrorMessage("GPU access not allowed. Reason: " + reason);
return handle;
}
auto* const info_mgr = GPUInfoManager::GetInstance();
if (info_type == "complete") {
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
info_mgr->FetchCompleteInfo(std::move(promise));
#else
info_mgr->FetchBasicInfo(std::move(promise));
#endif
} else /* (info_type == "basic") */ {
info_mgr->FetchBasicInfo(std::move(promise));
}
return handle;
}
static void RemoveNoSandboxSwitch(base::CommandLine* command_line) {
if (command_line->HasSwitch(sandbox::policy::switches::kNoSandbox)) {
const base::CommandLine::CharType* noSandboxArg =
FILE_PATH_LITERAL("--no-sandbox");
base::CommandLine::StringVector modified_command_line;
for (auto& arg : command_line->argv()) {
if (arg.compare(noSandboxArg) != 0) {
modified_command_line.push_back(arg);
}
}
command_line->InitFromArgv(modified_command_line);
}
}
void App::EnableSandbox(gin_helper::ErrorThrower thrower) {
if (Browser::Get()->is_ready()) {
thrower.ThrowError(
"app.enableSandbox() can only be called "
"before app is ready");
return;
}
auto* command_line = base::CommandLine::ForCurrentProcess();
RemoveNoSandboxSwitch(command_line);
command_line->AppendSwitch(switches::kEnableSandbox);
}
void App::SetUserAgentFallback(const std::string& user_agent) {
ElectronBrowserClient::Get()->SetUserAgent(user_agent);
}
#if BUILDFLAG(IS_WIN)
bool App::IsRunningUnderARM64Translation() const {
return base::win::OSInfo::IsRunningEmulatedOnArm64();
}
#endif
std::string App::GetUserAgentFallback() {
return ElectronBrowserClient::Get()->GetUserAgent();
}
#if BUILDFLAG(IS_MAC)
bool App::MoveToApplicationsFolder(gin_helper::ErrorThrower thrower,
gin::Arguments* args) {
return ElectronBundleMover::Move(thrower, args);
}
bool App::IsInApplicationsFolder() {
return ElectronBundleMover::IsCurrentAppInApplicationsFolder();
}
int DockBounce(gin::Arguments* args) {
int request_id = -1;
std::string type = "informational";
args->GetNext(&type);
if (type == "critical")
request_id = Browser::Get()->DockBounce(Browser::BounceType::kCritical);
else if (type == "informational")
request_id =
Browser::Get()->DockBounce(Browser::BounceType::kInformational);
return request_id;
}
void DockSetMenu(electron::api::Menu* menu) {
Browser::Get()->DockSetMenu(menu->model());
}
v8::Local<v8::Value> App::GetDockAPI(v8::Isolate* isolate) {
if (dock_.IsEmpty()) {
// Initialize the Dock API, the methods are bound to "dock" which exists
// for the lifetime of "app"
auto browser = base::Unretained(Browser::Get());
auto dock_obj = gin_helper::Dictionary::CreateEmpty(isolate);
dock_obj.SetMethod("bounce", &DockBounce);
dock_obj.SetMethod(
"cancelBounce",
base::BindRepeating(&Browser::DockCancelBounce, browser));
dock_obj.SetMethod(
"downloadFinished",
base::BindRepeating(&Browser::DockDownloadFinished, browser));
dock_obj.SetMethod(
"setBadge", base::BindRepeating(&Browser::DockSetBadgeText, browser));
dock_obj.SetMethod(
"getBadge", base::BindRepeating(&Browser::DockGetBadgeText, browser));
dock_obj.SetMethod("hide",
base::BindRepeating(&Browser::DockHide, browser));
dock_obj.SetMethod("show",
base::BindRepeating(&Browser::DockShow, browser));
dock_obj.SetMethod("isVisible",
base::BindRepeating(&Browser::DockIsVisible, browser));
dock_obj.SetMethod("setMenu", &DockSetMenu);
dock_obj.SetMethod("setIcon",
base::BindRepeating(&Browser::DockSetIcon, browser));
dock_.Reset(isolate, dock_obj.GetHandle());
}
return v8::Local<v8::Value>::New(isolate, dock_);
}
#endif
void ConfigureHostResolver(v8::Isolate* isolate,
const gin_helper::Dictionary& opts) {
gin_helper::ErrorThrower thrower(isolate);
if (!Browser::Get()->is_ready()) {
thrower.ThrowError(
"configureHostResolver cannot be called before the app is ready");
return;
}
net::SecureDnsMode secure_dns_mode = net::SecureDnsMode::kOff;
std::string default_doh_templates;
if (base::FeatureList::IsEnabled(features::kDnsOverHttps)) {
if (features::kDnsOverHttpsFallbackParam.Get()) {
secure_dns_mode = net::SecureDnsMode::kAutomatic;
} else {
secure_dns_mode = net::SecureDnsMode::kSecure;
}
default_doh_templates = features::kDnsOverHttpsTemplatesParam.Get();
}
net::DnsOverHttpsConfig doh_config;
if (!default_doh_templates.empty() &&
secure_dns_mode != net::SecureDnsMode::kOff) {
auto maybe_doh_config =
net::DnsOverHttpsConfig::FromString(default_doh_templates);
if (maybe_doh_config.has_value())
doh_config = maybe_doh_config.value();
}
bool enable_built_in_resolver =
base::FeatureList::IsEnabled(features::kAsyncDns);
bool additional_dns_query_types_enabled = true;
if (opts.Has("enableBuiltInResolver") &&
!opts.Get("enableBuiltInResolver", &enable_built_in_resolver)) {
thrower.ThrowTypeError("enableBuiltInResolver must be a boolean");
return;
}
if (opts.Has("secureDnsMode") &&
!opts.Get("secureDnsMode", &secure_dns_mode)) {
thrower.ThrowTypeError(
"secureDnsMode must be one of: off, automatic, secure");
return;
}
std::vector<std::string> secure_dns_server_strings;
if (opts.Has("secureDnsServers")) {
if (!opts.Get("secureDnsServers", &secure_dns_server_strings)) {
thrower.ThrowTypeError("secureDnsServers must be an array of strings");
return;
}
// Validate individual server templates prior to batch-assigning to
// doh_config.
std::vector<net::DnsOverHttpsServerConfig> servers;
for (const std::string& server_template : secure_dns_server_strings) {
absl::optional<net::DnsOverHttpsServerConfig> server_config =
net::DnsOverHttpsServerConfig::FromString(server_template);
if (!server_config.has_value()) {
thrower.ThrowTypeError(std::string("not a valid DoH template: ") +
server_template);
return;
}
servers.push_back(*server_config);
}
doh_config = net::DnsOverHttpsConfig(std::move(servers));
}
if (opts.Has("enableAdditionalDnsQueryTypes") &&
!opts.Get("enableAdditionalDnsQueryTypes",
&additional_dns_query_types_enabled)) {
thrower.ThrowTypeError("enableAdditionalDnsQueryTypes must be a boolean");
return;
}
// Configure the stub resolver. This must be done after the system
// NetworkContext is created, but before anything has the chance to use it.
content::GetNetworkService()->ConfigureStubHostResolver(
enable_built_in_resolver, secure_dns_mode, doh_config,
additional_dns_query_types_enabled);
}
// static
App* App::Get() {
static base::NoDestructor<App> app;
return app.get();
}
// static
gin::Handle<App> App::Create(v8::Isolate* isolate) {
return gin::CreateHandle(isolate, Get());
}
gin::ObjectTemplateBuilder App::GetObjectTemplateBuilder(v8::Isolate* isolate) {
auto browser = base::Unretained(Browser::Get());
return gin_helper::EventEmitterMixin<App>::GetObjectTemplateBuilder(isolate)
.SetMethod("quit", base::BindRepeating(&Browser::Quit, browser))
.SetMethod("exit", base::BindRepeating(&Browser::Exit, browser))
.SetMethod("focus", base::BindRepeating(&Browser::Focus, browser))
.SetMethod("getVersion",
base::BindRepeating(&Browser::GetVersion, browser))
.SetMethod("setVersion",
base::BindRepeating(&Browser::SetVersion, browser))
.SetMethod("getName", base::BindRepeating(&Browser::GetName, browser))
.SetMethod("setName", base::BindRepeating(&Browser::SetName, browser))
.SetMethod("isReady", base::BindRepeating(&Browser::is_ready, browser))
.SetMethod("whenReady", base::BindRepeating(&Browser::WhenReady, browser))
.SetMethod("addRecentDocument",
base::BindRepeating(&Browser::AddRecentDocument, browser))
.SetMethod("clearRecentDocuments",
base::BindRepeating(&Browser::ClearRecentDocuments, browser))
#if BUILDFLAG(IS_WIN)
.SetMethod("setAppUserModelId",
base::BindRepeating(&Browser::SetAppUserModelID, browser))
#endif
.SetMethod(
"isDefaultProtocolClient",
base::BindRepeating(&Browser::IsDefaultProtocolClient, browser))
.SetMethod(
"setAsDefaultProtocolClient",
base::BindRepeating(&Browser::SetAsDefaultProtocolClient, browser))
.SetMethod(
"removeAsDefaultProtocolClient",
base::BindRepeating(&Browser::RemoveAsDefaultProtocolClient, browser))
#if !BUILDFLAG(IS_LINUX)
.SetMethod(
"getApplicationInfoForProtocol",
base::BindRepeating(&Browser::GetApplicationInfoForProtocol, browser))
#endif
.SetMethod(
"getApplicationNameForProtocol",
base::BindRepeating(&Browser::GetApplicationNameForProtocol, browser))
.SetMethod("setBadgeCount",
base::BindRepeating(&Browser::SetBadgeCount, browser))
.SetMethod("getBadgeCount",
base::BindRepeating(&Browser::GetBadgeCount, browser))
.SetMethod("getLoginItemSettings", &App::GetLoginItemSettings)
.SetMethod("setLoginItemSettings",
base::BindRepeating(&Browser::SetLoginItemSettings, browser))
.SetMethod("isEmojiPanelSupported",
base::BindRepeating(&Browser::IsEmojiPanelSupported, browser))
#if BUILDFLAG(IS_MAC)
.SetMethod("hide", base::BindRepeating(&Browser::Hide, browser))
.SetMethod("isHidden", base::BindRepeating(&Browser::IsHidden, browser))
.SetMethod("show", base::BindRepeating(&Browser::Show, browser))
.SetMethod("setUserActivity",
base::BindRepeating(&Browser::SetUserActivity, browser))
.SetMethod("getCurrentActivityType",
base::BindRepeating(&Browser::GetCurrentActivityType, browser))
.SetMethod(
"invalidateCurrentActivity",
base::BindRepeating(&Browser::InvalidateCurrentActivity, browser))
.SetMethod("resignCurrentActivity",
base::BindRepeating(&Browser::ResignCurrentActivity, browser))
.SetMethod("updateCurrentActivity",
base::BindRepeating(&Browser::UpdateCurrentActivity, browser))
.SetMethod("moveToApplicationsFolder", &App::MoveToApplicationsFolder)
.SetMethod("isInApplicationsFolder", &App::IsInApplicationsFolder)
.SetMethod("setActivationPolicy", &App::SetActivationPolicy)
#endif
.SetMethod("setAboutPanelOptions",
base::BindRepeating(&Browser::SetAboutPanelOptions, browser))
.SetMethod("showAboutPanel",
base::BindRepeating(&Browser::ShowAboutPanel, browser))
#if BUILDFLAG(IS_MAC)
.SetMethod(
"isSecureKeyboardEntryEnabled",
base::BindRepeating(&Browser::IsSecureKeyboardEntryEnabled, browser))
.SetMethod(
"setSecureKeyboardEntryEnabled",
base::BindRepeating(&Browser::SetSecureKeyboardEntryEnabled, browser))
#endif
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
.SetMethod("showEmojiPanel",
base::BindRepeating(&Browser::ShowEmojiPanel, browser))
#endif
#if BUILDFLAG(IS_WIN)
.SetMethod("setUserTasks",
base::BindRepeating(&Browser::SetUserTasks, browser))
.SetMethod("getJumpListSettings", &App::GetJumpListSettings)
.SetMethod("setJumpList", &App::SetJumpList)
#endif
#if BUILDFLAG(IS_LINUX)
.SetMethod("isUnityRunning",
base::BindRepeating(&Browser::IsUnityRunning, browser))
#endif
.SetProperty("isPackaged", &App::IsPackaged)
.SetMethod("setAppPath", &App::SetAppPath)
.SetMethod("getAppPath", &App::GetAppPath)
.SetMethod("setPath", &App::SetPath)
.SetMethod("getPath", &App::GetPath)
.SetMethod("setAppLogsPath", &App::SetAppLogsPath)
.SetMethod("setDesktopName", &App::SetDesktopName)
.SetMethod("getLocale", &App::GetLocale)
.SetMethod("getPreferredSystemLanguages", &GetPreferredLanguages)
.SetMethod("getSystemLocale", &App::GetSystemLocale)
.SetMethod("getLocaleCountryCode", &App::GetLocaleCountryCode)
#if BUILDFLAG(USE_NSS_CERTS)
.SetMethod("importCertificate", &App::ImportCertificate)
#endif
.SetMethod("hasSingleInstanceLock", &App::HasSingleInstanceLock)
.SetMethod("requestSingleInstanceLock", &App::RequestSingleInstanceLock)
.SetMethod("releaseSingleInstanceLock", &App::ReleaseSingleInstanceLock)
.SetMethod("relaunch", &App::Relaunch)
.SetMethod("isAccessibilitySupportEnabled",
&App::IsAccessibilitySupportEnabled)
.SetMethod("setAccessibilitySupportEnabled",
&App::SetAccessibilitySupportEnabled)
.SetMethod("disableHardwareAcceleration",
&App::DisableHardwareAcceleration)
.SetMethod("disableDomainBlockingFor3DAPIs",
&App::DisableDomainBlockingFor3DAPIs)
.SetMethod("getFileIcon", &App::GetFileIcon)
.SetMethod("getAppMetrics", &App::GetAppMetrics)
.SetMethod("getGPUFeatureStatus", &App::GetGPUFeatureStatus)
.SetMethod("getGPUInfo", &App::GetGPUInfo)
#if IS_MAS_BUILD()
.SetMethod("startAccessingSecurityScopedResource",
&App::StartAccessingSecurityScopedResource)
#endif
#if BUILDFLAG(IS_MAC)
.SetProperty("dock", &App::GetDockAPI)
#endif
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
.SetProperty("runningUnderARM64Translation",
&App::IsRunningUnderARM64Translation)
#endif
.SetProperty("userAgentFallback", &App::GetUserAgentFallback,
&App::SetUserAgentFallback)
.SetMethod("configureHostResolver", &ConfigureHostResolver)
.SetMethod("enableSandbox", &App::EnableSandbox);
}
const char* App::GetTypeName() {
return "App";
}
} // namespace electron::api
namespace {
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("app", electron::api::App::Create(isolate));
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_app, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 37,560 |
[Bug]: Open at login with setLoginItemSettings in MAS build is not working
|
### 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
16.0.6
### What operating system are you using?
macOS
### Operating System Version
Version 13.2 (22D49)
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Setting app to open at login with setLoginItemSettings api should work both locally and with MAS build.
Locally the app is added to login items but when i build it for MAS this doesn't work.
### Actual Behavior
Setting app to open at login with setLoginItemSettings api works locally but doesn't work in MAS build.
In MAS build the app is not added to login items.
<img width="477" alt="image" src="https://user-images.githubusercontent.com/17458685/224576455-a9145dfc-7121-4097-9fe4-a472f0c2ead4.png">
### Testcase Gist URL
_No response_
### Additional Information
According to docs https://www.electronjs.org/docs/latest/api/app#appsetloginitemsettingssettings-macos-windows setting login item in MAS build should work by using the following API
```js
app.setLoginItemSettings({
openAtLogin: openAtLogin,
})
```
In the docs on limitations of MAS build there is no mention of any limitation of using above API https://www.electronjs.org/docs/latest/tutorial/mac-app-store-submission-guide#limitations-of-mas-build
Here is possible related issue and PRs:
- https://github.com/electron/electron/issues/7312
- https://github.com/electron/electron/pull/11144
- https://github.com/electron/electron/pull/10856
|
https://github.com/electron/electron/issues/37560
|
https://github.com/electron/electron/pull/37244
|
6d0d350e138494cd68dd3d4fa73b2719da4575bf
|
f7b1c75c72a8dcab4157408f92bd3771606d8029
| 2023-03-12T22:11:32Z |
c++
| 2023-10-16T16:25:11Z |
shell/browser/browser.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_BROWSER_H_
#define ELECTRON_SHELL_BROWSER_BROWSER_H_
#include <memory>
#include <string>
#include <vector>
#include "base/compiler_specific.h"
#include "base/observer_list.h"
#include "base/task/cancelable_task_tracker.h"
#include "base/values.h"
#include "gin/dictionary.h"
#include "shell/browser/browser_observer.h"
#include "shell/browser/window_list_observer.h"
#include "shell/common/gin_helper/promise.h"
#if BUILDFLAG(IS_WIN)
#include <windows.h>
#include "base/files/file_path.h"
#include "shell/browser/ui/win/taskbar_host.h"
#endif
#if BUILDFLAG(IS_MAC)
#include "ui/base/cocoa/secure_password_input.h"
#endif
namespace base {
class FilePath;
}
namespace gin_helper {
class Arguments;
}
namespace electron {
class ElectronMenuModel;
// This class is used for control application-wide operations.
class Browser : public WindowListObserver {
public:
Browser();
~Browser() override;
// disable copy
Browser(const Browser&) = delete;
Browser& operator=(const Browser&) = delete;
static Browser* Get();
// Try to close all windows and quit the application.
void Quit();
// Exit the application immediately and set exit code.
void Exit(gin::Arguments* args);
// Cleanup everything and shutdown the application gracefully.
void Shutdown();
// Focus the application.
void Focus(gin::Arguments* args);
// Returns the version of the executable (or bundle).
std::string GetVersion() const;
// Overrides the application version.
void SetVersion(const std::string& version);
// Returns the application's name, default is just Electron.
std::string GetName() const;
// Overrides the application name.
void SetName(const std::string& name);
// Add the |path| to recent documents list.
void AddRecentDocument(const base::FilePath& path);
// Clear the recent documents list.
void ClearRecentDocuments();
#if BUILDFLAG(IS_WIN)
// Set the application user model ID.
void SetAppUserModelID(const std::wstring& name);
#endif
// Remove the default protocol handler registry key
bool RemoveAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args);
// Set as default handler for a protocol.
bool SetAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args);
// Query the current state of default handler for a protocol.
bool IsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args);
std::u16string GetApplicationNameForProtocol(const GURL& url);
#if !BUILDFLAG(IS_LINUX)
// get the name, icon and path for an application
v8::Local<v8::Promise> GetApplicationInfoForProtocol(v8::Isolate* isolate,
const GURL& url);
#endif
// Set/Get the badge count.
bool SetBadgeCount(absl::optional<int> count);
int GetBadgeCount();
#if BUILDFLAG(IS_WIN)
struct LaunchItem {
std::wstring name;
std::wstring path;
std::wstring scope;
std::vector<std::wstring> args;
bool enabled = true;
LaunchItem();
~LaunchItem();
LaunchItem(const LaunchItem&);
};
#endif
// Set/Get the login item settings of the app
struct LoginItemSettings {
bool open_at_login = false;
bool open_as_hidden = false;
bool restore_state = false;
bool opened_at_login = false;
bool opened_as_hidden = false;
std::u16string path;
std::vector<std::u16string> args;
#if BUILDFLAG(IS_WIN)
// used in browser::setLoginItemSettings
bool enabled = true;
std::wstring name;
// used in browser::getLoginItemSettings
bool executable_will_launch_at_login = false;
std::vector<LaunchItem> launch_items;
#endif
LoginItemSettings();
~LoginItemSettings();
LoginItemSettings(const LoginItemSettings&);
};
void SetLoginItemSettings(LoginItemSettings settings);
LoginItemSettings GetLoginItemSettings(const LoginItemSettings& options);
#if BUILDFLAG(IS_MAC)
// Set the handler which decides whether to shutdown.
void SetShutdownHandler(base::RepeatingCallback<bool()> handler);
// Hide the application.
void Hide();
bool IsHidden();
// Show the application.
void Show();
// Creates an activity and sets it as the one currently in use.
void SetUserActivity(const std::string& type,
base::Value::Dict user_info,
gin::Arguments* args);
// Returns the type name of the current user activity.
std::string GetCurrentActivityType();
// Invalidates an activity and marks it as no longer eligible for
// continuation
void InvalidateCurrentActivity();
// Marks this activity object as inactive without invalidating it.
void ResignCurrentActivity();
// Updates the current user activity
void UpdateCurrentActivity(const std::string& type,
base::Value::Dict user_info);
// Indicates that an user activity is about to be resumed.
bool WillContinueUserActivity(const std::string& type);
// Indicates a failure to resume a Handoff activity.
void DidFailToContinueUserActivity(const std::string& type,
const std::string& error);
// Resumes an activity via hand-off.
bool ContinueUserActivity(const std::string& type,
base::Value::Dict user_info,
base::Value::Dict details);
// Indicates that an activity was continued on another device.
void UserActivityWasContinued(const std::string& type,
base::Value::Dict user_info);
// Gives an opportunity to update the Handoff payload.
bool UpdateUserActivityState(const std::string& type,
base::Value::Dict user_info);
void ApplyForcedRTL();
// Bounce the dock icon.
enum class BounceType {
kCritical = 0, // NSCriticalRequest
kInformational = 10, // NSInformationalRequest
};
int DockBounce(BounceType type);
void DockCancelBounce(int request_id);
// Bounce the Downloads stack.
void DockDownloadFinished(const std::string& filePath);
// Set/Get dock's badge text.
void DockSetBadgeText(const std::string& label);
std::string DockGetBadgeText();
// Hide/Show dock.
void DockHide();
v8::Local<v8::Promise> DockShow(v8::Isolate* isolate);
bool DockIsVisible();
// Set docks' menu.
void DockSetMenu(ElectronMenuModel* model);
// Set docks' icon.
void DockSetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon);
#endif // BUILDFLAG(IS_MAC)
void ShowAboutPanel();
void SetAboutPanelOptions(base::Value::Dict options);
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
void ShowEmojiPanel();
#endif
#if BUILDFLAG(IS_WIN)
struct UserTask {
base::FilePath program;
std::wstring arguments;
std::wstring title;
std::wstring description;
base::FilePath working_dir;
base::FilePath icon_path;
int icon_index;
UserTask();
UserTask(const UserTask&);
~UserTask();
};
// Add a custom task to jump list.
bool SetUserTasks(const std::vector<UserTask>& tasks);
// Returns the application user model ID, if there isn't one, then create
// one from app's name.
// The returned string managed by Browser, and should not be modified.
PCWSTR GetAppUserModelID();
#endif // BUILDFLAG(IS_WIN)
#if BUILDFLAG(IS_LINUX)
// Whether Unity launcher is running.
bool IsUnityRunning();
#endif // BUILDFLAG(IS_LINUX)
// Tell the application to open a file.
bool OpenFile(const std::string& file_path);
// Tell the application to open a url.
void OpenURL(const std::string& url);
#if BUILDFLAG(IS_MAC)
// Tell the application to create a new window for a tab.
void NewWindowForTab();
// Indicate that the app is now active.
void DidBecomeActive();
// Indicate that the app is no longer active and doesnβt have focus.
void DidResignActive();
#endif // BUILDFLAG(IS_MAC)
// Tell the application that application is activated with visible/invisible
// windows.
void Activate(bool has_visible_windows);
bool IsEmojiPanelSupported();
// Tell the application the loading has been done.
void WillFinishLaunching();
void DidFinishLaunching(base::Value::Dict launch_info);
void OnAccessibilitySupportChanged();
void PreMainMessageLoopRun();
void PreCreateThreads();
// Stores the supplied |quit_closure|, to be run when the last Browser
// instance is destroyed.
void SetMainMessageLoopQuitClosure(base::OnceClosure quit_closure);
void AddObserver(BrowserObserver* obs) { observers_.AddObserver(obs); }
void RemoveObserver(BrowserObserver* obs) { observers_.RemoveObserver(obs); }
#if BUILDFLAG(IS_MAC)
// Returns whether secure input is enabled
bool IsSecureKeyboardEntryEnabled();
void SetSecureKeyboardEntryEnabled(bool enabled);
#endif
bool is_shutting_down() const { return is_shutdown_; }
bool is_quitting() const { return is_quitting_; }
bool is_ready() const { return is_ready_; }
v8::Local<v8::Value> WhenReady(v8::Isolate* isolate);
protected:
// Returns the version of application bundle or executable file.
std::string GetExecutableFileVersion() const;
// Returns the name of application bundle or executable file.
std::string GetExecutableFileProductName() const;
// Send the will-quit message and then shutdown the application.
void NotifyAndShutdown();
// Send the before-quit message and start closing windows.
bool HandleBeforeQuit();
bool is_quitting_ = false;
private:
// WindowListObserver implementations:
void OnWindowCloseCancelled(NativeWindow* window) override;
void OnWindowAllClosed() override;
// Observers of the browser.
base::ObserverList<BrowserObserver> observers_;
// Tracks tasks requesting file icons.
base::CancelableTaskTracker cancelable_task_tracker_;
// Whether `app.exit()` has been called
bool is_exiting_ = false;
// Whether "ready" event has been emitted.
bool is_ready_ = false;
// The browser is being shutdown.
bool is_shutdown_ = false;
// Null until/unless the default main message loop is running.
base::OnceClosure quit_main_message_loop_;
int badge_count_ = 0;
std::unique_ptr<gin_helper::Promise<void>> ready_promise_;
#if BUILDFLAG(IS_MAC)
std::unique_ptr<ui::ScopedPasswordInputEnabler> password_input_enabler_;
base::Time last_dock_show_;
#endif
base::Value::Dict about_panel_options_;
#if BUILDFLAG(IS_WIN)
void UpdateBadgeContents(HWND hwnd,
const absl::optional<std::string>& badge_content,
const std::string& badge_alt_string);
// In charge of running taskbar related APIs.
TaskbarHost taskbar_host_;
#endif
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_BROWSER_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 37,560 |
[Bug]: Open at login with setLoginItemSettings in MAS build is not working
|
### 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
16.0.6
### What operating system are you using?
macOS
### Operating System Version
Version 13.2 (22D49)
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Setting app to open at login with setLoginItemSettings api should work both locally and with MAS build.
Locally the app is added to login items but when i build it for MAS this doesn't work.
### Actual Behavior
Setting app to open at login with setLoginItemSettings api works locally but doesn't work in MAS build.
In MAS build the app is not added to login items.
<img width="477" alt="image" src="https://user-images.githubusercontent.com/17458685/224576455-a9145dfc-7121-4097-9fe4-a472f0c2ead4.png">
### Testcase Gist URL
_No response_
### Additional Information
According to docs https://www.electronjs.org/docs/latest/api/app#appsetloginitemsettingssettings-macos-windows setting login item in MAS build should work by using the following API
```js
app.setLoginItemSettings({
openAtLogin: openAtLogin,
})
```
In the docs on limitations of MAS build there is no mention of any limitation of using above API https://www.electronjs.org/docs/latest/tutorial/mac-app-store-submission-guide#limitations-of-mas-build
Here is possible related issue and PRs:
- https://github.com/electron/electron/issues/7312
- https://github.com/electron/electron/pull/11144
- https://github.com/electron/electron/pull/10856
|
https://github.com/electron/electron/issues/37560
|
https://github.com/electron/electron/pull/37244
|
6d0d350e138494cd68dd3d4fa73b2719da4575bf
|
f7b1c75c72a8dcab4157408f92bd3771606d8029
| 2023-03-12T22:11:32Z |
c++
| 2023-10-16T16:25:11Z |
shell/browser/browser_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/browser.h"
#include <memory>
#include <string>
#include <utility>
#include "base/apple/bridging.h"
#include "base/apple/bundle_locations.h"
#include "base/apple/scoped_cftyperef.h"
#include "base/i18n/rtl.h"
#include "base/mac/mac_util.h"
#include "base/mac/mac_util.mm"
#include "base/strings/string_number_conversions.h"
#include "base/strings/sys_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "net/base/mac/url_conversions.h"
#include "shell/browser/badging/badge_manager.h"
#include "shell/browser/mac/dict_util.h"
#include "shell/browser/mac/electron_application.h"
#include "shell/browser/mac/electron_application_delegate.h"
#include "shell/browser/native_window.h"
#include "shell/browser/window_list.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/application_info.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_helper/arguments.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/platform_util.h"
#include "ui/base/resource/resource_scale_factor.h"
#include "ui/gfx/image/image.h"
#include "url/gurl.h"
namespace electron {
namespace {
NSString* GetAppPathForProtocol(const GURL& url) {
NSURL* ns_url = [NSURL
URLWithString:base::SysUTF8ToNSString(url.possibly_invalid_spec())];
base::apple::ScopedCFTypeRef<CFErrorRef> out_err;
base::apple::ScopedCFTypeRef<CFURLRef> openingApp(
LSCopyDefaultApplicationURLForURL(base::apple::NSToCFPtrCast(ns_url),
kLSRolesAll, out_err.InitializeInto()));
if (out_err) {
// likely kLSApplicationNotFoundErr
return nullptr;
}
NSString* app_path = [base::apple::CFToNSPtrCast(openingApp.get()) path];
return app_path;
}
gfx::Image GetApplicationIconForProtocol(NSString* _Nonnull app_path) {
NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile:app_path];
gfx::Image icon(image);
return icon;
}
std::u16string GetAppDisplayNameForProtocol(NSString* app_path) {
NSString* app_display_name =
[[NSFileManager defaultManager] displayNameAtPath:app_path];
return base::SysNSStringToUTF16(app_display_name);
}
#if !IS_MAS_BUILD()
bool CheckLoginItemStatus(bool* is_hidden) {
base::mac::LoginItemsFileList login_items;
if (!login_items.Initialize())
return false;
base::apple::ScopedCFTypeRef<LSSharedFileListItemRef> item(
login_items.GetLoginItemForMainApp());
if (!item.get())
return false;
if (is_hidden)
*is_hidden = base::mac::IsHiddenLoginItem(item);
return true;
}
#endif
} // namespace
v8::Local<v8::Promise> Browser::GetApplicationInfoForProtocol(
v8::Isolate* isolate,
const GURL& url) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
NSString* ns_app_path = GetAppPathForProtocol(url);
if (!ns_app_path) {
promise.RejectWithErrorMessage(
"Unable to retrieve installation path to app");
return handle;
}
std::u16string app_path = base::SysNSStringToUTF16(ns_app_path);
std::u16string app_display_name = GetAppDisplayNameForProtocol(ns_app_path);
gfx::Image app_icon = GetApplicationIconForProtocol(ns_app_path);
dict.Set("name", app_display_name);
dict.Set("path", app_path);
dict.Set("icon", app_icon);
promise.Resolve(dict);
return handle;
}
void Browser::SetShutdownHandler(base::RepeatingCallback<bool()> handler) {
[[AtomApplication sharedApplication] setShutdownHandler:std::move(handler)];
}
void Browser::Focus(gin::Arguments* args) {
gin_helper::Dictionary opts;
bool steal_focus = false;
if (args->GetNext(&opts)) {
gin_helper::ErrorThrower thrower(args->isolate());
if (!opts.Get("steal", &steal_focus)) {
thrower.ThrowError(
"Expected options object to contain a 'steal' boolean property");
return;
}
}
[[AtomApplication sharedApplication] activateIgnoringOtherApps:steal_focus];
}
void Browser::Hide() {
[[AtomApplication sharedApplication] hide:nil];
}
bool Browser::IsHidden() {
return [[AtomApplication sharedApplication] isHidden];
}
void Browser::Show() {
[[AtomApplication sharedApplication] unhide:nil];
}
void Browser::AddRecentDocument(const base::FilePath& path) {
NSString* path_string = base::apple::FilePathToNSString(path);
if (!path_string)
return;
NSURL* u = [NSURL fileURLWithPath:path_string];
if (!u)
return;
[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:u];
}
void Browser::ClearRecentDocuments() {
[[NSDocumentController sharedDocumentController] clearRecentDocuments:nil];
}
bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args) {
NSString* identifier = [base::apple::MainBundle() bundleIdentifier];
if (!identifier)
return false;
if (!Browser::IsDefaultProtocolClient(protocol, args))
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
CFStringRef protocol_cf = base::apple::NSToCFPtrCast(protocol_ns);
// TODO(codebytere): Use -[NSWorkspace URLForApplicationToOpenURL:] instead
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
CFArrayRef bundleList = LSCopyAllHandlersForURLScheme(protocol_cf);
#pragma clang diagnostic pop
if (!bundleList) {
return false;
}
// On macOS, we can't query the default, but the handlers list seems to put
// Apple's defaults first, so we'll use the first option that isn't our bundle
CFStringRef other = nil;
for (CFIndex i = 0; i < CFArrayGetCount(bundleList); ++i) {
other =
base::apple::CFCast<CFStringRef>(CFArrayGetValueAtIndex(bundleList, i));
if (![identifier isEqualToString:(__bridge NSString*)other]) {
break;
}
}
// No other app was found set it to none instead of setting it back to itself.
if ([identifier isEqualToString:(__bridge NSString*)other]) {
other = base::apple::NSToCFPtrCast(@"None");
}
OSStatus return_code = LSSetDefaultHandlerForURLScheme(protocol_cf, other);
return return_code == noErr;
}
bool Browser::SetAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args) {
if (protocol.empty())
return false;
NSString* identifier = [base::apple::MainBundle() bundleIdentifier];
if (!identifier)
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
OSStatus return_code =
LSSetDefaultHandlerForURLScheme(base::apple::NSToCFPtrCast(protocol_ns),
base::apple::NSToCFPtrCast(identifier));
return return_code == noErr;
}
bool Browser::IsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args) {
if (protocol.empty())
return false;
NSString* identifier = [base::apple::MainBundle() bundleIdentifier];
if (!identifier)
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
// TODO(codebytere): Use -[NSWorkspace URLForApplicationToOpenURL:] instead
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
base::apple::ScopedCFTypeRef<CFStringRef> bundleId(
LSCopyDefaultHandlerForURLScheme(
base::apple::NSToCFPtrCast(protocol_ns)));
#pragma clang diagnostic pop
if (!bundleId)
return false;
// Ensure the comparison is case-insensitive
// as LS does not persist the case of the bundle id.
NSComparisonResult result =
[base::apple::CFToNSPtrCast(bundleId) caseInsensitiveCompare:identifier];
return result == NSOrderedSame;
}
std::u16string Browser::GetApplicationNameForProtocol(const GURL& url) {
NSString* app_path = GetAppPathForProtocol(url);
if (!app_path) {
return std::u16string();
}
std::u16string app_display_name = GetAppDisplayNameForProtocol(app_path);
return app_display_name;
}
bool Browser::SetBadgeCount(absl::optional<int> count) {
DockSetBadgeText(!count.has_value() || count.value() != 0
? badging::BadgeManager::GetBadgeString(count)
: "");
if (count.has_value()) {
badge_count_ = count.value();
} else {
badge_count_ = 0;
}
return true;
}
void Browser::SetUserActivity(const std::string& type,
base::Value::Dict user_info,
gin::Arguments* args) {
std::string url_string;
args->GetNext(&url_string);
[[AtomApplication sharedApplication]
setCurrentActivity:base::SysUTF8ToNSString(type)
withUserInfo:DictionaryValueToNSDictionary(std::move(user_info))
withWebpageURL:net::NSURLWithGURL(GURL(url_string))];
}
std::string Browser::GetCurrentActivityType() {
NSUserActivity* userActivity =
[[AtomApplication sharedApplication] getCurrentActivity];
return base::SysNSStringToUTF8(userActivity.activityType);
}
void Browser::InvalidateCurrentActivity() {
[[AtomApplication sharedApplication] invalidateCurrentActivity];
}
void Browser::ResignCurrentActivity() {
[[AtomApplication sharedApplication] resignCurrentActivity];
}
void Browser::UpdateCurrentActivity(const std::string& type,
base::Value::Dict user_info) {
[[AtomApplication sharedApplication]
updateCurrentActivity:base::SysUTF8ToNSString(type)
withUserInfo:DictionaryValueToNSDictionary(
std::move(user_info))];
}
bool Browser::WillContinueUserActivity(const std::string& type) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnWillContinueUserActivity(&prevent_default, type);
return prevent_default;
}
void Browser::DidFailToContinueUserActivity(const std::string& type,
const std::string& error) {
for (BrowserObserver& observer : observers_)
observer.OnDidFailToContinueUserActivity(type, error);
}
bool Browser::ContinueUserActivity(const std::string& type,
base::Value::Dict user_info,
base::Value::Dict details) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnContinueUserActivity(&prevent_default, type, user_info.Clone(),
details.Clone());
return prevent_default;
}
void Browser::UserActivityWasContinued(const std::string& type,
base::Value::Dict user_info) {
for (BrowserObserver& observer : observers_)
observer.OnUserActivityWasContinued(type, user_info.Clone());
}
bool Browser::UpdateUserActivityState(const std::string& type,
base::Value::Dict user_info) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnUpdateUserActivityState(&prevent_default, type,
user_info.Clone());
return prevent_default;
}
// Modified from chrome/browser/ui/cocoa/l10n_util.mm.
void Browser::ApplyForcedRTL() {
NSUserDefaults* defaults = NSUserDefaults.standardUserDefaults;
auto dir = base::i18n::GetForcedTextDirection();
// An Electron app should respect RTL behavior of application locale over
// system locale.
auto should_be_rtl = dir == base::i18n::RIGHT_TO_LEFT || IsAppRTL();
auto should_be_ltr = dir == base::i18n::LEFT_TO_RIGHT || !IsAppRTL();
// -registerDefaults: won't do the trick here because these defaults exist
// (in the global domain) to reflect the system locale. They need to be set
// in Chrome's domain to supersede the system value.
if (should_be_rtl) {
[defaults setBool:YES forKey:@"AppleTextDirection"];
[defaults setBool:YES forKey:@"NSForceRightToLeftWritingDirection"];
} else if (should_be_ltr) {
[defaults setBool:YES forKey:@"AppleTextDirection"];
[defaults setBool:NO forKey:@"NSForceRightToLeftWritingDirection"];
} else {
[defaults removeObjectForKey:@"AppleTextDirection"];
[defaults removeObjectForKey:@"NSForceRightToLeftWritingDirection"];
}
}
Browser::LoginItemSettings Browser::GetLoginItemSettings(
const LoginItemSettings& options) {
LoginItemSettings settings;
#if IS_MAS_BUILD()
settings.open_at_login = platform_util::GetLoginItemEnabled();
#else
settings.open_at_login = CheckLoginItemStatus(&settings.open_as_hidden);
settings.restore_state = base::mac::WasLaunchedAsLoginItemRestoreState();
settings.opened_at_login = base::mac::WasLaunchedAsLoginOrResumeItem();
settings.opened_as_hidden = base::mac::WasLaunchedAsHiddenLoginItem();
#endif
return settings;
}
void Browser::SetLoginItemSettings(LoginItemSettings settings) {
#if IS_MAS_BUILD()
if (!platform_util::SetLoginItemEnabled(settings.open_at_login)) {
LOG(ERROR) << "Unable to set login item enabled on sandboxed app.";
}
#else
if (settings.open_at_login) {
base::mac::AddToLoginItems(base::apple::MainBundlePath(),
settings.open_as_hidden);
} else {
base::mac::RemoveFromLoginItems(base::apple::MainBundlePath());
}
#endif
}
std::string Browser::GetExecutableFileVersion() const {
return GetApplicationVersion();
}
std::string Browser::GetExecutableFileProductName() const {
return GetApplicationName();
}
int Browser::DockBounce(BounceType type) {
return [[AtomApplication sharedApplication]
requestUserAttention:static_cast<NSRequestUserAttentionType>(type)];
}
void Browser::DockCancelBounce(int request_id) {
[[AtomApplication sharedApplication] cancelUserAttentionRequest:request_id];
}
void Browser::DockSetBadgeText(const std::string& label) {
NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
[tile setBadgeLabel:base::SysUTF8ToNSString(label)];
}
void Browser::DockDownloadFinished(const std::string& filePath) {
[[NSDistributedNotificationCenter defaultCenter]
postNotificationName:@"com.apple.DownloadFileFinished"
object:base::SysUTF8ToNSString(filePath)];
}
std::string Browser::DockGetBadgeText() {
NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
return base::SysNSStringToUTF8([tile badgeLabel]);
}
void Browser::DockHide() {
// Transforming application state from UIElement to Foreground is an
// asynchronous operation, and unfortunately there is currently no way to know
// when it is finished.
// So if we call DockHide => DockShow => DockHide => DockShow in a very short
// time, we would trigger a bug of macOS that, there would be multiple dock
// icons of the app left in system.
// To work around this, we make sure DockHide does nothing if it is called
// immediately after DockShow. After some experiments, 1 second seems to be
// a proper interval.
if (!last_dock_show_.is_null() &&
base::Time::Now() - last_dock_show_ < base::Seconds(1)) {
return;
}
for (auto* const& window : WindowList::GetWindows())
[window->GetNativeWindow().GetNativeNSWindow() setCanHide:NO];
ProcessSerialNumber psn = {0, kCurrentProcess};
TransformProcessType(&psn, kProcessTransformToUIElementApplication);
}
bool Browser::DockIsVisible() {
// Because DockShow has a slight delay this may not be true immediately
// after that call.
return ([[NSRunningApplication currentApplication] activationPolicy] ==
NSApplicationActivationPolicyRegular);
}
v8::Local<v8::Promise> Browser::DockShow(v8::Isolate* isolate) {
last_dock_show_ = base::Time::Now();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
BOOL active = [[NSRunningApplication currentApplication] isActive];
ProcessSerialNumber psn = {0, kCurrentProcess};
if (active) {
// Workaround buggy behavior of TransformProcessType.
// http://stackoverflow.com/questions/7596643/
NSArray* runningApps = [NSRunningApplication
runningApplicationsWithBundleIdentifier:@"com.apple.dock"];
for (NSRunningApplication* app in runningApps) {
[app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
break;
}
__block gin_helper::Promise<void> p = std::move(promise);
dispatch_time_t one_ms = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
dispatch_after(one_ms, dispatch_get_main_queue(), ^{
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
dispatch_time_t one_ms_2 = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
dispatch_after(one_ms_2, dispatch_get_main_queue(), ^{
[[NSRunningApplication currentApplication]
activateWithOptions:NSApplicationActivateIgnoringOtherApps];
p.Resolve();
});
});
} else {
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
promise.Resolve();
}
return handle;
}
void Browser::DockSetMenu(ElectronMenuModel* model) {
ElectronApplicationDelegate* delegate =
(ElectronApplicationDelegate*)[NSApp delegate];
[delegate setApplicationDockMenu:model];
}
void Browser::DockSetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) {
gfx::Image image;
if (!icon->IsNull()) {
api::NativeImage* native_image = nullptr;
if (!api::NativeImage::TryConvertNativeImage(isolate, icon, &native_image))
return;
image = native_image->image();
}
// This is needed to avoid a hard CHECK when this fn is called
// before the browser process is ready, since supported scales
// are normally set by ui::ResourceBundle::InitSharedInstance
// during browser process startup.
if (!is_ready())
ui::SetSupportedResourceScaleFactors({ui::k100Percent});
[[AtomApplication sharedApplication]
setApplicationIconImage:image.AsNSImage()];
}
void Browser::ShowAboutPanel() {
NSDictionary* options = DictionaryValueToNSDictionary(about_panel_options_);
// Credits must be a NSAttributedString instead of NSString
NSString* credits = (NSString*)options[@"Credits"];
if (credits != nil) {
NSMutableDictionary* mutable_options = [options mutableCopy];
NSAttributedString* creditString = [[NSAttributedString alloc]
initWithString:credits
attributes:@{NSForegroundColorAttributeName : [NSColor textColor]}];
[mutable_options setValue:creditString forKey:@"Credits"];
options = [NSDictionary dictionaryWithDictionary:mutable_options];
}
[[AtomApplication sharedApplication]
orderFrontStandardAboutPanelWithOptions:options];
}
void Browser::SetAboutPanelOptions(base::Value::Dict options) {
about_panel_options_.clear();
for (const auto pair : options) {
std::string key = pair.first;
if (!key.empty() && pair.second.is_string()) {
key[0] = base::ToUpperASCII(key[0]);
about_panel_options_.Set(key, pair.second.Clone());
}
}
}
void Browser::ShowEmojiPanel() {
[[AtomApplication sharedApplication] orderFrontCharacterPalette:nil];
}
bool Browser::IsEmojiPanelSupported() {
return true;
}
bool Browser::IsSecureKeyboardEntryEnabled() {
return password_input_enabler_.get() != nullptr;
}
void Browser::SetSecureKeyboardEntryEnabled(bool enabled) {
if (enabled) {
password_input_enabler_ =
std::make_unique<ui::ScopedPasswordInputEnabler>();
} else {
password_input_enabler_.reset();
}
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 37,560 |
[Bug]: Open at login with setLoginItemSettings in MAS build is not working
|
### 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
16.0.6
### What operating system are you using?
macOS
### Operating System Version
Version 13.2 (22D49)
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Setting app to open at login with setLoginItemSettings api should work both locally and with MAS build.
Locally the app is added to login items but when i build it for MAS this doesn't work.
### Actual Behavior
Setting app to open at login with setLoginItemSettings api works locally but doesn't work in MAS build.
In MAS build the app is not added to login items.
<img width="477" alt="image" src="https://user-images.githubusercontent.com/17458685/224576455-a9145dfc-7121-4097-9fe4-a472f0c2ead4.png">
### Testcase Gist URL
_No response_
### Additional Information
According to docs https://www.electronjs.org/docs/latest/api/app#appsetloginitemsettingssettings-macos-windows setting login item in MAS build should work by using the following API
```js
app.setLoginItemSettings({
openAtLogin: openAtLogin,
})
```
In the docs on limitations of MAS build there is no mention of any limitation of using above API https://www.electronjs.org/docs/latest/tutorial/mac-app-store-submission-guide#limitations-of-mas-build
Here is possible related issue and PRs:
- https://github.com/electron/electron/issues/7312
- https://github.com/electron/electron/pull/11144
- https://github.com/electron/electron/pull/10856
|
https://github.com/electron/electron/issues/37560
|
https://github.com/electron/electron/pull/37244
|
6d0d350e138494cd68dd3d4fa73b2719da4575bf
|
f7b1c75c72a8dcab4157408f92bd3771606d8029
| 2023-03-12T22:11:32Z |
c++
| 2023-10-16T16:25:11Z |
shell/common/platform_util.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_PLATFORM_UTIL_H_
#define ELECTRON_SHELL_COMMON_PLATFORM_UTIL_H_
#include <string>
#include "base/files/file_path.h"
#include "base/functional/callback_forward.h"
#include "build/build_config.h"
class GURL;
namespace platform_util {
typedef base::OnceCallback<void(const std::string&)> OpenCallback;
// Show the given file in a file manager. If possible, select the file.
// Must be called from the UI thread.
void ShowItemInFolder(const base::FilePath& full_path);
// Open the given file in the desktop's default manner.
// Must be called from the UI thread.
void OpenPath(const base::FilePath& full_path, OpenCallback callback);
struct OpenExternalOptions {
bool activate = true;
base::FilePath working_dir;
bool log_usage = false;
};
// Open the given external protocol URL in the desktop's default manner.
// (For example, mailto: URLs in the default mail user agent.)
void OpenExternal(const GURL& url,
const OpenExternalOptions& options,
OpenCallback callback);
// Move a file to trash, asynchronously.
void TrashItem(const base::FilePath& full_path,
base::OnceCallback<void(bool, const std::string&)> callback);
void Beep();
#if BUILDFLAG(IS_WIN)
// SHGetFolderPath calls not covered by Chromium
bool GetFolderPath(int key, base::FilePath* result);
#endif
#if BUILDFLAG(IS_MAC)
bool GetLoginItemEnabled();
bool SetLoginItemEnabled(bool enabled);
#endif
#if BUILDFLAG(IS_LINUX)
// Returns a success flag.
// Unlike libgtkui, does *not* use "chromium-browser.desktop" as a fallback.
bool GetDesktopName(std::string* setme);
// The XDG application ID must match the name of the desktop entry file without
// the .desktop extension.
std::string GetXdgAppId();
#endif
} // namespace platform_util
#endif // ELECTRON_SHELL_COMMON_PLATFORM_UTIL_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 37,560 |
[Bug]: Open at login with setLoginItemSettings in MAS build is not working
|
### 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
16.0.6
### What operating system are you using?
macOS
### Operating System Version
Version 13.2 (22D49)
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Setting app to open at login with setLoginItemSettings api should work both locally and with MAS build.
Locally the app is added to login items but when i build it for MAS this doesn't work.
### Actual Behavior
Setting app to open at login with setLoginItemSettings api works locally but doesn't work in MAS build.
In MAS build the app is not added to login items.
<img width="477" alt="image" src="https://user-images.githubusercontent.com/17458685/224576455-a9145dfc-7121-4097-9fe4-a472f0c2ead4.png">
### Testcase Gist URL
_No response_
### Additional Information
According to docs https://www.electronjs.org/docs/latest/api/app#appsetloginitemsettingssettings-macos-windows setting login item in MAS build should work by using the following API
```js
app.setLoginItemSettings({
openAtLogin: openAtLogin,
})
```
In the docs on limitations of MAS build there is no mention of any limitation of using above API https://www.electronjs.org/docs/latest/tutorial/mac-app-store-submission-guide#limitations-of-mas-build
Here is possible related issue and PRs:
- https://github.com/electron/electron/issues/7312
- https://github.com/electron/electron/pull/11144
- https://github.com/electron/electron/pull/10856
|
https://github.com/electron/electron/issues/37560
|
https://github.com/electron/electron/pull/37244
|
6d0d350e138494cd68dd3d4fa73b2719da4575bf
|
f7b1c75c72a8dcab4157408f92bd3771606d8029
| 2023-03-12T22:11:32Z |
c++
| 2023-10-16T16:25:11Z |
shell/common/platform_util_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/common/platform_util.h"
#include <string>
#include <utility>
#import <Carbon/Carbon.h>
#import <Cocoa/Cocoa.h>
#import <ServiceManagement/ServiceManagement.h>
#include "base/apple/foundation_util.h"
#include "base/apple/osstatus_logging.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/callback.h"
#include "base/logging.h"
#include "base/mac/scoped_aedesc.h"
#include "base/strings/stringprintf.h"
#include "base/strings/sys_string_conversions.h"
#include "net/base/mac/url_conversions.h"
#include "ui/views/widget/widget.h"
#include "url/gurl.h"
namespace {
// This may be called from a global dispatch queue, the methods used here are
// thread safe, including LSGetApplicationForURL (> 10.2) and
// NSWorkspace#openURLs.
std::string OpenURL(NSURL* ns_url, bool activate) {
CFURLRef cf_url = (__bridge CFURLRef)(ns_url);
CFURLRef ref =
LSCopyDefaultApplicationURLForURL(cf_url, kLSRolesAll, nullptr);
// If no application could be found, nullptr is returned and outError
// (if not nullptr) is populated with kLSApplicationNotFoundErr.
if (ref == nullptr)
return "No application in the Launch Services database matches the input "
"criteria.";
NSUInteger launchOptions = NSWorkspaceLaunchDefault;
if (!activate)
launchOptions |= NSWorkspaceLaunchWithoutActivation;
bool opened = [[NSWorkspace sharedWorkspace] openURLs:@[ ns_url ]
withAppBundleIdentifier:nil
options:launchOptions
additionalEventParamDescriptor:nil
launchIdentifiers:nil];
if (!opened)
return "Failed to open URL";
return "";
}
NSString* GetLoginHelperBundleIdentifier() {
return [[[NSBundle mainBundle] bundleIdentifier]
stringByAppendingString:@".loginhelper"];
}
std::string OpenPathOnThread(const base::FilePath& full_path) {
NSString* path_string = base::SysUTF8ToNSString(full_path.value());
NSURL* url = [NSURL fileURLWithPath:path_string];
if (!url)
return "Invalid path";
const NSWorkspaceLaunchOptions launch_options =
NSWorkspaceLaunchAsync | NSWorkspaceLaunchWithErrorPresentation;
BOOL success = [[NSWorkspace sharedWorkspace] openURLs:@[ url ]
withAppBundleIdentifier:nil
options:launch_options
additionalEventParamDescriptor:nil
launchIdentifiers:nil];
return success ? "" : "Failed to open path";
}
} // namespace
namespace platform_util {
void ShowItemInFolder(const base::FilePath& path) {
// The API only takes absolute path.
base::FilePath full_path =
path.IsAbsolute() ? path : base::MakeAbsoluteFilePath(path);
DCHECK([NSThread isMainThread]);
NSString* path_string = base::SysUTF8ToNSString(full_path.value());
if (!path_string || ![[NSWorkspace sharedWorkspace] selectFile:path_string
inFileViewerRootedAtPath:@""]) {
LOG(WARNING) << "NSWorkspace failed to select file " << full_path.value();
}
}
void OpenPath(const base::FilePath& full_path, OpenCallback callback) {
std::move(callback).Run(OpenPathOnThread(full_path));
}
void OpenExternal(const GURL& url,
const OpenExternalOptions& options,
OpenCallback callback) {
DCHECK([NSThread isMainThread]);
NSURL* ns_url = net::NSURLWithGURL(url);
if (!ns_url) {
std::move(callback).Run("Invalid URL");
return;
}
bool activate = options.activate;
__block OpenCallback c = std::move(callback);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
__block std::string error = OpenURL(ns_url, activate);
dispatch_async(dispatch_get_main_queue(), ^{
std::move(c).Run(error);
});
});
}
bool MoveItemToTrashWithError(const base::FilePath& full_path,
bool delete_on_fail,
std::string* error) {
NSString* path_string = base::SysUTF8ToNSString(full_path.value());
if (!path_string) {
*error = "Invalid file path: " + full_path.value();
LOG(WARNING) << *error;
return false;
}
NSURL* url = [NSURL fileURLWithPath:path_string];
NSError* err = nil;
BOOL did_trash = [[NSFileManager defaultManager] trashItemAtURL:url
resultingItemURL:nil
error:&err];
if (delete_on_fail) {
// Some volumes may not support a Trash folder or it may be disabled
// so these methods will report failure by returning NO or nil and
// an NSError with NSFeatureUnsupportedError.
// Handle this by deleting the item as a fallback.
if (!did_trash && [err code] == NSFeatureUnsupportedError) {
did_trash = [[NSFileManager defaultManager] removeItemAtURL:url
error:&err];
}
}
if (!did_trash) {
*error = base::SysNSStringToUTF8([err localizedDescription]);
LOG(WARNING) << "NSWorkspace failed to move file " << full_path.value()
<< " to trash: " << *error;
}
return did_trash;
}
namespace internal {
bool PlatformTrashItem(const base::FilePath& full_path, std::string* error) {
return MoveItemToTrashWithError(full_path, false, error);
}
} // namespace internal
void Beep() {
NSBeep();
}
bool GetLoginItemEnabled() {
BOOL enabled = NO;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
// SMJobCopyDictionary does not work in sandbox (see rdar://13626319)
CFArrayRef jobs = SMCopyAllJobDictionaries(kSMDomainUserLaunchd);
#pragma clang diagnostic pop
NSArray* jobs_ = CFBridgingRelease(jobs);
NSString* identifier = GetLoginHelperBundleIdentifier();
if (jobs_ && [jobs_ count] > 0) {
for (NSDictionary* job in jobs_) {
if ([identifier isEqualToString:[job objectForKey:@"Label"]]) {
enabled = [[job objectForKey:@"OnDemand"] boolValue];
break;
}
}
}
return enabled;
}
bool SetLoginItemEnabled(bool enabled) {
NSString* identifier = GetLoginHelperBundleIdentifier();
return SMLoginItemSetEnabled((__bridge CFStringRef)identifier, enabled);
}
} // namespace platform_util
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 37,560 |
[Bug]: Open at login with setLoginItemSettings in MAS build is not working
|
### 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
16.0.6
### What operating system are you using?
macOS
### Operating System Version
Version 13.2 (22D49)
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Setting app to open at login with setLoginItemSettings api should work both locally and with MAS build.
Locally the app is added to login items but when i build it for MAS this doesn't work.
### Actual Behavior
Setting app to open at login with setLoginItemSettings api works locally but doesn't work in MAS build.
In MAS build the app is not added to login items.
<img width="477" alt="image" src="https://user-images.githubusercontent.com/17458685/224576455-a9145dfc-7121-4097-9fe4-a472f0c2ead4.png">
### Testcase Gist URL
_No response_
### Additional Information
According to docs https://www.electronjs.org/docs/latest/api/app#appsetloginitemsettingssettings-macos-windows setting login item in MAS build should work by using the following API
```js
app.setLoginItemSettings({
openAtLogin: openAtLogin,
})
```
In the docs on limitations of MAS build there is no mention of any limitation of using above API https://www.electronjs.org/docs/latest/tutorial/mac-app-store-submission-guide#limitations-of-mas-build
Here is possible related issue and PRs:
- https://github.com/electron/electron/issues/7312
- https://github.com/electron/electron/pull/11144
- https://github.com/electron/electron/pull/10856
|
https://github.com/electron/electron/issues/37560
|
https://github.com/electron/electron/pull/37244
|
6d0d350e138494cd68dd3d4fa73b2719da4575bf
|
f7b1c75c72a8dcab4157408f92bd3771606d8029
| 2023-03-12T22:11:32Z |
c++
| 2023-10-16T16:25:11Z |
spec/api-app-spec.ts
|
import { assert, expect } from 'chai';
import * as cp from 'node:child_process';
import * as https from 'node:https';
import * as http from 'node:http';
import * as net from 'node:net';
import * as fs from 'fs-extra';
import * as path from 'node:path';
import { promisify } from 'node:util';
import { app, BrowserWindow, Menu, session, net as electronNet, WebContents } from 'electron/main';
import { closeWindow, closeAllWindows } from './lib/window-helpers';
import { ifdescribe, ifit, listen, waitUntil } from './lib/spec-helpers';
import { expectDeprecationMessages } from './lib/deprecate-helpers';
import { once } from 'node:events';
import split = require('split')
const fixturesPath = path.resolve(__dirname, 'fixtures');
describe('electron module', () => {
it('does not expose internal modules to require', () => {
expect(() => {
require('clipboard');
}).to.throw(/Cannot find module 'clipboard'/);
});
describe('require("electron")', () => {
it('always returns the internal electron module', () => {
require('electron');
});
});
});
describe('app module', () => {
let server: https.Server;
let secureUrl: string;
const certPath = path.join(fixturesPath, 'certificates');
before(async () => {
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
};
server = https.createServer(options, (req, res) => {
if ((req as any).client.authorized) {
res.writeHead(200);
res.end('<title>authorized</title>');
} else {
res.writeHead(401);
res.end('<title>denied</title>');
}
});
secureUrl = (await listen(server)).url;
});
after(done => {
server.close(() => done());
});
describe('app.getVersion()', () => {
it('returns the version field of package.json', () => {
expect(app.getVersion()).to.equal('0.1.0');
});
});
describe('app.setVersion(version)', () => {
it('overrides the version', () => {
expect(app.getVersion()).to.equal('0.1.0');
app.setVersion('test-version');
expect(app.getVersion()).to.equal('test-version');
app.setVersion('0.1.0');
});
});
describe('app name APIs', () => {
it('with properties', () => {
it('returns the name field of package.json', () => {
expect(app.name).to.equal('Electron Test Main');
});
it('overrides the name', () => {
expect(app.name).to.equal('Electron Test Main');
app.name = 'electron-test-name';
expect(app.name).to.equal('electron-test-name');
app.name = 'Electron Test Main';
});
});
it('with functions', () => {
it('returns the name field of package.json', () => {
expect(app.getName()).to.equal('Electron Test Main');
});
it('overrides the name', () => {
expect(app.getName()).to.equal('Electron Test Main');
app.setName('electron-test-name');
expect(app.getName()).to.equal('electron-test-name');
app.setName('Electron Test Main');
});
});
});
describe('app.getLocale()', () => {
it('should not be empty', () => {
expect(app.getLocale()).to.not.equal('');
});
});
describe('app.getSystemLocale()', () => {
it('should not be empty', () => {
expect(app.getSystemLocale()).to.not.equal('');
});
});
describe('app.getPreferredSystemLanguages()', () => {
ifit(process.platform !== 'linux')('should not be empty', () => {
expect(app.getPreferredSystemLanguages().length).to.not.equal(0);
});
ifit(process.platform === 'linux')('should be empty or contain C entry', () => {
const languages = app.getPreferredSystemLanguages();
if (languages.length) {
expect(languages).to.not.include('C');
}
});
});
describe('app.getLocaleCountryCode()', () => {
it('should be empty or have length of two', () => {
const localeCountryCode = app.getLocaleCountryCode();
expect(localeCountryCode).to.be.a('string');
expect(localeCountryCode.length).to.be.oneOf([0, 2]);
});
});
describe('app.isPackaged', () => {
it('should be false during tests', () => {
expect(app.isPackaged).to.equal(false);
});
});
ifdescribe(process.platform === 'darwin')('app.isInApplicationsFolder()', () => {
it('should be false during tests', () => {
expect(app.isInApplicationsFolder()).to.equal(false);
});
});
describe('app.exit(exitCode)', () => {
let appProcess: cp.ChildProcess | null = null;
afterEach(() => {
if (appProcess) appProcess.kill();
});
it('emits a process exit event with the code', async () => {
const appPath = path.join(fixturesPath, 'api', 'quit-app');
const electronPath = process.execPath;
let output = '';
appProcess = cp.spawn(electronPath, [appPath]);
if (appProcess && appProcess.stdout) {
appProcess.stdout.on('data', data => { output += data; });
}
const [code] = await once(appProcess, 'exit');
if (process.platform !== 'win32') {
expect(output).to.include('Exit event with code: 123');
}
expect(code).to.equal(123);
});
it('closes all windows', async function () {
const appPath = path.join(fixturesPath, 'api', 'exit-closes-all-windows-app');
const electronPath = process.execPath;
appProcess = cp.spawn(electronPath, [appPath]);
const [code, signal] = await once(appProcess, 'exit');
expect(signal).to.equal(null, 'exit signal should be null, if you see this please tag @MarshallOfSound');
expect(code).to.equal(123, 'exit code should be 123, if you see this please tag @MarshallOfSound');
});
ifit(['darwin', 'linux'].includes(process.platform))('exits gracefully', async function () {
const electronPath = process.execPath;
const appPath = path.join(fixturesPath, 'api', 'singleton');
appProcess = cp.spawn(electronPath, [appPath]);
// Singleton will send us greeting data to let us know it's running.
// After that, ask it to exit gracefully and confirm that it does.
if (appProcess && appProcess.stdout) {
appProcess.stdout.on('data', () => appProcess!.kill());
}
const [code, signal] = await once(appProcess, 'exit');
const message = `code:\n${code}\nsignal:\n${signal}`;
expect(code).to.equal(0, message);
expect(signal).to.equal(null, message);
});
});
ifdescribe(process.platform === 'darwin')('app.setActivationPolicy', () => {
it('throws an error on invalid application policies', () => {
expect(() => {
app.setActivationPolicy('terrible' as any);
}).to.throw(/Invalid activation policy: must be one of 'regular', 'accessory', or 'prohibited'/);
});
});
describe('app.requestSingleInstanceLock', () => {
interface SingleInstanceLockTestArgs {
args: string[];
expectedAdditionalData: unknown;
}
it('prevents the second launch of app', async function () {
this.timeout(120000);
const appPath = path.join(fixturesPath, 'api', 'singleton-data');
const first = cp.spawn(process.execPath, [appPath]);
await once(first.stdout, 'data');
// Start second app when received output.
const second = cp.spawn(process.execPath, [appPath]);
const [code2] = await once(second, 'exit');
expect(code2).to.equal(1);
const [code1] = await once(first, 'exit');
expect(code1).to.equal(0);
});
it('returns true when setting non-existent user data folder', async function () {
const appPath = path.join(fixturesPath, 'api', 'singleton-userdata');
const instance = cp.spawn(process.execPath, [appPath]);
const [code] = await once(instance, 'exit');
expect(code).to.equal(0);
});
async function testArgumentPassing (testArgs: SingleInstanceLockTestArgs) {
const appPath = path.join(fixturesPath, 'api', 'singleton-data');
const first = cp.spawn(process.execPath, [appPath, ...testArgs.args]);
const firstExited = once(first, 'exit');
// Wait for the first app to boot.
const firstStdoutLines = first.stdout.pipe(split());
while ((await once(firstStdoutLines, 'data')).toString() !== 'started') {
// wait.
}
const additionalDataPromise = once(firstStdoutLines, 'data');
const secondInstanceArgs = [process.execPath, appPath, ...testArgs.args, '--some-switch', 'some-arg'];
const second = cp.spawn(secondInstanceArgs[0], secondInstanceArgs.slice(1));
const secondExited = once(second, 'exit');
const [code2] = await secondExited;
expect(code2).to.equal(1);
const [code1] = await firstExited;
expect(code1).to.equal(0);
const dataFromSecondInstance = await additionalDataPromise;
const [args, additionalData] = dataFromSecondInstance[0].toString('ascii').split('||');
const secondInstanceArgsReceived: string[] = JSON.parse(args.toString('ascii'));
const secondInstanceDataReceived = JSON.parse(additionalData.toString('ascii'));
// Ensure secondInstanceArgs is a subset of secondInstanceArgsReceived
for (const arg of secondInstanceArgs) {
expect(secondInstanceArgsReceived).to.include(arg,
`argument ${arg} is missing from received second args`);
}
expect(secondInstanceDataReceived).to.be.deep.equal(testArgs.expectedAdditionalData,
`received data ${JSON.stringify(secondInstanceDataReceived)} is not equal to expected data ${JSON.stringify(testArgs.expectedAdditionalData)}.`);
}
it('passes arguments to the second-instance event no additional data', async () => {
await testArgumentPassing({
args: [],
expectedAdditionalData: null
});
});
it('sends and receives JSON object data', async () => {
const expectedAdditionalData = {
level: 1,
testkey: 'testvalue1',
inner: {
level: 2,
testkey: 'testvalue2'
}
};
await testArgumentPassing({
args: ['--send-data'],
expectedAdditionalData
});
});
it('sends and receives numerical data', async () => {
await testArgumentPassing({
args: ['--send-data', '--data-content=2'],
expectedAdditionalData: 2
});
});
it('sends and receives string data', async () => {
await testArgumentPassing({
args: ['--send-data', '--data-content="data"'],
expectedAdditionalData: 'data'
});
});
it('sends and receives boolean data', async () => {
await testArgumentPassing({
args: ['--send-data', '--data-content=false'],
expectedAdditionalData: false
});
});
it('sends and receives array data', async () => {
await testArgumentPassing({
args: ['--send-data', '--data-content=[2, 3, 4]'],
expectedAdditionalData: [2, 3, 4]
});
});
it('sends and receives mixed array data', async () => {
await testArgumentPassing({
args: ['--send-data', '--data-content=["2", true, 4]'],
expectedAdditionalData: ['2', true, 4]
});
});
it('sends and receives null data', async () => {
await testArgumentPassing({
args: ['--send-data', '--data-content=null'],
expectedAdditionalData: null
});
});
it('cannot send or receive undefined data', async () => {
try {
await testArgumentPassing({
args: ['--send-ack', '--ack-content="undefined"', '--prevent-default', '--send-data', '--data-content="undefined"'],
expectedAdditionalData: undefined
});
assert(false);
} catch {
// This is expected.
}
});
});
describe('app.relaunch', () => {
let server: net.Server | null = null;
const socketPath = process.platform === 'win32' ? '\\\\.\\pipe\\electron-app-relaunch' : '/tmp/electron-app-relaunch';
beforeEach(done => {
fs.unlink(socketPath, () => {
server = net.createServer();
server.listen(socketPath);
done();
});
});
afterEach((done) => {
server!.close(() => {
if (process.platform === 'win32') {
done();
} else {
fs.unlink(socketPath, () => done());
}
});
});
it('relaunches the app', function (done) {
this.timeout(120000);
let state = 'none';
server!.once('error', error => done(error));
server!.on('connection', client => {
client.once('data', data => {
if (String(data) === '--first' && state === 'none') {
state = 'first-launch';
} else if (String(data) === '--second' && state === 'first-launch') {
state = 'second-launch';
} else if (String(data) === '--third' && state === 'second-launch') {
done();
} else {
done(`Unexpected state: "${state}", data: "${data}"`);
}
});
});
const appPath = path.join(fixturesPath, 'api', 'relaunch');
const child = cp.spawn(process.execPath, [appPath, '--first']);
child.stdout.on('data', (c) => console.log(c.toString()));
child.stderr.on('data', (c) => console.log(c.toString()));
child.on('exit', (code, signal) => {
if (code !== 0) {
console.log(`Process exited with code "${code}" signal "${signal}"`);
}
});
});
});
ifdescribe(process.platform === 'darwin')('app.setUserActivity(type, userInfo)', () => {
it('sets the current activity', () => {
app.setUserActivity('com.electron.testActivity', { testData: '123' });
expect(app.getCurrentActivityType()).to.equal('com.electron.testActivity');
});
});
describe('certificate-error event', () => {
afterEach(closeAllWindows);
it('is emitted when visiting a server with a self-signed cert', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL(secureUrl);
await once(app, 'certificate-error');
});
describe('when denied', () => {
before(() => {
app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
callback(false);
});
});
after(() => {
app.removeAllListeners('certificate-error');
});
it('causes did-fail-load', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL(secureUrl);
await once(w.webContents, 'did-fail-load');
});
});
});
// xdescribe('app.importCertificate', () => {
// let w = null
// before(function () {
// if (process.platform !== 'linux') {
// this.skip()
// }
// })
// afterEach(() => closeWindow(w).then(() => { w = null }))
// it('can import certificate into platform cert store', done => {
// const options = {
// certificate: path.join(certPath, 'client.p12'),
// password: 'electron'
// }
// w = new BrowserWindow({
// show: false,
// webPreferences: {
// nodeIntegration: true
// }
// })
// w.webContents.on('did-finish-load', () => {
// expect(w.webContents.getTitle()).to.equal('authorized')
// done()
// })
// ipcRenderer.once('select-client-certificate', (event, webContentsId, list) => {
// expect(webContentsId).to.equal(w.webContents.id)
// expect(list).to.have.lengthOf(1)
// expect(list[0]).to.deep.equal({
// issuerName: 'Intermediate CA',
// subjectName: 'Client Cert',
// issuer: { commonName: 'Intermediate CA' },
// subject: { commonName: 'Client Cert' }
// })
// event.sender.send('client-certificate-response', list[0])
// })
// app.importCertificate(options, result => {
// expect(result).toNotExist()
// ipcRenderer.sendSync('set-client-certificate-option', false)
// w.loadURL(secureUrl)
// })
// })
// })
describe('BrowserWindow events', () => {
let w: BrowserWindow = null as any;
afterEach(() => {
closeWindow(w).then(() => { w = null as any; });
});
it('should emit browser-window-focus event when window is focused', async () => {
const emitted = once(app, 'browser-window-focus') as Promise<[any, BrowserWindow]>;
w = new BrowserWindow({ show: false });
w.emit('focus');
const [, window] = await emitted;
expect(window.id).to.equal(w.id);
});
it('should emit browser-window-blur event when window is blurred', async () => {
const emitted = once(app, 'browser-window-blur') as Promise<[any, BrowserWindow]>;
w = new BrowserWindow({ show: false });
w.emit('blur');
const [, window] = await emitted;
expect(window.id).to.equal(w.id);
});
it('should emit browser-window-created event when window is created', async () => {
const emitted = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>;
w = new BrowserWindow({ show: false });
const [, window] = await emitted;
expect(window.id).to.equal(w.id);
});
it('should emit web-contents-created event when a webContents is created', async () => {
const emitted = once(app, 'web-contents-created') as Promise<[any, WebContents]>;
w = new BrowserWindow({ show: false });
const [, webContents] = await emitted;
expect(webContents.id).to.equal(w.webContents.id);
});
// FIXME: re-enable this test on win32.
ifit(process.platform !== 'win32')('should emit renderer-process-crashed event when renderer crashes', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
await w.loadURL('about:blank');
expectDeprecationMessages(async () => {
const emitted = once(app, 'renderer-process-crashed') as Promise<[any, WebContents, boolean]>;
w.webContents.executeJavaScript('process.crash()');
const [, webContents, killed] = await emitted;
expect(webContents).to.equal(w.webContents);
expect(killed).to.be.false();
}, '\'renderer-process-crashed event\' is deprecated and will be removed. Please use \'render-process-gone event\' instead.');
});
// FIXME: re-enable this test on win32.
ifit(process.platform !== 'win32')('should emit render-process-gone event when renderer crashes', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
await w.loadURL('about:blank');
const emitted = once(app, 'render-process-gone') as Promise<[any, WebContents, Electron.RenderProcessGoneDetails]>;
w.webContents.executeJavaScript('process.crash()');
const [, webContents, details] = await emitted;
expect(webContents).to.equal(w.webContents);
expect(details.reason).to.be.oneOf(['crashed', 'abnormal-exit']);
});
});
describe('app.badgeCount', () => {
const platformIsNotSupported =
(process.platform === 'win32') ||
(process.platform === 'linux' && !app.isUnityRunning());
const expectedBadgeCount = 42;
after(() => { app.badgeCount = 0; });
ifdescribe(!platformIsNotSupported)('on supported platform', () => {
describe('with properties', () => {
it('sets a badge count', function () {
app.badgeCount = expectedBadgeCount;
expect(app.badgeCount).to.equal(expectedBadgeCount);
});
});
describe('with functions', () => {
it('sets a numerical badge count', function () {
app.setBadgeCount(expectedBadgeCount);
expect(app.getBadgeCount()).to.equal(expectedBadgeCount);
});
it('sets an non numeric (dot) badge count', function () {
app.setBadgeCount();
// Badge count should be zero when non numeric (dot) is requested
expect(app.getBadgeCount()).to.equal(0);
});
});
});
ifdescribe(process.platform !== 'win32' && platformIsNotSupported)('on unsupported platform', () => {
describe('with properties', () => {
it('does not set a badge count', function () {
app.badgeCount = 9999;
expect(app.badgeCount).to.equal(0);
});
});
describe('with functions', () => {
it('does not set a badge count)', function () {
app.setBadgeCount(9999);
expect(app.getBadgeCount()).to.equal(0);
});
});
});
});
ifdescribe(process.platform !== 'linux' && !process.mas)('app.get/setLoginItemSettings API', function () {
const updateExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe');
const processStartArgs = [
'--processStart', `"${path.basename(process.execPath)}"`,
'--process-start-args', '"--hidden"'
];
const regAddArgs = [
'ADD',
'HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run',
'/v',
'additionalEntry',
'/t',
'REG_BINARY',
'/f',
'/d'
];
beforeEach(() => {
app.setLoginItemSettings({ openAtLogin: false });
app.setLoginItemSettings({ openAtLogin: false, path: updateExe, args: processStartArgs });
app.setLoginItemSettings({ name: 'additionalEntry', openAtLogin: false });
});
afterEach(() => {
app.setLoginItemSettings({ openAtLogin: false });
app.setLoginItemSettings({ openAtLogin: false, path: updateExe, args: processStartArgs });
app.setLoginItemSettings({ name: 'additionalEntry', openAtLogin: false });
});
ifit(process.platform !== 'win32')('sets and returns the app as a login item', function () {
app.setLoginItemSettings({ openAtLogin: true });
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: true,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false
});
});
ifit(process.platform === 'win32')('sets and returns the app as a login item (windows)', function () {
app.setLoginItemSettings({ openAtLogin: true, enabled: true });
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: true,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false,
executableWillLaunchAtLogin: true,
launchItems: [{
name: 'electron.app.Electron',
path: process.execPath,
args: [],
scope: 'user',
enabled: true
}]
});
app.setLoginItemSettings({ openAtLogin: false });
app.setLoginItemSettings({ openAtLogin: true, enabled: false });
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: true,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false,
executableWillLaunchAtLogin: false,
launchItems: [{
name: 'electron.app.Electron',
path: process.execPath,
args: [],
scope: 'user',
enabled: false
}]
});
});
ifit(process.platform !== 'win32')('adds a login item that loads in hidden mode', function () {
app.setLoginItemSettings({ openAtLogin: true, openAsHidden: true });
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: true,
openAsHidden: process.platform === 'darwin' && !process.mas, // Only available on macOS
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false
});
});
ifit(process.platform === 'win32')('adds a login item that loads in hidden mode (windows)', function () {
app.setLoginItemSettings({ openAtLogin: true, openAsHidden: true });
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: true,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false,
executableWillLaunchAtLogin: true,
launchItems: [{
name: 'electron.app.Electron',
path: process.execPath,
args: [],
scope: 'user',
enabled: true
}]
});
});
it('correctly sets and unsets the LoginItem', function () {
expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
app.setLoginItemSettings({ openAtLogin: true });
expect(app.getLoginItemSettings().openAtLogin).to.equal(true);
app.setLoginItemSettings({ openAtLogin: false });
expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
});
ifit(process.platform === 'darwin')('correctly sets and unsets the LoginItem as hidden', function () {
expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
expect(app.getLoginItemSettings().openAsHidden).to.equal(false);
app.setLoginItemSettings({ openAtLogin: true, openAsHidden: true });
expect(app.getLoginItemSettings().openAtLogin).to.equal(true);
expect(app.getLoginItemSettings().openAsHidden).to.equal(true);
app.setLoginItemSettings({ openAtLogin: true, openAsHidden: false });
expect(app.getLoginItemSettings().openAtLogin).to.equal(true);
expect(app.getLoginItemSettings().openAsHidden).to.equal(false);
});
ifit(process.platform === 'win32')('allows you to pass a custom executable and arguments', function () {
app.setLoginItemSettings({ openAtLogin: true, path: updateExe, args: processStartArgs, enabled: true });
expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
const openAtLoginTrueEnabledTrue = app.getLoginItemSettings({
path: updateExe,
args: processStartArgs
});
expect(openAtLoginTrueEnabledTrue.openAtLogin).to.equal(true);
expect(openAtLoginTrueEnabledTrue.executableWillLaunchAtLogin).to.equal(true);
app.setLoginItemSettings({ openAtLogin: true, path: updateExe, args: processStartArgs, enabled: false });
const openAtLoginTrueEnabledFalse = app.getLoginItemSettings({
path: updateExe,
args: processStartArgs
});
expect(openAtLoginTrueEnabledFalse.openAtLogin).to.equal(true);
expect(openAtLoginTrueEnabledFalse.executableWillLaunchAtLogin).to.equal(false);
app.setLoginItemSettings({ openAtLogin: false, path: updateExe, args: processStartArgs, enabled: false });
const openAtLoginFalseEnabledFalse = app.getLoginItemSettings({
path: updateExe,
args: processStartArgs
});
expect(openAtLoginFalseEnabledFalse.openAtLogin).to.equal(false);
expect(openAtLoginFalseEnabledFalse.executableWillLaunchAtLogin).to.equal(false);
});
ifit(process.platform === 'win32')('allows you to pass a custom name', function () {
app.setLoginItemSettings({ openAtLogin: true });
app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: false });
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: true,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false,
executableWillLaunchAtLogin: true,
launchItems: [{
name: 'additionalEntry',
path: process.execPath,
args: [],
scope: 'user',
enabled: false
}, {
name: 'electron.app.Electron',
path: process.execPath,
args: [],
scope: 'user',
enabled: true
}]
});
app.setLoginItemSettings({ openAtLogin: false, name: 'additionalEntry' });
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: true,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false,
executableWillLaunchAtLogin: true,
launchItems: [{
name: 'electron.app.Electron',
path: process.execPath,
args: [],
scope: 'user',
enabled: true
}]
});
});
ifit(process.platform === 'win32')('finds launch items independent of args', function () {
app.setLoginItemSettings({ openAtLogin: true, args: ['arg1'] });
app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: false, args: ['arg2'] });
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: false,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false,
executableWillLaunchAtLogin: true,
launchItems: [{
name: 'additionalEntry',
path: process.execPath,
args: ['arg2'],
scope: 'user',
enabled: false
}, {
name: 'electron.app.Electron',
path: process.execPath,
args: ['arg1'],
scope: 'user',
enabled: true
}]
});
});
ifit(process.platform === 'win32')('finds launch items independent of path quotation or casing', function () {
const expectation = {
openAtLogin: false,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false,
executableWillLaunchAtLogin: true,
launchItems: [{
name: 'additionalEntry',
path: 'C:\\electron\\myapp.exe',
args: ['arg1'],
scope: 'user',
enabled: true
}]
};
app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: true, path: 'C:\\electron\\myapp.exe', args: ['arg1'] });
expect(app.getLoginItemSettings({ path: '"C:\\electron\\MYAPP.exe"' })).to.deep.equal(expectation);
app.setLoginItemSettings({ openAtLogin: false, name: 'additionalEntry' });
app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: true, path: '"C:\\electron\\MYAPP.exe"', args: ['arg1'] });
expect(app.getLoginItemSettings({ path: 'C:\\electron\\myapp.exe' })).to.deep.equal({
...expectation,
launchItems: [
{
name: 'additionalEntry',
path: 'C:\\electron\\MYAPP.exe',
args: ['arg1'],
scope: 'user',
enabled: true
}
]
});
});
ifit(process.platform === 'win32')('detects disabled by TaskManager', async function () {
app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: true, args: ['arg1'] });
const appProcess = cp.spawn('reg', [...regAddArgs, '030000000000000000000000']);
await once(appProcess, 'exit');
expect(app.getLoginItemSettings()).to.deep.equal({
openAtLogin: false,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false,
executableWillLaunchAtLogin: false,
launchItems: [{
name: 'additionalEntry',
path: process.execPath,
args: ['arg1'],
scope: 'user',
enabled: false
}]
});
});
ifit(process.platform === 'win32')('detects enabled by TaskManager', async function () {
const expectation = {
openAtLogin: false,
openAsHidden: false,
wasOpenedAtLogin: false,
wasOpenedAsHidden: false,
restoreState: false,
executableWillLaunchAtLogin: true,
launchItems: [{
name: 'additionalEntry',
path: process.execPath,
args: ['arg1'],
scope: 'user',
enabled: true
}]
};
app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: false, args: ['arg1'] });
let appProcess = cp.spawn('reg', [...regAddArgs, '020000000000000000000000']);
await once(appProcess, 'exit');
expect(app.getLoginItemSettings()).to.deep.equal(expectation);
app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: false, args: ['arg1'] });
appProcess = cp.spawn('reg', [...regAddArgs, '000000000000000000000000']);
await once(appProcess, 'exit');
expect(app.getLoginItemSettings()).to.deep.equal(expectation);
});
});
ifdescribe(process.platform !== 'linux')('accessibilitySupportEnabled property', () => {
it('with properties', () => {
it('can set accessibility support enabled', () => {
expect(app.accessibilitySupportEnabled).to.eql(false);
app.accessibilitySupportEnabled = true;
expect(app.accessibilitySupportEnabled).to.eql(true);
});
});
it('with functions', () => {
it('can set accessibility support enabled', () => {
expect(app.isAccessibilitySupportEnabled()).to.eql(false);
app.setAccessibilitySupportEnabled(true);
expect(app.isAccessibilitySupportEnabled()).to.eql(true);
});
});
});
describe('getAppPath', () => {
it('works for directories with package.json', async () => {
const { appPath } = await runTestApp('app-path');
expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path'));
});
it('works for directories with index.js', async () => {
const { appPath } = await runTestApp('app-path/lib');
expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
});
it('works for files without extension', async () => {
const { appPath } = await runTestApp('app-path/lib/index');
expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
});
it('works for files', async () => {
const { appPath } = await runTestApp('app-path/lib/index.js');
expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
});
});
describe('getPath(name)', () => {
it('returns paths that exist', () => {
const paths = [
fs.existsSync(app.getPath('exe')),
fs.existsSync(app.getPath('home')),
fs.existsSync(app.getPath('temp'))
];
expect(paths).to.deep.equal([true, true, true]);
});
it('throws an error when the name is invalid', () => {
expect(() => {
app.getPath('does-not-exist' as any);
}).to.throw(/Failed to get 'does-not-exist' path/);
});
it('returns the overridden path', () => {
app.setPath('music', __dirname);
expect(app.getPath('music')).to.equal(__dirname);
});
if (process.platform === 'win32') {
it('gets the folder for recent files', () => {
const recent = app.getPath('recent');
// We expect that one of our test machines have overridden this
// to be something crazy, it'll always include the word "Recent"
// unless people have been registry-hacking like crazy
expect(recent).to.include('Recent');
});
it('can override the recent files path', () => {
app.setPath('recent', 'C:\\fake-path');
expect(app.getPath('recent')).to.equal('C:\\fake-path');
});
}
it('uses the app name in getPath(userData)', () => {
expect(app.getPath('userData')).to.include(app.name);
});
});
describe('setPath(name, path)', () => {
it('throws when a relative path is passed', () => {
const badPath = 'hey/hi/hello';
expect(() => {
app.setPath('music', badPath);
}).to.throw(/Path must be absolute/);
});
it('does not create a new directory by default', () => {
const badPath = path.join(__dirname, 'music');
expect(fs.existsSync(badPath)).to.be.false();
app.setPath('music', badPath);
expect(fs.existsSync(badPath)).to.be.false();
expect(() => { app.getPath(badPath as any); }).to.throw();
});
describe('sessionData', () => {
const appPath = path.join(__dirname, 'fixtures', 'apps', 'set-path');
const appName = fs.readJsonSync(path.join(appPath, 'package.json')).name;
const userDataPath = path.join(app.getPath('appData'), appName);
const tempBrowserDataPath = path.join(app.getPath('temp'), appName);
const sessionFiles = [
'Preferences',
'Code Cache',
'Local Storage',
'IndexedDB',
'Service Worker'
];
const hasSessionFiles = (dir: string) => {
for (const file of sessionFiles) {
if (!fs.existsSync(path.join(dir, file))) {
return false;
}
}
return true;
};
beforeEach(() => {
fs.removeSync(userDataPath);
fs.removeSync(tempBrowserDataPath);
});
it('writes to userData by default', () => {
expect(hasSessionFiles(userDataPath)).to.equal(false);
cp.spawnSync(process.execPath, [appPath]);
expect(hasSessionFiles(userDataPath)).to.equal(true);
});
it('can be changed', () => {
expect(hasSessionFiles(userDataPath)).to.equal(false);
cp.spawnSync(process.execPath, [appPath, 'sessionData', tempBrowserDataPath]);
expect(hasSessionFiles(userDataPath)).to.equal(false);
expect(hasSessionFiles(tempBrowserDataPath)).to.equal(true);
});
it('changing userData affects default sessionData', () => {
expect(hasSessionFiles(userDataPath)).to.equal(false);
cp.spawnSync(process.execPath, [appPath, 'userData', tempBrowserDataPath]);
expect(hasSessionFiles(userDataPath)).to.equal(false);
expect(hasSessionFiles(tempBrowserDataPath)).to.equal(true);
});
});
});
describe('setAppLogsPath(path)', () => {
it('throws when a relative path is passed', () => {
const badPath = 'hey/hi/hello';
expect(() => {
app.setAppLogsPath(badPath);
}).to.throw(/Path must be absolute/);
});
});
ifdescribe(process.platform !== 'linux')('select-client-certificate event', () => {
let w: BrowserWindow;
before(function () {
session.fromPartition('empty-certificate').setCertificateVerifyProc((req, cb) => { cb(0); });
});
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'empty-certificate'
}
});
});
afterEach(() => closeWindow(w).then(() => { w = null as any; }));
after(() => session.fromPartition('empty-certificate').setCertificateVerifyProc(null));
it('can respond with empty certificate list', async () => {
app.once('select-client-certificate', function (event, webContents, url, list, callback) {
console.log('select-client-certificate emitted');
event.preventDefault();
callback();
});
await w.webContents.loadURL(secureUrl);
expect(w.webContents.getTitle()).to.equal('denied');
});
});
ifdescribe(process.platform === 'win32')('setAsDefaultProtocolClient(protocol, path, args)', () => {
const protocol = 'electron-test';
const updateExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe');
const processStartArgs = [
'--processStart', `"${path.basename(process.execPath)}"`,
'--process-start-args', '"--hidden"'
];
let Winreg: any;
let classesKey: any;
before(function () {
Winreg = require('winreg');
classesKey = new Winreg({
hive: Winreg.HKCU,
key: '\\Software\\Classes\\'
});
});
after(function (done) {
if (process.platform !== 'win32') {
done();
} else {
const protocolKey = new Winreg({
hive: Winreg.HKCU,
key: `\\Software\\Classes\\${protocol}`
});
// The last test leaves the registry dirty,
// delete the protocol key for those of us who test at home
protocolKey.destroy(() => done());
}
});
beforeEach(() => {
app.removeAsDefaultProtocolClient(protocol);
app.removeAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
});
afterEach(() => {
app.removeAsDefaultProtocolClient(protocol);
expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
app.removeAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(false);
});
it('sets the app as the default protocol client', () => {
expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
app.setAsDefaultProtocolClient(protocol);
expect(app.isDefaultProtocolClient(protocol)).to.equal(true);
});
it('allows a custom path and args to be specified', () => {
expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(false);
app.setAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(true);
expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
});
it('creates a registry entry for the protocol class', async () => {
app.setAsDefaultProtocolClient(protocol);
const keys = await promisify(classesKey.keys).call(classesKey) as any[];
const exists = keys.some(key => key.key.includes(protocol));
expect(exists).to.equal(true);
});
it('completely removes a registry entry for the protocol class', async () => {
app.setAsDefaultProtocolClient(protocol);
app.removeAsDefaultProtocolClient(protocol);
const keys = await promisify(classesKey.keys).call(classesKey) as any[];
const exists = keys.some(key => key.key.includes(protocol));
expect(exists).to.equal(false);
});
it('only unsets a class registry key if it contains other data', async () => {
app.setAsDefaultProtocolClient(protocol);
const protocolKey = new Winreg({
hive: Winreg.HKCU,
key: `\\Software\\Classes\\${protocol}`
});
await promisify(protocolKey.set).call(protocolKey, 'test-value', 'REG_BINARY', '123');
app.removeAsDefaultProtocolClient(protocol);
const keys = await promisify(classesKey.keys).call(classesKey) as any[];
const exists = keys.some(key => key.key.includes(protocol));
expect(exists).to.equal(true);
});
it('sets the default client such that getApplicationNameForProtocol returns Electron', () => {
app.setAsDefaultProtocolClient(protocol);
expect(app.getApplicationNameForProtocol(`${protocol}://`)).to.equal('Electron');
});
});
describe('getApplicationNameForProtocol()', () => {
// TODO: Linux CI doesn't have registered http & https handlers
ifit(!(process.env.CI && process.platform === 'linux'))('returns application names for common protocols', function () {
// We can't expect particular app names here, but these protocols should
// at least have _something_ registered. Except on our Linux CI
// environment apparently.
const protocols = [
'http://',
'https://'
];
for (const protocol of protocols) {
expect(app.getApplicationNameForProtocol(protocol)).to.not.equal('');
}
});
it('returns an empty string for a bogus protocol', () => {
expect(app.getApplicationNameForProtocol('bogus-protocol://')).to.equal('');
});
});
ifdescribe(process.platform !== 'linux')('getApplicationInfoForProtocol()', () => {
it('returns promise rejection for a bogus protocol', async function () {
await expect(
app.getApplicationInfoForProtocol('bogus-protocol://')
).to.eventually.be.rejectedWith(
'Unable to retrieve installation path to app'
);
});
it('returns resolved promise with appPath, displayName and icon', async function () {
const appInfo = await app.getApplicationInfoForProtocol('https://');
expect(appInfo.path).not.to.be.undefined();
expect(appInfo.name).not.to.be.undefined();
expect(appInfo.icon).not.to.be.undefined();
});
});
describe('isDefaultProtocolClient()', () => {
it('returns false for a bogus protocol', () => {
expect(app.isDefaultProtocolClient('bogus-protocol://')).to.equal(false);
});
});
ifdescribe(process.platform === 'win32')('app launch through uri', () => {
it('does not launch for argument following a URL', async () => {
const appPath = path.join(fixturesPath, 'api', 'quit-app');
// App should exit with non 123 code.
const first = cp.spawn(process.execPath, [appPath, 'electron-test:?', 'abc']);
const [code] = await once(first, 'exit');
expect(code).to.not.equal(123);
});
it('launches successfully for argument following a file path', async () => {
const appPath = path.join(fixturesPath, 'api', 'quit-app');
// App should exit with code 123.
const first = cp.spawn(process.execPath, [appPath, 'e:\\abc', 'abc']);
const [code] = await once(first, 'exit');
expect(code).to.equal(123);
});
it('launches successfully for multiple URIs following --', async () => {
const appPath = path.join(fixturesPath, 'api', 'quit-app');
// App should exit with code 123.
const first = cp.spawn(process.execPath, [appPath, '--', 'http://electronjs.org', 'electron-test://testdata']);
const [code] = await once(first, 'exit');
expect(code).to.equal(123);
});
});
// FIXME Get these specs running on Linux CI
ifdescribe(process.platform !== 'linux')('getFileIcon() API', () => {
const iconPath = path.join(__dirname, 'fixtures/assets/icon.ico');
const sizes = {
small: 16,
normal: 32,
large: process.platform === 'win32' ? 32 : 48
};
it('fetches a non-empty icon', async () => {
const icon = await app.getFileIcon(iconPath);
expect(icon.isEmpty()).to.equal(false);
});
it('fetches normal icon size by default', async () => {
const icon = await app.getFileIcon(iconPath);
const size = icon.getSize();
expect(size.height).to.equal(sizes.normal);
expect(size.width).to.equal(sizes.normal);
});
describe('size option', () => {
it('fetches a small icon', async () => {
const icon = await app.getFileIcon(iconPath, { size: 'small' });
const size = icon.getSize();
expect(size.height).to.equal(sizes.small);
expect(size.width).to.equal(sizes.small);
});
it('fetches a normal icon', async () => {
const icon = await app.getFileIcon(iconPath, { size: 'normal' });
const size = icon.getSize();
expect(size.height).to.equal(sizes.normal);
expect(size.width).to.equal(sizes.normal);
});
it('fetches a large icon', async () => {
// macOS does not support large icons
if (process.platform === 'darwin') return;
const icon = await app.getFileIcon(iconPath, { size: 'large' });
const size = icon.getSize();
expect(size.height).to.equal(sizes.large);
expect(size.width).to.equal(sizes.large);
});
});
});
describe('getAppMetrics() API', () => {
it('returns memory and cpu stats of all running electron processes', () => {
const appMetrics = app.getAppMetrics();
expect(appMetrics).to.be.an('array').and.have.lengthOf.at.least(1, 'App memory info object is not > 0');
const types = [];
for (const entry of appMetrics) {
expect(entry.pid).to.be.above(0, 'pid is not > 0');
expect(entry.type).to.be.a('string').that.does.not.equal('');
expect(entry.creationTime).to.be.a('number').that.is.greaterThan(0);
types.push(entry.type);
expect(entry.cpu).to.have.ownProperty('percentCPUUsage').that.is.a('number');
expect(entry.cpu).to.have.ownProperty('idleWakeupsPerSecond').that.is.a('number');
expect(entry.memory).to.have.property('workingSetSize').that.is.greaterThan(0);
expect(entry.memory).to.have.property('peakWorkingSetSize').that.is.greaterThan(0);
if (entry.type === 'Utility' || entry.type === 'GPU') {
expect(entry.serviceName).to.be.a('string').that.does.not.equal('');
}
if (entry.type === 'Utility') {
expect(entry).to.have.property('name').that.is.a('string');
}
if (process.platform === 'win32') {
expect(entry.memory).to.have.property('privateBytes').that.is.greaterThan(0);
}
if (process.platform !== 'linux') {
expect(entry.sandboxed).to.be.a('boolean');
}
if (process.platform === 'win32') {
expect(entry.integrityLevel).to.be.a('string');
}
}
if (process.platform === 'darwin') {
expect(types).to.include('GPU');
}
expect(types).to.include('Browser');
});
});
describe('getGPUFeatureStatus() API', () => {
it('returns the graphic features statuses', () => {
const features = app.getGPUFeatureStatus();
expect(features).to.have.ownProperty('webgl').that.is.a('string');
expect(features).to.have.ownProperty('gpu_compositing').that.is.a('string');
});
});
// FIXME https://github.com/electron/electron/issues/24224
ifdescribe(process.platform !== 'linux')('getGPUInfo() API', () => {
const appPath = path.join(fixturesPath, 'api', 'gpu-info.js');
const getGPUInfo = async (type: string) => {
const appProcess = cp.spawn(process.execPath, [appPath, type]);
let gpuInfoData = '';
let errorData = '';
appProcess.stdout.on('data', (data) => {
gpuInfoData += data;
});
appProcess.stderr.on('data', (data) => {
errorData += data;
});
const [exitCode] = await once(appProcess, 'exit');
if (exitCode === 0) {
try {
const [, json] = /HERE COMES THE JSON: (.+) AND THERE IT WAS/.exec(gpuInfoData)!;
// return info data on successful exit
return JSON.parse(json);
} catch (e) {
console.error('Failed to interpret the following as JSON:');
console.error(gpuInfoData);
throw e;
}
} else {
// return error if not clean exit
throw new Error(errorData);
}
};
const verifyBasicGPUInfo = async (gpuInfo: any) => {
// Devices information is always present in the available info.
expect(gpuInfo).to.have.ownProperty('gpuDevice')
.that.is.an('array')
.and.does.not.equal([]);
const device = gpuInfo.gpuDevice[0];
expect(device).to.be.an('object')
.and.to.have.property('deviceId')
.that.is.a('number')
.not.lessThan(0);
};
it('succeeds with basic GPUInfo', async () => {
const gpuInfo = await getGPUInfo('basic');
await verifyBasicGPUInfo(gpuInfo);
});
it('succeeds with complete GPUInfo', async () => {
const completeInfo = await getGPUInfo('complete');
if (process.platform === 'linux') {
// For linux and macOS complete info is same as basic info
await verifyBasicGPUInfo(completeInfo);
const basicInfo = await getGPUInfo('basic');
expect(completeInfo).to.deep.equal(basicInfo);
} else {
// Gl version is present in the complete info.
expect(completeInfo).to.have.ownProperty('auxAttributes')
.that.is.an('object');
if (completeInfo.gpuDevice.active) {
expect(completeInfo.auxAttributes).to.have.ownProperty('glVersion')
.that.is.a('string')
.and.does.not.equal([]);
}
}
});
it('fails for invalid info_type', () => {
const invalidType = 'invalid';
const expectedErrorMessage = "Invalid info type. Use 'basic' or 'complete'";
return expect(app.getGPUInfo(invalidType as any)).to.eventually.be.rejectedWith(expectedErrorMessage);
});
});
ifdescribe(!(process.platform === 'linux' && (process.arch === 'arm64' || process.arch === 'arm')))('sandbox options', () => {
// Our ARM tests are run on VSTS rather than CircleCI, and the Docker
// setup on VSTS disallows syscalls that Chrome requires for setting up
// sandboxing.
// See:
// - https://docs.docker.com/engine/security/seccomp/#significant-syscalls-blocked-by-the-default-profile
// - https://chromium.googlesource.com/chromium/src/+/70.0.3538.124/sandbox/linux/services/credentials.cc#292
// - https://github.com/docker/docker-ce/blob/ba7dfc59ccfe97c79ee0d1379894b35417b40bca/components/engine/profiles/seccomp/seccomp_default.go#L497
// - https://blog.jessfraz.com/post/how-to-use-new-docker-seccomp-profiles/
//
// Adding `--cap-add SYS_ADMIN` or `--security-opt seccomp=unconfined`
// to the Docker invocation allows the syscalls that Chrome needs, but
// are probably more permissive than we'd like.
let appProcess: cp.ChildProcess = null as any;
let server: net.Server = null as any;
const socketPath = process.platform === 'win32' ? '\\\\.\\pipe\\electron-mixed-sandbox' : '/tmp/electron-mixed-sandbox';
beforeEach(function (done) {
fs.unlink(socketPath, () => {
server = net.createServer();
server.listen(socketPath);
done();
});
});
afterEach(done => {
if (appProcess != null) appProcess.kill();
if (server) {
server.close(() => {
if (process.platform === 'win32') {
done();
} else {
fs.unlink(socketPath, () => done());
}
});
} else {
done();
}
});
describe('when app.enableSandbox() is called', () => {
it('adds --enable-sandbox to all renderer processes', done => {
const appPath = path.join(fixturesPath, 'api', 'mixed-sandbox-app');
appProcess = cp.spawn(process.execPath, [appPath, '--app-enable-sandbox'], { stdio: 'inherit' });
server.once('error', error => { done(error); });
server.on('connection', client => {
client.once('data', (data) => {
const argv = JSON.parse(data.toString());
expect(argv.sandbox).to.include('--enable-sandbox');
expect(argv.sandbox).to.not.include('--no-sandbox');
expect(argv.noSandbox).to.include('--enable-sandbox');
expect(argv.noSandbox).to.not.include('--no-sandbox');
expect(argv.noSandboxDevtools).to.equal(true);
expect(argv.sandboxDevtools).to.equal(true);
done();
});
});
});
});
describe('when the app is launched with --enable-sandbox', () => {
it('adds --enable-sandbox to all renderer processes', done => {
const appPath = path.join(fixturesPath, 'api', 'mixed-sandbox-app');
appProcess = cp.spawn(process.execPath, [appPath, '--enable-sandbox'], { stdio: 'inherit' });
server.once('error', error => { done(error); });
server.on('connection', client => {
client.once('data', data => {
const argv = JSON.parse(data.toString());
expect(argv.sandbox).to.include('--enable-sandbox');
expect(argv.sandbox).to.not.include('--no-sandbox');
expect(argv.noSandbox).to.include('--enable-sandbox');
expect(argv.noSandbox).to.not.include('--no-sandbox');
expect(argv.noSandboxDevtools).to.equal(true);
expect(argv.sandboxDevtools).to.equal(true);
done();
});
});
});
});
});
describe('disableDomainBlockingFor3DAPIs() API', () => {
it('throws when called after app is ready', () => {
expect(() => {
app.disableDomainBlockingFor3DAPIs();
}).to.throw(/before app is ready/);
});
});
ifdescribe(process.platform === 'darwin')('app hide and show API', () => {
describe('app.isHidden', () => {
it('returns true when the app is hidden', async () => {
app.hide();
await expect(
waitUntil(() => app.isHidden())
).to.eventually.be.fulfilled();
});
it('returns false when the app is shown', async () => {
app.show();
await expect(
waitUntil(() => !app.isHidden())
).to.eventually.be.fulfilled();
});
});
});
ifdescribe(process.platform === 'darwin')('dock APIs', () => {
after(async () => {
await app.dock.show();
});
describe('dock.setMenu', () => {
it('can be retrieved via dock.getMenu', () => {
expect(app.dock.getMenu()).to.equal(null);
const menu = new Menu();
app.dock.setMenu(menu);
expect(app.dock.getMenu()).to.equal(menu);
});
it('keeps references to the menu', () => {
app.dock.setMenu(new Menu());
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
});
});
describe('dock.setIcon', () => {
it('throws a descriptive error for a bad icon path', () => {
const badPath = path.resolve('I', 'Do', 'Not', 'Exist');
expect(() => {
app.dock.setIcon(badPath);
}).to.throw(/Failed to load image from path (.+)/);
});
});
describe('dock.bounce', () => {
it('should return -1 for unknown bounce type', () => {
expect(app.dock.bounce('bad type' as any)).to.equal(-1);
});
it('should return a positive number for informational type', () => {
const appHasFocus = !!BrowserWindow.getFocusedWindow();
if (!appHasFocus) {
expect(app.dock.bounce('informational')).to.be.at.least(0);
}
});
it('should return a positive number for critical type', () => {
const appHasFocus = !!BrowserWindow.getFocusedWindow();
if (!appHasFocus) {
expect(app.dock.bounce('critical')).to.be.at.least(0);
}
});
});
describe('dock.cancelBounce', () => {
it('should not throw', () => {
app.dock.cancelBounce(app.dock.bounce('critical'));
});
});
describe('dock.setBadge', () => {
after(() => {
app.dock.setBadge('');
});
it('should not throw', () => {
app.dock.setBadge('1');
});
it('should be retrievable via getBadge', () => {
app.dock.setBadge('test');
expect(app.dock.getBadge()).to.equal('test');
});
});
describe('dock.hide', () => {
it('should not throw', () => {
app.dock.hide();
expect(app.dock.isVisible()).to.equal(false);
});
});
// Note that dock.show tests should run after dock.hide tests, to work
// around a bug of macOS.
// See https://github.com/electron/electron/pull/25269 for more.
describe('dock.show', () => {
it('should not throw', () => {
return app.dock.show().then(() => {
expect(app.dock.isVisible()).to.equal(true);
});
});
it('returns a Promise', () => {
expect(app.dock.show()).to.be.a('promise');
});
it('eventually fulfills', async () => {
await expect(app.dock.show()).to.eventually.be.fulfilled.equal(undefined);
});
});
});
describe('whenReady', () => {
it('returns a Promise', () => {
expect(app.whenReady()).to.be.a('promise');
});
it('becomes fulfilled if the app is already ready', async () => {
expect(app.isReady()).to.equal(true);
await expect(app.whenReady()).to.be.eventually.fulfilled.equal(undefined);
});
});
describe('app.applicationMenu', () => {
it('has the applicationMenu property', () => {
expect(app).to.have.property('applicationMenu');
});
});
describe('commandLine.hasSwitch', () => {
it('returns true when present', () => {
app.commandLine.appendSwitch('foobar1');
expect(app.commandLine.hasSwitch('foobar1')).to.equal(true);
});
it('returns false when not present', () => {
expect(app.commandLine.hasSwitch('foobar2')).to.equal(false);
});
});
describe('commandLine.hasSwitch (existing argv)', () => {
it('returns true when present', async () => {
const { hasSwitch } = await runTestApp('command-line', '--foobar');
expect(hasSwitch).to.equal(true);
});
it('returns false when not present', async () => {
const { hasSwitch } = await runTestApp('command-line');
expect(hasSwitch).to.equal(false);
});
});
describe('commandLine.getSwitchValue', () => {
it('returns the value when present', () => {
app.commandLine.appendSwitch('foobar', 'æøΓ₯ΓΌ');
expect(app.commandLine.getSwitchValue('foobar')).to.equal('æøΓ₯ΓΌ');
});
it('returns an empty string when present without value', () => {
app.commandLine.appendSwitch('foobar1');
expect(app.commandLine.getSwitchValue('foobar1')).to.equal('');
});
it('returns an empty string when not present', () => {
expect(app.commandLine.getSwitchValue('foobar2')).to.equal('');
});
});
describe('commandLine.getSwitchValue (existing argv)', () => {
it('returns the value when present', async () => {
const { getSwitchValue } = await runTestApp('command-line', '--foobar=test');
expect(getSwitchValue).to.equal('test');
});
it('returns an empty string when present without value', async () => {
const { getSwitchValue } = await runTestApp('command-line', '--foobar');
expect(getSwitchValue).to.equal('');
});
it('returns an empty string when not present', async () => {
const { getSwitchValue } = await runTestApp('command-line');
expect(getSwitchValue).to.equal('');
});
});
describe('commandLine.removeSwitch', () => {
it('no-ops a non-existent switch', async () => {
expect(app.commandLine.hasSwitch('foobar3')).to.equal(false);
app.commandLine.removeSwitch('foobar3');
expect(app.commandLine.hasSwitch('foobar3')).to.equal(false);
});
it('removes an existing switch', async () => {
app.commandLine.appendSwitch('foobar3', 'test');
expect(app.commandLine.hasSwitch('foobar3')).to.equal(true);
app.commandLine.removeSwitch('foobar3');
expect(app.commandLine.hasSwitch('foobar3')).to.equal(false);
});
});
ifdescribe(process.platform === 'darwin')('app.setSecureKeyboardEntryEnabled', () => {
it('changes Secure Keyboard Entry is enabled', () => {
app.setSecureKeyboardEntryEnabled(true);
expect(app.isSecureKeyboardEntryEnabled()).to.equal(true);
app.setSecureKeyboardEntryEnabled(false);
expect(app.isSecureKeyboardEntryEnabled()).to.equal(false);
});
});
describe('configureHostResolver', () => {
after(() => {
// Returns to the default configuration.
app.configureHostResolver({});
});
it('fails on bad arguments', () => {
expect(() => {
(app.configureHostResolver as any)();
}).to.throw();
expect(() => {
app.configureHostResolver({
secureDnsMode: 'notAValidValue' as any
});
}).to.throw();
expect(() => {
app.configureHostResolver({
secureDnsServers: [123 as any]
});
}).to.throw();
});
it('affects dns lookup behavior', async () => {
// 1. resolve a domain name to check that things are working
await expect(new Promise((resolve, reject) => {
electronNet.request({
method: 'HEAD',
url: 'https://www.electronjs.org'
}).on('response', resolve)
.on('error', reject)
.end();
})).to.eventually.be.fulfilled();
// 2. change the host resolver configuration to something that will
// always fail
app.configureHostResolver({
secureDnsMode: 'secure',
secureDnsServers: ['https://127.0.0.1:1234']
});
// 3. check that resolving domain names now fails
await expect(new Promise((resolve, reject) => {
electronNet.request({
method: 'HEAD',
// Needs to be a slightly different domain to above, otherwise the
// response will come from the cache.
url: 'https://electronjs.org'
}).on('response', resolve)
.on('error', reject)
.end();
})).to.eventually.be.rejectedWith(/ERR_NAME_NOT_RESOLVED/);
});
});
describe('about panel', () => {
it('app.setAboutPanelOptions() does not crash', () => {
app.setAboutPanelOptions({
applicationName: 'electron!!',
version: '1.2.3'
});
});
it('app.showAboutPanel() does not crash & runs asynchronously', () => {
app.showAboutPanel();
});
});
});
describe('default behavior', () => {
describe('application menu', () => {
it('creates the default menu if the app does not set it', async () => {
const result = await runTestApp('default-menu');
expect(result).to.equal(false);
});
it('does not create the default menu if the app sets a custom menu', async () => {
const result = await runTestApp('default-menu', '--custom-menu');
expect(result).to.equal(true);
});
it('does not create the default menu if the app sets a null menu', async () => {
const result = await runTestApp('default-menu', '--null-menu');
expect(result).to.equal(true);
});
});
describe('window-all-closed', () => {
afterEach(closeAllWindows);
it('quits when the app does not handle the event', async () => {
const result = await runTestApp('window-all-closed');
expect(result).to.equal(false);
});
it('does not quit when the app handles the event', async () => {
const result = await runTestApp('window-all-closed', '--handle-event');
expect(result).to.equal(true);
});
it('should omit closed windows from getAllWindows', async () => {
const w = new BrowserWindow({ show: false });
const len = new Promise(resolve => {
app.on('window-all-closed', () => {
resolve(BrowserWindow.getAllWindows().length);
});
});
w.close();
expect(await len).to.equal(0);
});
});
describe('user agent fallback', () => {
let initialValue: string;
before(() => {
initialValue = app.userAgentFallback!;
});
it('should have a reasonable default', () => {
expect(initialValue).to.include(`Electron/${process.versions.electron}`);
expect(initialValue).to.include(`Chrome/${process.versions.chrome}`);
});
it('should be overridable', () => {
app.userAgentFallback = 'test-agent/123';
expect(app.userAgentFallback).to.equal('test-agent/123');
});
it('should be restorable', () => {
app.userAgentFallback = 'test-agent/123';
app.userAgentFallback = '';
expect(app.userAgentFallback).to.equal(initialValue);
});
});
describe('login event', () => {
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((request, response) => {
if (request.headers.authorization) {
return response.end('ok');
}
response
.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' })
.end();
});
serverUrl = (await listen(server)).url;
});
it('should emit a login event on app when a WebContents hits a 401', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL(serverUrl);
const [, webContents] = await once(app, 'login') as [any, WebContents];
expect(webContents).to.equal(w.webContents);
});
});
describe('running under ARM64 translation', () => {
it('does not throw an error', () => {
if (process.platform === 'darwin' || process.platform === 'win32') {
expect(app.runningUnderARM64Translation).not.to.be.undefined();
expect(() => {
return app.runningUnderARM64Translation;
}).not.to.throw();
} else {
expect(app.runningUnderARM64Translation).to.be.undefined();
}
});
});
});
async function runTestApp (name: string, ...args: any[]) {
const appPath = path.join(fixturesPath, 'api', name);
const electronPath = process.execPath;
const appProcess = cp.spawn(electronPath, [appPath, ...args]);
let output = '';
appProcess.stdout.on('data', (data) => { output += data; });
await once(appProcess.stdout, 'end');
return JSON.parse(output);
}
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,211 |
[Bug]: Electron 28 breaks `import` of transitive dependencies inside ES modules
|
### 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
28.0.0-alpha.2
### What operating system are you using?
Windows
### Operating System Version
Windows 10
### What arch are you using?
x64
### Last Known Working Electron version
27.0.0
### Expected Behavior
Importing an ESM dependency which imports some other dependency (ESM or CJS) should work from inside `app.asar`
### Actual Behavior
The module lookup starts at ```node_modules/<directory where the dependency's `main` file lives>/node_modules```, doesn't find the transitive dependency there and then crashes, never reaching the top-level `node_modules` which is where the transitive dependency actually lives:

### Testcase Gist URL
_No response_
### Additional Information
I've run into this using [this repro](https://github.com/electron/asar/issues/249#issuecomment-1434998313), where the ESM dependency `got` is imported causing the app to crash when looking for the transitive ESM dependency `@sindresorhus/is`. I've put together a minimal reproduction with two local dependencies, which should make it easier to test different variables: https://github.com/erikian/esm-asar-demo
Note that this problem seems to be limited to dependencies inside `node_modules`, i.e. ESM imports across project files work fine:
```ts
// src/main.mjs
import printStuff from './printStuff.js'
printStuff('it works!')
// src/printStuff.js
import logger from './logger.js'
export default function printStuff(...stuff) {
logger(...stuff)
}
// src/logger.js
export default function logger(...args) {
console.log(...args)
}
```
Some findings:
- `const { default: printStuff } = await import('my-esm-dependency')` doesn't work out of the box, but it does work when setting `process.noAsar = true` before importing. Moving the import into the `app.whenReady` callback also doesn't work
- `import printStuff from 'my-esm-dependency'` doesn't work at all, not even with `process.noAsar = true`
- This is not limited to ESM entrypoints. I also get the same errors on the `commonjs-entrypoint` branch, and changing to Electron 27.0.0 fixes the problem.
|
https://github.com/electron/electron/issues/40211
|
https://github.com/electron/electron/pull/40221
|
f7b1c75c72a8dcab4157408f92bd3771606d8029
|
b6ec19a582579c8f7972a1c140b9404e8b2ccd87
| 2023-10-16T01:14:29Z |
c++
| 2023-10-16T16:35:25Z |
lib/asar/fs-wrapper.ts
|
import { Buffer } from 'buffer';
import { constants } from 'fs';
import * as path from 'path';
import * as util from 'util';
import type * as Crypto from 'crypto';
const asar = process._linkedBinding('electron_common_asar');
const Module = require('module') as NodeJS.ModuleInternal;
const Promise: PromiseConstructor = global.Promise;
const envNoAsar = process.env.ELECTRON_NO_ASAR &&
process.type !== 'browser' &&
process.type !== 'renderer';
const isAsarDisabled = () => process.noAsar || envNoAsar;
const internalBinding = process.internalBinding!;
delete process.internalBinding;
const nextTick = (functionToCall: Function, args: any[] = []) => {
process.nextTick(() => functionToCall(...args));
};
// Cache asar archive objects.
const cachedArchives = new Map<string, NodeJS.AsarArchive>();
const getOrCreateArchive = (archivePath: string) => {
const isCached = cachedArchives.has(archivePath);
if (isCached) {
return cachedArchives.get(archivePath)!;
}
try {
const newArchive = new asar.Archive(archivePath);
cachedArchives.set(archivePath, newArchive);
return newArchive;
} catch {
return null;
}
};
process._getOrCreateArchive = getOrCreateArchive;
const asarRe = /\.asar/i;
const { getValidatedPath } = __non_webpack_require__('internal/fs/utils');
// In the renderer node internals use the node global URL but we do not set that to be
// the global URL instance. We need to do instanceof checks against the internal URL impl
const { URL: NodeURL } = __non_webpack_require__('internal/url');
// Separate asar package's path from full path.
const splitPath = (archivePathOrBuffer: string | Buffer | URL) => {
// Shortcut for disabled asar.
if (isAsarDisabled()) return { isAsar: <const>false };
// Check for a bad argument type.
let archivePath = archivePathOrBuffer;
if (Buffer.isBuffer(archivePathOrBuffer)) {
archivePath = archivePathOrBuffer.toString();
}
if (archivePath instanceof NodeURL) {
archivePath = getValidatedPath(archivePath);
}
if (typeof archivePath !== 'string') return { isAsar: <const>false };
if (!asarRe.test(archivePath)) return { isAsar: <const>false };
return asar.splitPath(path.normalize(archivePath));
};
// Convert asar archive's Stats object to fs's Stats object.
let nextInode = 0;
const uid = process.getuid?.() ?? 0;
const gid = process.getgid?.() ?? 0;
const fakeTime = new Date();
enum AsarFileType {
kFile = (constants as any).UV_DIRENT_FILE,
kDirectory = (constants as any).UV_DIRENT_DIR,
kLink = (constants as any).UV_DIRENT_LINK,
}
const fileTypeToMode = new Map<AsarFileType, number>([
[AsarFileType.kFile, constants.S_IFREG],
[AsarFileType.kDirectory, constants.S_IFDIR],
[AsarFileType.kLink, constants.S_IFLNK]
]);
const asarStatsToFsStats = function (stats: NodeJS.AsarFileStat) {
const { Stats } = require('fs');
const mode = constants.S_IROTH | constants.S_IRGRP | constants.S_IRUSR | constants.S_IWUSR | fileTypeToMode.get(stats.type)!;
return new Stats(
1, // dev
mode, // mode
1, // nlink
uid,
gid,
0, // rdev
undefined, // blksize
++nextInode, // ino
stats.size,
undefined, // blocks,
fakeTime.getTime(), // atim_msec
fakeTime.getTime(), // mtim_msec
fakeTime.getTime(), // ctim_msec
fakeTime.getTime() // birthtim_msec
);
};
const enum AsarError {
NOT_FOUND = 'NOT_FOUND',
NOT_DIR = 'NOT_DIR',
NO_ACCESS = 'NO_ACCESS',
INVALID_ARCHIVE = 'INVALID_ARCHIVE'
}
type AsarErrorObject = Error & { code?: string, errno?: number };
const createError = (errorType: AsarError, { asarPath, filePath }: { asarPath?: string, filePath?: string } = {}) => {
let error: AsarErrorObject;
switch (errorType) {
case AsarError.NOT_FOUND:
error = new Error(`ENOENT, ${filePath} not found in ${asarPath}`);
error.code = 'ENOENT';
error.errno = -2;
break;
case AsarError.NOT_DIR:
error = new Error('ENOTDIR, not a directory');
error.code = 'ENOTDIR';
error.errno = -20;
break;
case AsarError.NO_ACCESS:
error = new Error(`EACCES: permission denied, access '${filePath}'`);
error.code = 'EACCES';
error.errno = -13;
break;
case AsarError.INVALID_ARCHIVE:
error = new Error(`Invalid package ${asarPath}`);
break;
default:
throw new Error(`Invalid error type "${errorType}" passed to createError.`);
}
return error;
};
const overrideAPISync = function (module: Record<string, any>, name: string, pathArgumentIndex?: number | null, fromAsync: boolean = false) {
if (pathArgumentIndex == null) pathArgumentIndex = 0;
const old = module[name];
const func = function (this: any, ...args: any[]) {
const pathArgument = args[pathArgumentIndex!];
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return old.apply(this, args);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
const newPath = archive.copyFileOut(filePath);
if (!newPath) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
args[pathArgumentIndex!] = newPath;
return old.apply(this, args);
};
if (fromAsync) {
return func;
}
module[name] = func;
};
const overrideAPI = function (module: Record<string, any>, name: string, pathArgumentIndex?: number | null) {
if (pathArgumentIndex == null) pathArgumentIndex = 0;
const old = module[name];
module[name] = function (this: any, ...args: any[]) {
const pathArgument = args[pathArgumentIndex!];
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return old.apply(this, args);
const { asarPath, filePath } = pathInfo;
const callback = args[args.length - 1];
if (typeof callback !== 'function') {
return overrideAPISync(module, name, pathArgumentIndex!, true)!.apply(this, args);
}
const archive = getOrCreateArchive(asarPath);
if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
nextTick(callback, [error]);
return;
}
const newPath = archive.copyFileOut(filePath);
if (!newPath) {
const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
nextTick(callback, [error]);
return;
}
args[pathArgumentIndex!] = newPath;
return old.apply(this, args);
};
if (old[util.promisify.custom]) {
module[name][util.promisify.custom] = makePromiseFunction(old[util.promisify.custom], pathArgumentIndex);
}
if (module.promises && module.promises[name]) {
module.promises[name] = makePromiseFunction(module.promises[name], pathArgumentIndex);
}
};
let crypto: typeof Crypto;
function validateBufferIntegrity (buffer: Buffer, integrity: NodeJS.AsarFileInfo['integrity']) {
if (!integrity) return;
// Delay load crypto to improve app boot performance
// when integrity protection is not enabled
crypto = crypto || require('crypto');
const actual = crypto.createHash(integrity.algorithm).update(buffer).digest('hex');
if (actual !== integrity.hash) {
console.error(`ASAR Integrity Violation: got a hash mismatch (${actual} vs ${integrity.hash})`);
process.exit(1);
}
}
const makePromiseFunction = function (orig: Function, pathArgumentIndex: number) {
return function (this: any, ...args: any[]) {
const pathArgument = args[pathArgumentIndex];
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return orig.apply(this, args);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) {
return Promise.reject(createError(AsarError.INVALID_ARCHIVE, { asarPath }));
}
const newPath = archive.copyFileOut(filePath);
if (!newPath) {
return Promise.reject(createError(AsarError.NOT_FOUND, { asarPath, filePath }));
}
args[pathArgumentIndex] = newPath;
return orig.apply(this, args);
};
};
// Override fs APIs.
export const wrapFsWithAsar = (fs: Record<string, any>) => {
const logFDs = new Map<string, number>();
const logASARAccess = (asarPath: string, filePath: string, offset: number) => {
if (!process.env.ELECTRON_LOG_ASAR_READS) return;
if (!logFDs.has(asarPath)) {
const logFilename = `${path.basename(asarPath, '.asar')}-access-log.txt`;
const logPath = path.join(require('os').tmpdir(), logFilename);
logFDs.set(asarPath, fs.openSync(logPath, 'a'));
}
fs.writeSync(logFDs.get(asarPath), `${offset}: ${filePath}\n`);
};
const { lstatSync } = fs;
fs.lstatSync = (pathArgument: string, options: any) => {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return lstatSync(pathArgument, options);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
const stats = archive.stat(filePath);
if (!stats) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
return asarStatsToFsStats(stats);
};
const { lstat } = fs;
fs.lstat = (pathArgument: string, options: any, callback: any) => {
const pathInfo = splitPath(pathArgument);
if (typeof options === 'function') {
callback = options;
options = {};
}
if (!pathInfo.isAsar) return lstat(pathArgument, options, callback);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
nextTick(callback, [error]);
return;
}
const stats = archive.stat(filePath);
if (!stats) {
const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
nextTick(callback, [error]);
return;
}
const fsStats = asarStatsToFsStats(stats);
nextTick(callback, [null, fsStats]);
};
fs.promises.lstat = util.promisify(fs.lstat);
const { statSync } = fs;
fs.statSync = (pathArgument: string, options: any) => {
const { isAsar } = splitPath(pathArgument);
if (!isAsar) return statSync(pathArgument, options);
// Do not distinguish links for now.
return fs.lstatSync(pathArgument, options);
};
const { stat } = fs;
fs.stat = (pathArgument: string, options: any, callback: any) => {
const { isAsar } = splitPath(pathArgument);
if (typeof options === 'function') {
callback = options;
options = {};
}
if (!isAsar) return stat(pathArgument, options, callback);
// Do not distinguish links for now.
process.nextTick(() => fs.lstat(pathArgument, options, callback));
};
fs.promises.stat = util.promisify(fs.stat);
const wrapRealpathSync = function (realpathSync: Function) {
return function (this: any, pathArgument: string, options: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return realpathSync.apply(this, arguments);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) {
throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
}
const fileRealPath = archive.realpath(filePath);
if (fileRealPath === false) {
throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
}
return path.join(realpathSync(asarPath, options), fileRealPath);
};
};
const { realpathSync } = fs;
fs.realpathSync = wrapRealpathSync(realpathSync);
fs.realpathSync.native = wrapRealpathSync(realpathSync.native);
const wrapRealpath = function (realpath: Function) {
return function (this: any, pathArgument: string, options: any, callback: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return realpath.apply(this, arguments);
const { asarPath, filePath } = pathInfo;
if (arguments.length < 3) {
callback = options;
options = {};
}
const archive = getOrCreateArchive(asarPath);
if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
nextTick(callback, [error]);
return;
}
const fileRealPath = archive.realpath(filePath);
if (fileRealPath === false) {
const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
nextTick(callback, [error]);
return;
}
realpath(asarPath, options, (error: Error | null, archiveRealPath: string) => {
if (error === null) {
const fullPath = path.join(archiveRealPath, fileRealPath);
callback(null, fullPath);
} else {
callback(error);
}
});
};
};
const { realpath } = fs;
fs.realpath = wrapRealpath(realpath);
fs.realpath.native = wrapRealpath(realpath.native);
fs.promises.realpath = util.promisify(fs.realpath.native);
const { exists: nativeExists } = fs;
fs.exists = function exists (pathArgument: string, callback: any) {
let pathInfo: ReturnType<typeof splitPath>;
try {
pathInfo = splitPath(pathArgument);
} catch {
nextTick(callback, [false]);
return;
}
if (!pathInfo.isAsar) return nativeExists(pathArgument, callback);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
nextTick(callback, [error]);
return;
}
const pathExists = (archive.stat(filePath) !== false);
nextTick(callback, [pathExists]);
};
fs.exists[util.promisify.custom] = function exists (pathArgument: string) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return nativeExists[util.promisify.custom](pathArgument);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
return Promise.reject(error);
}
return Promise.resolve(archive.stat(filePath) !== false);
};
const { existsSync } = fs;
fs.existsSync = (pathArgument: string) => {
let pathInfo: ReturnType<typeof splitPath>;
try {
pathInfo = splitPath(pathArgument);
} catch {
return false;
}
if (!pathInfo.isAsar) return existsSync(pathArgument);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) return false;
return archive.stat(filePath) !== false;
};
const { access } = fs;
fs.access = function (pathArgument: string, mode: any, callback: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return access.apply(this, arguments);
const { asarPath, filePath } = pathInfo;
if (typeof mode === 'function') {
callback = mode;
mode = fs.constants.F_OK;
}
const archive = getOrCreateArchive(asarPath);
if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
nextTick(callback, [error]);
return;
}
const info = archive.getFileInfo(filePath);
if (!info) {
const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
nextTick(callback, [error]);
return;
}
if (info.unpacked) {
const realPath = archive.copyFileOut(filePath);
return fs.access(realPath, mode, callback);
}
const stats = archive.stat(filePath);
if (!stats) {
const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
nextTick(callback, [error]);
return;
}
if (mode & fs.constants.W_OK) {
const error = createError(AsarError.NO_ACCESS, { asarPath, filePath });
nextTick(callback, [error]);
return;
}
nextTick(callback);
};
fs.promises.access = util.promisify(fs.access);
const { accessSync } = fs;
fs.accessSync = function (pathArgument: string, mode: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return accessSync.apply(this, arguments);
const { asarPath, filePath } = pathInfo;
if (mode == null) mode = fs.constants.F_OK;
const archive = getOrCreateArchive(asarPath);
if (!archive) {
throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
}
const info = archive.getFileInfo(filePath);
if (!info) {
throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
}
if (info.unpacked) {
const realPath = archive.copyFileOut(filePath);
return fs.accessSync(realPath, mode);
}
const stats = archive.stat(filePath);
if (!stats) {
throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
}
if (mode & fs.constants.W_OK) {
throw createError(AsarError.NO_ACCESS, { asarPath, filePath });
}
};
function fsReadFileAsar (pathArgument: string, options: any, callback: any) {
const pathInfo = splitPath(pathArgument);
if (pathInfo.isAsar) {
const { asarPath, filePath } = pathInfo;
if (typeof options === 'function') {
callback = options;
options = { encoding: null };
} else if (typeof options === 'string') {
options = { encoding: options };
} else if (options === null || options === undefined) {
options = { encoding: null };
} else if (typeof options !== 'object') {
throw new TypeError('Bad arguments');
}
const { encoding } = options;
const archive = getOrCreateArchive(asarPath);
if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
nextTick(callback, [error]);
return;
}
const info = archive.getFileInfo(filePath);
if (!info) {
const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
nextTick(callback, [error]);
return;
}
if (info.size === 0) {
nextTick(callback, [null, encoding ? '' : Buffer.alloc(0)]);
return;
}
if (info.unpacked) {
const realPath = archive.copyFileOut(filePath);
return fs.readFile(realPath, options, callback);
}
const buffer = Buffer.alloc(info.size);
const fd = archive.getFdAndValidateIntegrityLater();
if (!(fd >= 0)) {
const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
nextTick(callback, [error]);
return;
}
logASARAccess(asarPath, filePath, info.offset);
fs.read(fd, buffer, 0, info.size, info.offset, (error: Error) => {
validateBufferIntegrity(buffer, info.integrity);
callback(error, encoding ? buffer.toString(encoding) : buffer);
});
}
}
const { readFile } = fs;
fs.readFile = function (pathArgument: string, options: any, callback: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) {
return readFile.apply(this, arguments);
}
return fsReadFileAsar(pathArgument, options, callback);
};
const { readFile: readFilePromise } = fs.promises;
fs.promises.readFile = function (pathArgument: string, options: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) {
return readFilePromise.apply(this, arguments);
}
const p = util.promisify(fsReadFileAsar);
return p(pathArgument, options);
};
const { readFileSync } = fs;
fs.readFileSync = function (pathArgument: string, options: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return readFileSync.apply(this, arguments);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
const info = archive.getFileInfo(filePath);
if (!info) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
if (info.size === 0) return (options) ? '' : Buffer.alloc(0);
if (info.unpacked) {
const realPath = archive.copyFileOut(filePath);
return fs.readFileSync(realPath, options);
}
if (!options) {
options = { encoding: null };
} else if (typeof options === 'string') {
options = { encoding: options };
} else if (typeof options !== 'object') {
throw new TypeError('Bad arguments');
}
const { encoding } = options;
const buffer = Buffer.alloc(info.size);
const fd = archive.getFdAndValidateIntegrityLater();
if (!(fd >= 0)) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
logASARAccess(asarPath, filePath, info.offset);
fs.readSync(fd, buffer, 0, info.size, info.offset);
validateBufferIntegrity(buffer, info.integrity);
return (encoding) ? buffer.toString(encoding) : buffer;
};
const { readdir } = fs;
fs.readdir = function (pathArgument: string, options?: { encoding?: string | null; withFileTypes?: boolean } | null, callback?: Function) {
const pathInfo = splitPath(pathArgument);
if (typeof options === 'function') {
callback = options;
options = undefined;
}
if (!pathInfo.isAsar) return readdir.apply(this, arguments);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
nextTick(callback!, [error]);
return;
}
const files = archive.readdir(filePath);
if (!files) {
const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
nextTick(callback!, [error]);
return;
}
if (options?.withFileTypes) {
const dirents = [];
for (const file of files) {
const childPath = path.join(filePath, file);
const stats = archive.stat(childPath);
if (!stats) {
const error = createError(AsarError.NOT_FOUND, { asarPath, filePath: childPath });
nextTick(callback!, [error]);
return;
}
dirents.push(new fs.Dirent(file, stats.type));
}
nextTick(callback!, [null, dirents]);
return;
}
nextTick(callback!, [null, files]);
};
fs.promises.readdir = util.promisify(fs.readdir);
type ReaddirSyncOptions = { encoding: BufferEncoding | null; withFileTypes?: false };
const { readdirSync } = fs;
fs.readdirSync = function (pathArgument: string, options: ReaddirSyncOptions | BufferEncoding | null) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return readdirSync.apply(this, arguments);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) {
throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
}
const files = archive.readdir(filePath);
if (!files) {
throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
}
if (options && (options as ReaddirSyncOptions).withFileTypes) {
const dirents = [];
for (const file of files) {
const childPath = path.join(filePath, file);
const stats = archive.stat(childPath);
if (!stats) {
throw createError(AsarError.NOT_FOUND, { asarPath, filePath: childPath });
}
dirents.push(new fs.Dirent(file, stats.type));
}
return dirents;
}
return files;
};
const { internalModuleReadJSON } = internalBinding('fs');
internalBinding('fs').internalModuleReadJSON = (pathArgument: string) => {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return internalModuleReadJSON(pathArgument);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) return [];
const info = archive.getFileInfo(filePath);
if (!info) return [];
if (info.size === 0) return ['', false];
if (info.unpacked) {
const realPath = archive.copyFileOut(filePath);
const str = fs.readFileSync(realPath, { encoding: 'utf8' });
return [str, str.length > 0];
}
const buffer = Buffer.alloc(info.size);
const fd = archive.getFdAndValidateIntegrityLater();
if (!(fd >= 0)) return [];
logASARAccess(asarPath, filePath, info.offset);
fs.readSync(fd, buffer, 0, info.size, info.offset);
validateBufferIntegrity(buffer, info.integrity);
const str = buffer.toString('utf8');
return [str, str.length > 0];
};
const { internalModuleStat } = internalBinding('fs');
internalBinding('fs').internalModuleStat = (pathArgument: string) => {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return internalModuleStat(pathArgument);
const { asarPath, filePath } = pathInfo;
// -ENOENT
const archive = getOrCreateArchive(asarPath);
if (!archive) return -34;
// -ENOENT
const stats = archive.stat(filePath);
if (!stats) return -34;
return (stats.type === AsarFileType.kDirectory) ? 1 : 0;
};
// Calling mkdir for directory inside asar archive should throw ENOTDIR
// error, but on Windows it throws ENOENT.
if (process.platform === 'win32') {
const { mkdir } = fs;
fs.mkdir = (pathArgument: string, options: any, callback: any) => {
if (typeof options === 'function') {
callback = options;
options = {};
}
const pathInfo = splitPath(pathArgument);
if (pathInfo.isAsar && pathInfo.filePath.length > 0) {
const error = createError(AsarError.NOT_DIR);
nextTick(callback, [error]);
return;
}
mkdir(pathArgument, options, callback);
};
fs.promises.mkdir = util.promisify(fs.mkdir);
const { mkdirSync } = fs;
fs.mkdirSync = function (pathArgument: string, options: any) {
const pathInfo = splitPath(pathArgument);
if (pathInfo.isAsar && pathInfo.filePath.length) throw createError(AsarError.NOT_DIR);
return mkdirSync(pathArgument, options);
};
}
function invokeWithNoAsar (func: Function) {
return function (this: any) {
const processNoAsarOriginalValue = process.noAsar;
process.noAsar = true;
try {
return func.apply(this, arguments);
} finally {
process.noAsar = processNoAsarOriginalValue;
}
};
}
// Strictly implementing the flags of fs.copyFile is hard, just do a simple
// implementation for now. Doing 2 copies won't spend much time more as OS
// has filesystem caching.
overrideAPI(fs, 'copyFile');
overrideAPISync(fs, 'copyFileSync');
overrideAPI(fs, 'open');
overrideAPISync(process, 'dlopen', 1);
overrideAPISync(Module._extensions, '.node', 1);
overrideAPISync(fs, 'openSync');
const overrideChildProcess = (childProcess: Record<string, any>) => {
// Executing a command string containing a path to an asar archive
// confuses `childProcess.execFile`, which is internally called by
// `childProcess.{exec,execSync}`, causing Electron to consider the full
// command as a single path to an archive.
const { exec, execSync } = childProcess;
childProcess.exec = invokeWithNoAsar(exec);
childProcess.exec[util.promisify.custom] = invokeWithNoAsar(exec[util.promisify.custom]);
childProcess.execSync = invokeWithNoAsar(execSync);
overrideAPI(childProcess, 'execFile');
overrideAPISync(childProcess, 'execFileSync');
};
const asarReady = new WeakSet();
// Lazily override the child_process APIs only when child_process is
// fetched the first time. We will eagerly override the child_process APIs
// when this env var is set so that stack traces generated inside node unit
// tests will match. This env var will only slow things down in users apps
// and should not be used.
if (process.env.ELECTRON_EAGER_ASAR_HOOK_FOR_TESTING) {
overrideChildProcess(require('child_process'));
} else {
const originalModuleLoad = Module._load;
Module._load = (request: string, ...args: any[]) => {
const loadResult = originalModuleLoad(request, ...args);
if (request === 'child_process' || request === 'node:child_process') {
if (!asarReady.has(loadResult)) {
asarReady.add(loadResult);
// Just to make it obvious what we are dealing with here
const childProcess = loadResult;
overrideChildProcess(childProcess);
}
}
return loadResult;
};
}
};
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,211 |
[Bug]: Electron 28 breaks `import` of transitive dependencies inside ES modules
|
### 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
28.0.0-alpha.2
### What operating system are you using?
Windows
### Operating System Version
Windows 10
### What arch are you using?
x64
### Last Known Working Electron version
27.0.0
### Expected Behavior
Importing an ESM dependency which imports some other dependency (ESM or CJS) should work from inside `app.asar`
### Actual Behavior
The module lookup starts at ```node_modules/<directory where the dependency's `main` file lives>/node_modules```, doesn't find the transitive dependency there and then crashes, never reaching the top-level `node_modules` which is where the transitive dependency actually lives:

### Testcase Gist URL
_No response_
### Additional Information
I've run into this using [this repro](https://github.com/electron/asar/issues/249#issuecomment-1434998313), where the ESM dependency `got` is imported causing the app to crash when looking for the transitive ESM dependency `@sindresorhus/is`. I've put together a minimal reproduction with two local dependencies, which should make it easier to test different variables: https://github.com/erikian/esm-asar-demo
Note that this problem seems to be limited to dependencies inside `node_modules`, i.e. ESM imports across project files work fine:
```ts
// src/main.mjs
import printStuff from './printStuff.js'
printStuff('it works!')
// src/printStuff.js
import logger from './logger.js'
export default function printStuff(...stuff) {
logger(...stuff)
}
// src/logger.js
export default function logger(...args) {
console.log(...args)
}
```
Some findings:
- `const { default: printStuff } = await import('my-esm-dependency')` doesn't work out of the box, but it does work when setting `process.noAsar = true` before importing. Moving the import into the `app.whenReady` callback also doesn't work
- `import printStuff from 'my-esm-dependency'` doesn't work at all, not even with `process.noAsar = true`
- This is not limited to ESM entrypoints. I also get the same errors on the `commonjs-entrypoint` branch, and changing to Electron 27.0.0 fixes the problem.
|
https://github.com/electron/electron/issues/40211
|
https://github.com/electron/electron/pull/40221
|
f7b1c75c72a8dcab4157408f92bd3771606d8029
|
b6ec19a582579c8f7972a1c140b9404e8b2ccd87
| 2023-10-16T01:14:29Z |
c++
| 2023-10-16T16:35:25Z |
spec/asar-spec.ts
|
import { expect } from 'chai';
import * as path from 'node:path';
import * as url from 'node:url';
import { Worker } from 'node:worker_threads';
import { BrowserWindow, ipcMain } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import { getRemoteContext, ifdescribe, ifit, itremote, useRemoteContext } from './lib/spec-helpers';
import * as importedFs from 'node:fs';
import { once } from 'node:events';
describe('asar package', () => {
const fixtures = path.join(__dirname, 'fixtures');
const asarDir = path.join(fixtures, 'test.asar');
afterEach(closeAllWindows);
describe('asar protocol', () => {
it('sets __dirname correctly', async function () {
after(function () {
ipcMain.removeAllListeners('dirname');
});
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
const p = path.resolve(asarDir, 'web.asar', 'index.html');
const dirnameEvent = once(ipcMain, 'dirname');
w.loadFile(p);
const [, dirname] = await dirnameEvent;
expect(dirname).to.equal(path.dirname(p));
});
it('loads script tag in html', async function () {
after(function () {
ipcMain.removeAllListeners('ping');
});
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
const p = path.resolve(asarDir, 'script.asar', 'index.html');
const ping = once(ipcMain, 'ping');
w.loadFile(p);
const [, message] = await ping;
expect(message).to.equal('pong');
});
it('loads video tag in html', async function () {
this.timeout(60000);
after(function () {
ipcMain.removeAllListeners('asar-video');
});
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
const p = path.resolve(asarDir, 'video.asar', 'index.html');
w.loadFile(p);
const [, message, error] = await once(ipcMain, 'asar-video');
if (message === 'ended') {
expect(error).to.be.null();
} else if (message === 'error') {
throw new Error(error);
}
});
});
describe('worker', () => {
it('Worker can load asar file', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'workers', 'load_worker.html'));
const workerUrl = url.format({
pathname: path.resolve(fixtures, 'workers', 'workers.asar', 'worker.js').replaceAll('\\', '/'),
protocol: 'file',
slashes: true
});
const result = await w.webContents.executeJavaScript(`loadWorker('${workerUrl}')`);
expect(result).to.equal('success');
});
it('SharedWorker can load asar file', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'workers', 'load_shared_worker.html'));
const workerUrl = url.format({
pathname: path.resolve(fixtures, 'workers', 'workers.asar', 'shared_worker.js').replaceAll('\\', '/'),
protocol: 'file',
slashes: true
});
const result = await w.webContents.executeJavaScript(`loadSharedWorker('${workerUrl}')`);
expect(result).to.equal('success');
});
});
describe('worker threads', function () {
// DISABLED-FIXME(#38192): only disabled for ASan.
ifit(!process.env.IS_ASAN)('should start worker thread from asar file', function (callback) {
const p = path.join(asarDir, 'worker_threads.asar', 'worker.js');
const w = new Worker(p);
w.on('error', (err) => callback(err));
w.on('message', (message) => {
expect(message).to.equal('ping');
w.terminate();
callback(null);
});
});
});
});
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async function expectToThrowErrorWithCode (_func: Function, _code: string) {
/* dummy for typescript */
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function promisify (_f: Function): any {
/* dummy for typescript */
}
describe('asar package', function () {
const fixtures = path.join(__dirname, 'fixtures');
const asarDir = path.join(fixtures, 'test.asar');
const fs = require('node:fs') as typeof importedFs; // dummy, to fool typescript
useRemoteContext({
url: url.pathToFileURL(path.join(fixtures, 'pages', 'blank.html')),
setup: `
async function expectToThrowErrorWithCode (func, code) {
let error;
try {
await func();
} catch (e) {
error = e;
}
const chai = require('chai')
chai.expect(error).to.have.property('code').which.equals(code);
}
fs = require('node:fs')
path = require('node:path')
asarDir = ${JSON.stringify(asarDir)}
// This is used instead of util.promisify for some tests to dodge the
// util.promisify.custom behavior.
promisify = (f) => {
return (...args) => new Promise((resolve, reject) => {
f(...args, (err, result) => {
if (err) reject(err)
else resolve(result)
})
})
}
null
`
});
describe('node api', function () {
itremote('supports paths specified as a Buffer', function () {
const file = Buffer.from(path.join(asarDir, 'a.asar', 'file1'));
expect(fs.existsSync(file)).to.be.true();
});
describe('fs.readFileSync', function () {
itremote('does not leak fd', function () {
let readCalls = 1;
while (readCalls <= 10000) {
fs.readFileSync(path.join(process.resourcesPath, 'default_app.asar', 'main.js'));
readCalls++;
}
});
itremote('reads a normal file', function () {
const file1 = path.join(asarDir, 'a.asar', 'file1');
expect(fs.readFileSync(file1).toString().trim()).to.equal('file1');
const file2 = path.join(asarDir, 'a.asar', 'file2');
expect(fs.readFileSync(file2).toString().trim()).to.equal('file2');
const file3 = path.join(asarDir, 'a.asar', 'file3');
expect(fs.readFileSync(file3).toString().trim()).to.equal('file3');
});
itremote('reads from a empty file', function () {
const file = path.join(asarDir, 'empty.asar', 'file1');
const buffer = fs.readFileSync(file);
expect(buffer).to.be.empty();
expect(buffer.toString()).to.equal('');
});
itremote('reads a linked file', function () {
const p = path.join(asarDir, 'a.asar', 'link1');
expect(fs.readFileSync(p).toString().trim()).to.equal('file1');
});
itremote('reads a file from linked directory', function () {
const p1 = path.join(asarDir, 'a.asar', 'link2', 'file1');
expect(fs.readFileSync(p1).toString().trim()).to.equal('file1');
const p2 = path.join(asarDir, 'a.asar', 'link2', 'link2', 'file1');
expect(fs.readFileSync(p2).toString().trim()).to.equal('file1');
});
itremote('throws ENOENT error when can not find file', function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
expect(() => {
fs.readFileSync(p);
}).to.throw(/ENOENT/);
});
itremote('passes ENOENT error to callback when can not find file', function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
let async = false;
fs.readFile(p, function (error) {
expect(async).to.be.true();
expect(error).to.match(/ENOENT/);
});
async = true;
});
itremote('reads a normal file with unpacked files', function () {
const p = path.join(asarDir, 'unpack.asar', 'a.txt');
expect(fs.readFileSync(p).toString().trim()).to.equal('a');
});
itremote('reads a file in filesystem', function () {
const p = path.resolve(asarDir, 'file');
expect(fs.readFileSync(p).toString().trim()).to.equal('file');
});
});
describe('fs.readFile', function () {
itremote('reads a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
const content = await new Promise((resolve, reject) => fs.readFile(p, (err, content) => {
if (err) return reject(err);
resolve(content);
}));
expect(String(content).trim()).to.equal('file1');
});
itremote('reads from a empty file', async function () {
const p = path.join(asarDir, 'empty.asar', 'file1');
const content = await new Promise((resolve, reject) => fs.readFile(p, (err, content) => {
if (err) return reject(err);
resolve(content);
}));
expect(String(content)).to.equal('');
});
itremote('reads from a empty file with encoding', async function () {
const p = path.join(asarDir, 'empty.asar', 'file1');
const content = await new Promise((resolve, reject) => fs.readFile(p, (err, content) => {
if (err) return reject(err);
resolve(content);
}));
expect(String(content)).to.equal('');
});
itremote('reads a linked file', async function () {
const p = path.join(asarDir, 'a.asar', 'link1');
const content = await new Promise((resolve, reject) => fs.readFile(p, (err, content) => {
if (err) return reject(err);
resolve(content);
}));
expect(String(content).trim()).to.equal('file1');
});
itremote('reads a file from linked directory', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2', 'file1');
const content = await new Promise((resolve, reject) => fs.readFile(p, (err, content) => {
if (err) return reject(err);
resolve(content);
}));
expect(String(content).trim()).to.equal('file1');
});
itremote('throws ENOENT error when can not find file', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
const err = await new Promise<any>((resolve) => fs.readFile(p, resolve));
expect(err.code).to.equal('ENOENT');
});
});
describe('fs.promises.readFile', function () {
itremote('reads a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
const content = await fs.promises.readFile(p);
expect(String(content).trim()).to.equal('file1');
});
itremote('reads from a empty file', async function () {
const p = path.join(asarDir, 'empty.asar', 'file1');
const content = await fs.promises.readFile(p);
expect(String(content)).to.equal('');
});
itremote('reads from a empty file with encoding', async function () {
const p = path.join(asarDir, 'empty.asar', 'file1');
const content = await fs.promises.readFile(p, 'utf8');
expect(content).to.equal('');
});
itremote('reads a linked file', async function () {
const p = path.join(asarDir, 'a.asar', 'link1');
const content = await fs.promises.readFile(p);
expect(String(content).trim()).to.equal('file1');
});
itremote('reads a file from linked directory', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2', 'file1');
const content = await fs.promises.readFile(p);
expect(String(content).trim()).to.equal('file1');
});
itremote('throws ENOENT error when can not find file', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
await expectToThrowErrorWithCode(() => fs.promises.readFile(p), 'ENOENT');
});
});
describe('fs.copyFile', function () {
itremote('copies a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
const temp = require('temp').track();
const dest = temp.path();
await new Promise<void>((resolve, reject) => {
fs.copyFile(p, dest, (err) => {
if (err) reject(err);
else resolve();
});
});
expect(fs.readFileSync(p).equals(fs.readFileSync(dest))).to.be.true();
});
itremote('copies a unpacked file', async function () {
const p = path.join(asarDir, 'unpack.asar', 'a.txt');
const temp = require('temp').track();
const dest = temp.path();
await new Promise<void>((resolve, reject) => {
fs.copyFile(p, dest, (err) => {
if (err) reject(err);
else resolve();
});
});
expect(fs.readFileSync(p).equals(fs.readFileSync(dest))).to.be.true();
});
});
describe('fs.promises.copyFile', function () {
itremote('copies a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
const temp = require('temp').track();
const dest = temp.path();
await fs.promises.copyFile(p, dest);
expect(fs.readFileSync(p).equals(fs.readFileSync(dest))).to.be.true();
});
itremote('copies a unpacked file', async function () {
const p = path.join(asarDir, 'unpack.asar', 'a.txt');
const temp = require('temp').track();
const dest = temp.path();
await fs.promises.copyFile(p, dest);
expect(fs.readFileSync(p).equals(fs.readFileSync(dest))).to.be.true();
});
});
describe('fs.copyFileSync', function () {
itremote('copies a normal file', function () {
const p = path.join(asarDir, 'a.asar', 'file1');
const temp = require('temp').track();
const dest = temp.path();
fs.copyFileSync(p, dest);
expect(fs.readFileSync(p).equals(fs.readFileSync(dest))).to.be.true();
});
itremote('copies a unpacked file', function () {
const p = path.join(asarDir, 'unpack.asar', 'a.txt');
const temp = require('temp').track();
const dest = temp.path();
fs.copyFileSync(p, dest);
expect(fs.readFileSync(p).equals(fs.readFileSync(dest))).to.be.true();
});
});
describe('fs.lstatSync', function () {
itremote('handles path with trailing slash correctly', function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2', 'file1');
fs.lstatSync(p);
fs.lstatSync(p + '/');
});
itremote('returns information of root', function () {
const p = path.join(asarDir, 'a.asar');
const stats = fs.lstatSync(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.true();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(0);
});
itremote('returns information of root with stats as bigint', function () {
const p = path.join(asarDir, 'a.asar');
const stats = fs.lstatSync(p, { bigint: false });
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.true();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(0);
});
itremote('returns information of a normal file', function () {
const ref2 = ['file1', 'file2', 'file3', path.join('dir1', 'file1'), path.join('link2', 'file1')];
for (let j = 0, len = ref2.length; j < len; j++) {
const file = ref2[j];
const p = path.join(asarDir, 'a.asar', file);
const stats = fs.lstatSync(p);
expect(stats.isFile()).to.be.true();
expect(stats.isDirectory()).to.be.false();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(6);
}
});
itremote('returns information of a normal directory', function () {
const ref2 = ['dir1', 'dir2', 'dir3'];
for (let j = 0, len = ref2.length; j < len; j++) {
const file = ref2[j];
const p = path.join(asarDir, 'a.asar', file);
const stats = fs.lstatSync(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.true();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(0);
}
});
itremote('returns information of a linked file', function () {
const ref2 = ['link1', path.join('dir1', 'link1'), path.join('link2', 'link2')];
for (let j = 0, len = ref2.length; j < len; j++) {
const file = ref2[j];
const p = path.join(asarDir, 'a.asar', file);
const stats = fs.lstatSync(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.false();
expect(stats.isSymbolicLink()).to.be.true();
expect(stats.size).to.equal(0);
}
});
itremote('returns information of a linked directory', function () {
const ref2 = ['link2', path.join('dir1', 'link2'), path.join('link2', 'link2')];
for (let j = 0, len = ref2.length; j < len; j++) {
const file = ref2[j];
const p = path.join(asarDir, 'a.asar', file);
const stats = fs.lstatSync(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.false();
expect(stats.isSymbolicLink()).to.be.true();
expect(stats.size).to.equal(0);
}
});
itremote('throws ENOENT error when can not find file', function () {
const ref2 = ['file4', 'file5', path.join('dir1', 'file4')];
for (let j = 0, len = ref2.length; j < len; j++) {
const file = ref2[j];
const p = path.join(asarDir, 'a.asar', file);
expect(() => {
fs.lstatSync(p);
}).to.throw(/ENOENT/);
}
});
});
describe('fs.lstat', function () {
itremote('handles path with trailing slash correctly', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2', 'file1');
await promisify(fs.lstat)(p + '/');
});
itremote('returns information of root', async function () {
const p = path.join(asarDir, 'a.asar');
const stats = await promisify(fs.lstat)(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.true();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(0);
});
itremote('returns information of root with stats as bigint', async function () {
const p = path.join(asarDir, 'a.asar');
const stats = await promisify(fs.lstat)(p, { bigint: false });
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.true();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(0);
});
itremote('returns information of a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'file1');
const stats = await promisify(fs.lstat)(p);
expect(stats.isFile()).to.be.true();
expect(stats.isDirectory()).to.be.false();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(6);
});
itremote('returns information of a normal directory', async function () {
const p = path.join(asarDir, 'a.asar', 'dir1');
const stats = await promisify(fs.lstat)(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.true();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(0);
});
itremote('returns information of a linked file', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link1');
const stats = await promisify(fs.lstat)(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.false();
expect(stats.isSymbolicLink()).to.be.true();
expect(stats.size).to.equal(0);
});
itremote('returns information of a linked directory', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2');
const stats = await promisify(fs.lstat)(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.false();
expect(stats.isSymbolicLink()).to.be.true();
expect(stats.size).to.equal(0);
});
itremote('throws ENOENT error when can not find file', async function () {
const p = path.join(asarDir, 'a.asar', 'file4');
const err = await new Promise<any>(resolve => fs.lstat(p, resolve));
expect(err.code).to.equal('ENOENT');
});
});
describe('fs.promises.lstat', function () {
itremote('handles path with trailing slash correctly', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2', 'file1');
await fs.promises.lstat(p + '/');
});
itremote('returns information of root', async function () {
const p = path.join(asarDir, 'a.asar');
const stats = await fs.promises.lstat(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.true();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(0);
});
itremote('returns information of root with stats as bigint', async function () {
const p = path.join(asarDir, 'a.asar');
const stats = await fs.promises.lstat(p, { bigint: false });
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.true();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(0);
});
itremote('returns information of a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'file1');
const stats = await fs.promises.lstat(p);
expect(stats.isFile()).to.be.true();
expect(stats.isDirectory()).to.be.false();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(6);
});
itremote('returns information of a normal directory', async function () {
const p = path.join(asarDir, 'a.asar', 'dir1');
const stats = await fs.promises.lstat(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.true();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(0);
});
itremote('returns information of a linked file', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link1');
const stats = await fs.promises.lstat(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.false();
expect(stats.isSymbolicLink()).to.be.true();
expect(stats.size).to.equal(0);
});
itremote('returns information of a linked directory', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2');
const stats = await fs.promises.lstat(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.false();
expect(stats.isSymbolicLink()).to.be.true();
expect(stats.size).to.equal(0);
});
itremote('throws ENOENT error when can not find file', async function () {
const p = path.join(asarDir, 'a.asar', 'file4');
await expectToThrowErrorWithCode(() => fs.promises.lstat(p), 'ENOENT');
});
});
describe('fs.realpathSync', () => {
itremote('returns real path root', () => {
const parent = fs.realpathSync(asarDir);
const p = 'a.asar';
const r = fs.realpathSync(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal file', () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'file1');
const r = fs.realpathSync(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal directory', () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'dir1');
const r = fs.realpathSync(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a linked file', () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'link2', 'link1');
const r = fs.realpathSync(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'file1'));
});
itremote('returns real path of a linked directory', () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'link2', 'link2');
const r = fs.realpathSync(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'dir1'));
});
itremote('returns real path of an unpacked file', () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('unpack.asar', 'a.txt');
const r = fs.realpathSync(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('throws ENOENT error when can not find file', () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'not-exist');
expect(() => {
fs.realpathSync(path.join(parent, p));
}).to.throw(/ENOENT/);
});
});
describe('fs.realpathSync.native', () => {
itremote('returns real path root', () => {
const parent = fs.realpathSync.native(asarDir);
const p = 'a.asar';
const r = fs.realpathSync.native(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal file', () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'file1');
const r = fs.realpathSync.native(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal directory', () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'dir1');
const r = fs.realpathSync.native(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a linked file', () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'link2', 'link1');
const r = fs.realpathSync.native(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'file1'));
});
itremote('returns real path of a linked directory', () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'link2', 'link2');
const r = fs.realpathSync.native(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'dir1'));
});
itremote('returns real path of an unpacked file', () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('unpack.asar', 'a.txt');
const r = fs.realpathSync.native(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('throws ENOENT error when can not find file', () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'not-exist');
expect(() => {
fs.realpathSync.native(path.join(parent, p));
}).to.throw(/ENOENT/);
});
});
describe('fs.realpath', () => {
itremote('returns real path root', async () => {
const parent = fs.realpathSync(asarDir);
const p = 'a.asar';
const r = await promisify(fs.realpath)(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal file', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'file1');
const r = await promisify(fs.realpath)(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal directory', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'dir1');
const r = await promisify(fs.realpath)(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a linked file', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'link2', 'link1');
const r = await promisify(fs.realpath)(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'file1'));
});
itremote('returns real path of a linked directory', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'link2', 'link2');
const r = await promisify(fs.realpath)(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'dir1'));
});
itremote('returns real path of an unpacked file', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('unpack.asar', 'a.txt');
const r = await promisify(fs.realpath)(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('throws ENOENT error when can not find file', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'not-exist');
const err = await new Promise<any>(resolve => fs.realpath(path.join(parent, p), resolve));
expect(err.code).to.equal('ENOENT');
});
});
describe('fs.promises.realpath', () => {
itremote('returns real path root', async () => {
const parent = fs.realpathSync(asarDir);
const p = 'a.asar';
const r = await fs.promises.realpath(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal file', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'file1');
const r = await fs.promises.realpath(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal directory', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'dir1');
const r = await fs.promises.realpath(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a linked file', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'link2', 'link1');
const r = await fs.promises.realpath(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'file1'));
});
itremote('returns real path of a linked directory', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'link2', 'link2');
const r = await fs.promises.realpath(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'dir1'));
});
itremote('returns real path of an unpacked file', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('unpack.asar', 'a.txt');
const r = await fs.promises.realpath(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('throws ENOENT error when can not find file', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'not-exist');
await expectToThrowErrorWithCode(() => fs.promises.realpath(path.join(parent, p)), 'ENOENT');
});
});
describe('fs.realpath.native', () => {
itremote('returns real path root', async () => {
const parent = fs.realpathSync.native(asarDir);
const p = 'a.asar';
const r = await promisify(fs.realpath.native)(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal file', async () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'file1');
const r = await promisify(fs.realpath.native)(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal directory', async () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'dir1');
const r = await promisify(fs.realpath.native)(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a linked file', async () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'link2', 'link1');
const r = await promisify(fs.realpath.native)(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'file1'));
});
itremote('returns real path of a linked directory', async () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'link2', 'link2');
const r = await promisify(fs.realpath.native)(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'dir1'));
});
itremote('returns real path of an unpacked file', async () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('unpack.asar', 'a.txt');
const r = await promisify(fs.realpath.native)(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('throws ENOENT error when can not find file', async () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'not-exist');
const err = await new Promise<any>(resolve => fs.realpath.native(path.join(parent, p), resolve));
expect(err.code).to.equal('ENOENT');
});
});
describe('fs.readdirSync', function () {
itremote('reads dirs from root', function () {
const p = path.join(asarDir, 'a.asar');
const dirs = fs.readdirSync(p);
expect(dirs).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']);
});
itremote('reads dirs from a normal dir', function () {
const p = path.join(asarDir, 'a.asar', 'dir1');
const dirs = fs.readdirSync(p);
expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']);
});
itremote('supports withFileTypes', function () {
const p = path.join(asarDir, 'a.asar');
const dirs = fs.readdirSync(p, { withFileTypes: true });
for (const dir of dirs) {
expect(dir).to.be.an.instanceof(fs.Dirent);
}
const names = dirs.map(a => a.name);
expect(names).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']);
});
itremote('supports withFileTypes for a deep directory', function () {
const p = path.join(asarDir, 'a.asar', 'dir3');
const dirs = fs.readdirSync(p, { withFileTypes: true });
for (const dir of dirs) {
expect(dir).to.be.an.instanceof(fs.Dirent);
}
const names = dirs.map(a => a.name);
expect(names).to.deep.equal(['file1', 'file2', 'file3']);
});
itremote('reads dirs from a linked dir', function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2');
const dirs = fs.readdirSync(p);
expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']);
});
itremote('throws ENOENT error when can not find file', function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
expect(() => {
fs.readdirSync(p);
}).to.throw(/ENOENT/);
});
});
describe('fs.readdir', function () {
itremote('reads dirs from root', async () => {
const p = path.join(asarDir, 'a.asar');
const dirs = await promisify(fs.readdir)(p);
expect(dirs).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']);
});
itremote('supports withFileTypes', async () => {
const p = path.join(asarDir, 'a.asar');
const dirs = await promisify(fs.readdir)(p, { withFileTypes: true });
for (const dir of dirs) {
expect(dir).to.be.an.instanceof(fs.Dirent);
}
const names = dirs.map((a: any) => a.name);
expect(names).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']);
});
itremote('reads dirs from a normal dir', async () => {
const p = path.join(asarDir, 'a.asar', 'dir1');
const dirs = await promisify(fs.readdir)(p);
expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']);
});
itremote('reads dirs from a linked dir', async () => {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2');
const dirs = await promisify(fs.readdir)(p);
expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']);
});
itremote('throws ENOENT error when can not find file', async () => {
const p = path.join(asarDir, 'a.asar', 'not-exist');
const err = await new Promise<any>(resolve => fs.readdir(p, resolve));
expect(err.code).to.equal('ENOENT');
});
it('handles null for options', function (done) {
const p = path.join(asarDir, 'a.asar', 'dir1');
fs.readdir(p, null, function (err, dirs) {
try {
expect(err).to.be.null();
expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']);
done();
} catch (e) {
done(e);
}
});
});
it('handles undefined for options', function (done) {
const p = path.join(asarDir, 'a.asar', 'dir1');
fs.readdir(p, undefined, function (err, dirs) {
try {
expect(err).to.be.null();
expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']);
done();
} catch (e) {
done(e);
}
});
});
});
describe('fs.promises.readdir', function () {
itremote('reads dirs from root', async function () {
const p = path.join(asarDir, 'a.asar');
const dirs = await fs.promises.readdir(p);
expect(dirs).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']);
});
itremote('supports withFileTypes', async function () {
const p = path.join(asarDir, 'a.asar');
const dirs = await fs.promises.readdir(p, { withFileTypes: true });
for (const dir of dirs) {
expect(dir).to.be.an.instanceof(fs.Dirent);
}
const names = dirs.map(a => a.name);
expect(names).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']);
});
itremote('reads dirs from a normal dir', async function () {
const p = path.join(asarDir, 'a.asar', 'dir1');
const dirs = await fs.promises.readdir(p);
expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']);
});
itremote('reads dirs from a linked dir', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2');
const dirs = await fs.promises.readdir(p);
expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']);
});
itremote('throws ENOENT error when can not find file', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
await expectToThrowErrorWithCode(() => fs.promises.readdir(p), 'ENOENT');
});
});
describe('fs.openSync', function () {
itremote('opens a normal/linked/under-linked-directory file', function () {
const ref2 = ['file1', 'link1', path.join('link2', 'file1')];
for (let j = 0, len = ref2.length; j < len; j++) {
const file = ref2[j];
const p = path.join(asarDir, 'a.asar', file);
const fd = fs.openSync(p, 'r');
const buffer = Buffer.alloc(6);
fs.readSync(fd, buffer, 0, 6, 0);
expect(String(buffer).trim()).to.equal('file1');
fs.closeSync(fd);
}
});
itremote('throws ENOENT error when can not find file', function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
expect(() => {
(fs.openSync as any)(p);
}).to.throw(/ENOENT/);
});
});
describe('fs.open', function () {
itremote('opens a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
const fd = await promisify(fs.open)(p, 'r');
const buffer = Buffer.alloc(6);
await promisify(fs.read)(fd, buffer, 0, 6, 0);
expect(String(buffer).trim()).to.equal('file1');
await promisify(fs.close)(fd);
});
itremote('throws ENOENT error when can not find file', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
const err = await new Promise<any>(resolve => fs.open(p, 'r', resolve));
expect(err.code).to.equal('ENOENT');
});
});
describe('fs.promises.open', function () {
itremote('opens a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
const fh = await fs.promises.open(p, 'r');
const buffer = Buffer.alloc(6);
await fh.read(buffer, 0, 6, 0);
expect(String(buffer).trim()).to.equal('file1');
await fh.close();
});
itremote('throws ENOENT error when can not find file', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
await expectToThrowErrorWithCode(() => fs.promises.open(p, 'r'), 'ENOENT');
});
});
describe('fs.mkdir', function () {
itremote('throws error when calling inside asar archive', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
const err = await new Promise<any>(resolve => fs.mkdir(p, resolve));
expect(err.code).to.equal('ENOTDIR');
});
});
describe('fs.promises.mkdir', function () {
itremote('throws error when calling inside asar archive', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
await expectToThrowErrorWithCode(() => fs.promises.mkdir(p), 'ENOTDIR');
});
});
describe('fs.mkdirSync', function () {
itremote('throws error when calling inside asar archive', function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
expect(() => {
fs.mkdirSync(p);
}).to.throw(/ENOTDIR/);
});
});
describe('fs.exists', function () {
itremote('handles an existing file', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
const exists = await new Promise(resolve => fs.exists(p, resolve));
expect(exists).to.be.true();
});
itremote('handles a non-existent file', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
const exists = await new Promise(resolve => fs.exists(p, resolve));
expect(exists).to.be.false();
});
itremote('promisified version handles an existing file', async () => {
const p = path.join(asarDir, 'a.asar', 'file1');
const exists = await require('node:util').promisify(fs.exists)(p);
expect(exists).to.be.true();
});
itremote('promisified version handles a non-existent file', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
const exists = await require('node:util').promisify(fs.exists)(p);
expect(exists).to.be.false();
});
});
describe('fs.existsSync', function () {
itremote('handles an existing file', function () {
const p = path.join(asarDir, 'a.asar', 'file1');
expect(fs.existsSync(p)).to.be.true();
});
itremote('handles a non-existent file', function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
expect(fs.existsSync(p)).to.be.false();
});
});
describe('fs.access', function () {
itremote('accesses a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
await promisify(fs.access)(p);
});
itremote('throws an error when called with write mode', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
const err = await new Promise<any>(resolve => fs.access(p, fs.constants.R_OK | fs.constants.W_OK, resolve));
expect(err.code).to.equal('EACCES');
});
itremote('throws an error when called on non-existent file', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
const err = await new Promise<any>(resolve => fs.access(p, fs.constants.R_OK | fs.constants.W_OK, resolve));
expect(err.code).to.equal('ENOENT');
});
itremote('allows write mode for unpacked files', async function () {
const p = path.join(asarDir, 'unpack.asar', 'a.txt');
await promisify(fs.access)(p, fs.constants.R_OK | fs.constants.W_OK);
});
});
describe('fs.promises.access', function () {
itremote('accesses a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
await fs.promises.access(p);
});
itremote('throws an error when called with write mode', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
await expectToThrowErrorWithCode(() => fs.promises.access(p, fs.constants.R_OK | fs.constants.W_OK), 'EACCES');
});
itremote('throws an error when called on non-existent file', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
await expectToThrowErrorWithCode(() => fs.promises.access(p), 'ENOENT');
});
itremote('allows write mode for unpacked files', async function () {
const p = path.join(asarDir, 'unpack.asar', 'a.txt');
await fs.promises.access(p, fs.constants.R_OK | fs.constants.W_OK);
});
});
describe('fs.accessSync', function () {
itremote('accesses a normal file', function () {
const p = path.join(asarDir, 'a.asar', 'file1');
expect(() => {
fs.accessSync(p);
}).to.not.throw();
});
itremote('throws an error when called with write mode', function () {
const p = path.join(asarDir, 'a.asar', 'file1');
expect(() => {
fs.accessSync(p, fs.constants.R_OK | fs.constants.W_OK);
}).to.throw(/EACCES/);
});
itremote('throws an error when called on non-existent file', function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
expect(() => {
fs.accessSync(p);
}).to.throw(/ENOENT/);
});
itremote('allows write mode for unpacked files', function () {
const p = path.join(asarDir, 'unpack.asar', 'a.txt');
expect(() => {
fs.accessSync(p, fs.constants.R_OK | fs.constants.W_OK);
}).to.not.throw();
});
});
function generateSpecs (childProcess: string) {
describe(`${childProcess}.fork`, function () {
itremote('opens a normal js file', async function (childProcess: string) {
const child = require(childProcess).fork(path.join(asarDir, 'a.asar', 'ping.js'));
child.send('message');
const msg = await new Promise(resolve => child.once('message', resolve));
expect(msg).to.equal('message');
}, [childProcess]);
itremote('supports asar in the forked js', async function (childProcess: string, fixtures: string) {
const file = path.join(asarDir, 'a.asar', 'file1');
const child = require(childProcess).fork(path.join(fixtures, 'module', 'asar.js'));
child.send(file);
const content = await new Promise(resolve => child.once('message', resolve));
expect(content).to.equal(fs.readFileSync(file).toString());
}, [childProcess, fixtures]);
});
describe(`${childProcess}.exec`, function () {
itremote('should not try to extract the command if there is a reference to a file inside an .asar', async function (childProcess: string) {
const echo = path.join(asarDir, 'echo.asar', 'echo');
const stdout = await promisify(require(childProcess).exec)('echo ' + echo + ' foo bar');
expect(stdout.toString().replaceAll('\r', '')).to.equal(echo + ' foo bar\n');
}, [childProcess]);
});
describe(`${childProcess}.execSync`, function () {
itremote('should not try to extract the command if there is a reference to a file inside an .asar', async function (childProcess: string) {
const echo = path.join(asarDir, 'echo.asar', 'echo');
const stdout = require(childProcess).execSync('echo ' + echo + ' foo bar');
expect(stdout.toString().replaceAll('\r', '')).to.equal(echo + ' foo bar\n');
}, [childProcess]);
});
ifdescribe(process.platform === 'darwin' && process.arch !== 'arm64')(`${childProcess}.execFile`, function () {
itremote('executes binaries', async function (childProcess: string) {
const echo = path.join(asarDir, 'echo.asar', 'echo');
const stdout = await promisify(require(childProcess).execFile)(echo, ['test']);
expect(stdout).to.equal('test\n');
}, [childProcess]);
itremote('executes binaries without callback', async function (childProcess: string) {
const echo = path.join(asarDir, 'echo.asar', 'echo');
const process = require(childProcess).execFile(echo, ['test']);
const code = await new Promise(resolve => process.once('close', resolve));
expect(code).to.equal(0);
process.on('error', function () {
throw new Error('error');
});
}, [childProcess]);
itremote('execFileSync executes binaries', function (childProcess: string) {
const echo = path.join(asarDir, 'echo.asar', 'echo');
const output = require(childProcess).execFileSync(echo, ['test']);
expect(String(output)).to.equal('test\n');
}, [childProcess]);
});
}
generateSpecs('child_process');
generateSpecs('node:child_process');
describe('internalModuleReadJSON', function () {
itremote('reads a normal file', function () {
const { internalModuleReadJSON } = (process as any).binding('fs');
const file1 = path.join(asarDir, 'a.asar', 'file1');
const [s1, c1] = internalModuleReadJSON(file1);
expect([s1.toString().trim(), c1]).to.eql(['file1', true]);
const file2 = path.join(asarDir, 'a.asar', 'file2');
const [s2, c2] = internalModuleReadJSON(file2);
expect([s2.toString().trim(), c2]).to.eql(['file2', true]);
const file3 = path.join(asarDir, 'a.asar', 'file3');
const [s3, c3] = internalModuleReadJSON(file3);
expect([s3.toString().trim(), c3]).to.eql(['file3', true]);
});
itremote('reads a normal file with unpacked files', function () {
const { internalModuleReadJSON } = (process as any).binding('fs');
const p = path.join(asarDir, 'unpack.asar', 'a.txt');
const [s, c] = internalModuleReadJSON(p);
expect([s.toString().trim(), c]).to.eql(['a', true]);
});
});
describe('util.promisify', function () {
itremote('can promisify all fs functions', function () {
const originalFs = require('original-fs');
const util = require('node:util');
for (const [propertyName, originalValue] of Object.entries(originalFs)) {
// Some properties exist but have a value of `undefined` on some platforms.
// E.g. `fs.lchmod`, which in only available on MacOS, see
// https://nodejs.org/docs/latest-v10.x/api/fs.html#fs_fs_lchmod_path_mode_callback
// Also check for `null`s, `hasOwnProperty()` can't handle them.
if (typeof originalValue === 'undefined' || originalValue === null) continue;
if (Object.hasOwn(originalValue, util.promisify.custom)) {
expect(fs).to.have.own.property(propertyName)
.that.has.own.property(util.promisify.custom);
}
}
});
});
describe('process.noAsar', function () {
const errorName = process.platform === 'win32' ? 'ENOENT' : 'ENOTDIR';
beforeEach(async function () {
return (await getRemoteContext()).webContents.executeJavaScript(`
process.noAsar = true;
`);
});
afterEach(async function () {
return (await getRemoteContext()).webContents.executeJavaScript(`
process.noAsar = false;
`);
});
itremote('disables asar support in sync API', function (errorName: string) {
const file = path.join(asarDir, 'a.asar', 'file1');
const dir = path.join(asarDir, 'a.asar', 'dir1');
console.log(1);
expect(() => {
fs.readFileSync(file);
}).to.throw(new RegExp(errorName));
expect(() => {
fs.lstatSync(file);
}).to.throw(new RegExp(errorName));
expect(() => {
fs.realpathSync(file);
}).to.throw(new RegExp(errorName));
expect(() => {
fs.readdirSync(dir);
}).to.throw(new RegExp(errorName));
}, [errorName]);
itremote('disables asar support in async API', async function (errorName: string) {
const file = path.join(asarDir, 'a.asar', 'file1');
const dir = path.join(asarDir, 'a.asar', 'dir1');
await new Promise<void>(resolve => {
fs.readFile(file, function (error) {
expect(error?.code).to.equal(errorName);
fs.lstat(file, function (error) {
expect(error?.code).to.equal(errorName);
fs.realpath(file, function (error) {
expect(error?.code).to.equal(errorName);
fs.readdir(dir, function (error) {
expect(error?.code).to.equal(errorName);
resolve();
});
});
});
});
});
}, [errorName]);
itremote('disables asar support in promises API', async function (errorName: string) {
const file = path.join(asarDir, 'a.asar', 'file1');
const dir = path.join(asarDir, 'a.asar', 'dir1');
await expect(fs.promises.readFile(file)).to.be.eventually.rejectedWith(Error, new RegExp(errorName));
await expect(fs.promises.lstat(file)).to.be.eventually.rejectedWith(Error, new RegExp(errorName));
await expect(fs.promises.realpath(file)).to.be.eventually.rejectedWith(Error, new RegExp(errorName));
await expect(fs.promises.readdir(dir)).to.be.eventually.rejectedWith(Error, new RegExp(errorName));
}, [errorName]);
itremote('treats *.asar as normal file', function () {
const originalFs = require('original-fs');
const asar = path.join(asarDir, 'a.asar');
const content1 = fs.readFileSync(asar);
const content2 = originalFs.readFileSync(asar);
expect(content1.compare(content2)).to.equal(0);
expect(() => {
fs.readdirSync(asar);
}).to.throw(/ENOTDIR/);
});
itremote('is reset to its original value when execSync throws an error', function () {
process.noAsar = false;
expect(() => {
require('node:child_process').execSync(path.join(__dirname, 'does-not-exist.txt'));
}).to.throw();
expect(process.noAsar).to.be.false();
});
});
/*
describe('process.env.ELECTRON_NO_ASAR', function () {
itremote('disables asar support in forked processes', function (done) {
const forked = ChildProcess.fork(path.join(__dirname, 'fixtures', 'module', 'no-asar.js'), [], {
env: {
ELECTRON_NO_ASAR: true
}
});
forked.on('message', function (stats) {
try {
expect(stats.isFile).to.be.true();
expect(stats.size).to.equal(3458);
done();
} catch (e) {
done(e);
}
});
});
itremote('disables asar support in spawned processes', function (done) {
const spawned = ChildProcess.spawn(process.execPath, [path.join(__dirname, 'fixtures', 'module', 'no-asar.js')], {
env: {
ELECTRON_NO_ASAR: true,
ELECTRON_RUN_AS_NODE: true
}
});
let output = '';
spawned.stdout.on('data', function (data) {
output += data;
});
spawned.stdout.on('close', function () {
try {
const stats = JSON.parse(output);
expect(stats.isFile).to.be.true();
expect(stats.size).to.equal(3458);
done();
} catch (e) {
done(e);
}
});
});
});
*/
});
describe('asar protocol', function () {
itremote('can request a file in package', async function () {
const p = path.resolve(asarDir, 'a.asar', 'file1');
const response = await fetch('file://' + p);
const data = await response.text();
expect(data.trim()).to.equal('file1');
});
itremote('can request a file in package with unpacked files', async function () {
const p = path.resolve(asarDir, 'unpack.asar', 'a.txt');
const response = await fetch('file://' + p);
const data = await response.text();
expect(data.trim()).to.equal('a');
});
itremote('can request a linked file in package', async function () {
const p = path.resolve(asarDir, 'a.asar', 'link2', 'link1');
const response = await fetch('file://' + p);
const data = await response.text();
expect(data.trim()).to.equal('file1');
});
itremote('can request a file in filesystem', async function () {
const p = path.resolve(asarDir, 'file');
const response = await fetch('file://' + p);
const data = await response.text();
expect(data.trim()).to.equal('file');
});
itremote('gets error when file is not found', async function () {
const p = path.resolve(asarDir, 'a.asar', 'no-exist');
try {
const response = await fetch('file://' + p);
expect(response.status).to.equal(404);
} catch (error: any) {
expect(error.message).to.equal('Failed to fetch');
}
});
});
describe('original-fs module', function () {
itremote('treats .asar as file', function () {
const file = path.join(asarDir, 'a.asar');
const originalFs = require('original-fs');
const stats = originalFs.statSync(file);
expect(stats.isFile()).to.be.true();
});
/*
it('is available in forked scripts', async function () {
const child = ChildProcess.fork(path.join(fixtures, 'module', 'original-fs.js'));
const message = once(child, 'message');
child.send('message');
const [msg] = await message;
expect(msg).to.equal('object');
});
*/
itremote('can be used with streams', () => {
const originalFs = require('original-fs');
originalFs.createReadStream(path.join(asarDir, 'a.asar'));
});
itremote('can recursively delete a directory with an asar file in itremote', () => {
const deleteDir = path.join(asarDir, 'deleteme');
fs.mkdirSync(deleteDir);
const originalFs = require('original-fs');
originalFs.rmdirSync(deleteDir, { recursive: true });
expect(fs.existsSync(deleteDir)).to.be.false();
});
itremote('has the same APIs as fs', function () {
expect(Object.keys(require('node:fs'))).to.deep.equal(Object.keys(require('original-fs')));
expect(Object.keys(require('node:fs').promises)).to.deep.equal(Object.keys(require('original-fs').promises));
});
});
describe('graceful-fs module', function () {
itremote('recognize asar archives', function () {
const gfs = require('graceful-fs');
const p = path.join(asarDir, 'a.asar', 'link1');
expect(gfs.readFileSync(p).toString().trim()).to.equal('file1');
});
itremote('does not touch global fs object', function () {
const gfs = require('graceful-fs');
expect(fs.readdir).to.not.equal(gfs.readdir);
});
});
describe('mkdirp module', function () {
itremote('throws error when calling inside asar archive', function () {
const mkdirp = require('mkdirp');
const p = path.join(asarDir, 'a.asar', 'not-exist');
expect(() => {
mkdirp.sync(p);
}).to.throw(/ENOTDIR/);
});
});
describe('native-image', function () {
itremote('reads image from asar archive', function () {
const p = path.join(asarDir, 'logo.asar', 'logo.png');
const logo = require('electron').nativeImage.createFromPath(p);
expect(logo.getSize()).to.deep.equal({
width: 55,
height: 55
});
});
itremote('reads image from asar archive with unpacked files', function () {
const p = path.join(asarDir, 'unpack.asar', 'atom.png');
const logo = require('electron').nativeImage.createFromPath(p);
expect(logo.getSize()).to.deep.equal({
width: 1024,
height: 1024
});
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,211 |
[Bug]: Electron 28 breaks `import` of transitive dependencies inside ES modules
|
### 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
28.0.0-alpha.2
### What operating system are you using?
Windows
### Operating System Version
Windows 10
### What arch are you using?
x64
### Last Known Working Electron version
27.0.0
### Expected Behavior
Importing an ESM dependency which imports some other dependency (ESM or CJS) should work from inside `app.asar`
### Actual Behavior
The module lookup starts at ```node_modules/<directory where the dependency's `main` file lives>/node_modules```, doesn't find the transitive dependency there and then crashes, never reaching the top-level `node_modules` which is where the transitive dependency actually lives:

### Testcase Gist URL
_No response_
### Additional Information
I've run into this using [this repro](https://github.com/electron/asar/issues/249#issuecomment-1434998313), where the ESM dependency `got` is imported causing the app to crash when looking for the transitive ESM dependency `@sindresorhus/is`. I've put together a minimal reproduction with two local dependencies, which should make it easier to test different variables: https://github.com/erikian/esm-asar-demo
Note that this problem seems to be limited to dependencies inside `node_modules`, i.e. ESM imports across project files work fine:
```ts
// src/main.mjs
import printStuff from './printStuff.js'
printStuff('it works!')
// src/printStuff.js
import logger from './logger.js'
export default function printStuff(...stuff) {
logger(...stuff)
}
// src/logger.js
export default function logger(...args) {
console.log(...args)
}
```
Some findings:
- `const { default: printStuff } = await import('my-esm-dependency')` doesn't work out of the box, but it does work when setting `process.noAsar = true` before importing. Moving the import into the `app.whenReady` callback also doesn't work
- `import printStuff from 'my-esm-dependency'` doesn't work at all, not even with `process.noAsar = true`
- This is not limited to ESM entrypoints. I also get the same errors on the `commonjs-entrypoint` branch, and changing to Electron 27.0.0 fixes the problem.
|
https://github.com/electron/electron/issues/40211
|
https://github.com/electron/electron/pull/40221
|
f7b1c75c72a8dcab4157408f92bd3771606d8029
|
b6ec19a582579c8f7972a1c140b9404e8b2ccd87
| 2023-10-16T01:14:29Z |
c++
| 2023-10-16T16:35:25Z |
lib/asar/fs-wrapper.ts
|
import { Buffer } from 'buffer';
import { constants } from 'fs';
import * as path from 'path';
import * as util from 'util';
import type * as Crypto from 'crypto';
const asar = process._linkedBinding('electron_common_asar');
const Module = require('module') as NodeJS.ModuleInternal;
const Promise: PromiseConstructor = global.Promise;
const envNoAsar = process.env.ELECTRON_NO_ASAR &&
process.type !== 'browser' &&
process.type !== 'renderer';
const isAsarDisabled = () => process.noAsar || envNoAsar;
const internalBinding = process.internalBinding!;
delete process.internalBinding;
const nextTick = (functionToCall: Function, args: any[] = []) => {
process.nextTick(() => functionToCall(...args));
};
// Cache asar archive objects.
const cachedArchives = new Map<string, NodeJS.AsarArchive>();
const getOrCreateArchive = (archivePath: string) => {
const isCached = cachedArchives.has(archivePath);
if (isCached) {
return cachedArchives.get(archivePath)!;
}
try {
const newArchive = new asar.Archive(archivePath);
cachedArchives.set(archivePath, newArchive);
return newArchive;
} catch {
return null;
}
};
process._getOrCreateArchive = getOrCreateArchive;
const asarRe = /\.asar/i;
const { getValidatedPath } = __non_webpack_require__('internal/fs/utils');
// In the renderer node internals use the node global URL but we do not set that to be
// the global URL instance. We need to do instanceof checks against the internal URL impl
const { URL: NodeURL } = __non_webpack_require__('internal/url');
// Separate asar package's path from full path.
const splitPath = (archivePathOrBuffer: string | Buffer | URL) => {
// Shortcut for disabled asar.
if (isAsarDisabled()) return { isAsar: <const>false };
// Check for a bad argument type.
let archivePath = archivePathOrBuffer;
if (Buffer.isBuffer(archivePathOrBuffer)) {
archivePath = archivePathOrBuffer.toString();
}
if (archivePath instanceof NodeURL) {
archivePath = getValidatedPath(archivePath);
}
if (typeof archivePath !== 'string') return { isAsar: <const>false };
if (!asarRe.test(archivePath)) return { isAsar: <const>false };
return asar.splitPath(path.normalize(archivePath));
};
// Convert asar archive's Stats object to fs's Stats object.
let nextInode = 0;
const uid = process.getuid?.() ?? 0;
const gid = process.getgid?.() ?? 0;
const fakeTime = new Date();
enum AsarFileType {
kFile = (constants as any).UV_DIRENT_FILE,
kDirectory = (constants as any).UV_DIRENT_DIR,
kLink = (constants as any).UV_DIRENT_LINK,
}
const fileTypeToMode = new Map<AsarFileType, number>([
[AsarFileType.kFile, constants.S_IFREG],
[AsarFileType.kDirectory, constants.S_IFDIR],
[AsarFileType.kLink, constants.S_IFLNK]
]);
const asarStatsToFsStats = function (stats: NodeJS.AsarFileStat) {
const { Stats } = require('fs');
const mode = constants.S_IROTH | constants.S_IRGRP | constants.S_IRUSR | constants.S_IWUSR | fileTypeToMode.get(stats.type)!;
return new Stats(
1, // dev
mode, // mode
1, // nlink
uid,
gid,
0, // rdev
undefined, // blksize
++nextInode, // ino
stats.size,
undefined, // blocks,
fakeTime.getTime(), // atim_msec
fakeTime.getTime(), // mtim_msec
fakeTime.getTime(), // ctim_msec
fakeTime.getTime() // birthtim_msec
);
};
const enum AsarError {
NOT_FOUND = 'NOT_FOUND',
NOT_DIR = 'NOT_DIR',
NO_ACCESS = 'NO_ACCESS',
INVALID_ARCHIVE = 'INVALID_ARCHIVE'
}
type AsarErrorObject = Error & { code?: string, errno?: number };
const createError = (errorType: AsarError, { asarPath, filePath }: { asarPath?: string, filePath?: string } = {}) => {
let error: AsarErrorObject;
switch (errorType) {
case AsarError.NOT_FOUND:
error = new Error(`ENOENT, ${filePath} not found in ${asarPath}`);
error.code = 'ENOENT';
error.errno = -2;
break;
case AsarError.NOT_DIR:
error = new Error('ENOTDIR, not a directory');
error.code = 'ENOTDIR';
error.errno = -20;
break;
case AsarError.NO_ACCESS:
error = new Error(`EACCES: permission denied, access '${filePath}'`);
error.code = 'EACCES';
error.errno = -13;
break;
case AsarError.INVALID_ARCHIVE:
error = new Error(`Invalid package ${asarPath}`);
break;
default:
throw new Error(`Invalid error type "${errorType}" passed to createError.`);
}
return error;
};
const overrideAPISync = function (module: Record<string, any>, name: string, pathArgumentIndex?: number | null, fromAsync: boolean = false) {
if (pathArgumentIndex == null) pathArgumentIndex = 0;
const old = module[name];
const func = function (this: any, ...args: any[]) {
const pathArgument = args[pathArgumentIndex!];
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return old.apply(this, args);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
const newPath = archive.copyFileOut(filePath);
if (!newPath) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
args[pathArgumentIndex!] = newPath;
return old.apply(this, args);
};
if (fromAsync) {
return func;
}
module[name] = func;
};
const overrideAPI = function (module: Record<string, any>, name: string, pathArgumentIndex?: number | null) {
if (pathArgumentIndex == null) pathArgumentIndex = 0;
const old = module[name];
module[name] = function (this: any, ...args: any[]) {
const pathArgument = args[pathArgumentIndex!];
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return old.apply(this, args);
const { asarPath, filePath } = pathInfo;
const callback = args[args.length - 1];
if (typeof callback !== 'function') {
return overrideAPISync(module, name, pathArgumentIndex!, true)!.apply(this, args);
}
const archive = getOrCreateArchive(asarPath);
if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
nextTick(callback, [error]);
return;
}
const newPath = archive.copyFileOut(filePath);
if (!newPath) {
const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
nextTick(callback, [error]);
return;
}
args[pathArgumentIndex!] = newPath;
return old.apply(this, args);
};
if (old[util.promisify.custom]) {
module[name][util.promisify.custom] = makePromiseFunction(old[util.promisify.custom], pathArgumentIndex);
}
if (module.promises && module.promises[name]) {
module.promises[name] = makePromiseFunction(module.promises[name], pathArgumentIndex);
}
};
let crypto: typeof Crypto;
function validateBufferIntegrity (buffer: Buffer, integrity: NodeJS.AsarFileInfo['integrity']) {
if (!integrity) return;
// Delay load crypto to improve app boot performance
// when integrity protection is not enabled
crypto = crypto || require('crypto');
const actual = crypto.createHash(integrity.algorithm).update(buffer).digest('hex');
if (actual !== integrity.hash) {
console.error(`ASAR Integrity Violation: got a hash mismatch (${actual} vs ${integrity.hash})`);
process.exit(1);
}
}
const makePromiseFunction = function (orig: Function, pathArgumentIndex: number) {
return function (this: any, ...args: any[]) {
const pathArgument = args[pathArgumentIndex];
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return orig.apply(this, args);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) {
return Promise.reject(createError(AsarError.INVALID_ARCHIVE, { asarPath }));
}
const newPath = archive.copyFileOut(filePath);
if (!newPath) {
return Promise.reject(createError(AsarError.NOT_FOUND, { asarPath, filePath }));
}
args[pathArgumentIndex] = newPath;
return orig.apply(this, args);
};
};
// Override fs APIs.
export const wrapFsWithAsar = (fs: Record<string, any>) => {
const logFDs = new Map<string, number>();
const logASARAccess = (asarPath: string, filePath: string, offset: number) => {
if (!process.env.ELECTRON_LOG_ASAR_READS) return;
if (!logFDs.has(asarPath)) {
const logFilename = `${path.basename(asarPath, '.asar')}-access-log.txt`;
const logPath = path.join(require('os').tmpdir(), logFilename);
logFDs.set(asarPath, fs.openSync(logPath, 'a'));
}
fs.writeSync(logFDs.get(asarPath), `${offset}: ${filePath}\n`);
};
const { lstatSync } = fs;
fs.lstatSync = (pathArgument: string, options: any) => {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return lstatSync(pathArgument, options);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
const stats = archive.stat(filePath);
if (!stats) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
return asarStatsToFsStats(stats);
};
const { lstat } = fs;
fs.lstat = (pathArgument: string, options: any, callback: any) => {
const pathInfo = splitPath(pathArgument);
if (typeof options === 'function') {
callback = options;
options = {};
}
if (!pathInfo.isAsar) return lstat(pathArgument, options, callback);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
nextTick(callback, [error]);
return;
}
const stats = archive.stat(filePath);
if (!stats) {
const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
nextTick(callback, [error]);
return;
}
const fsStats = asarStatsToFsStats(stats);
nextTick(callback, [null, fsStats]);
};
fs.promises.lstat = util.promisify(fs.lstat);
const { statSync } = fs;
fs.statSync = (pathArgument: string, options: any) => {
const { isAsar } = splitPath(pathArgument);
if (!isAsar) return statSync(pathArgument, options);
// Do not distinguish links for now.
return fs.lstatSync(pathArgument, options);
};
const { stat } = fs;
fs.stat = (pathArgument: string, options: any, callback: any) => {
const { isAsar } = splitPath(pathArgument);
if (typeof options === 'function') {
callback = options;
options = {};
}
if (!isAsar) return stat(pathArgument, options, callback);
// Do not distinguish links for now.
process.nextTick(() => fs.lstat(pathArgument, options, callback));
};
fs.promises.stat = util.promisify(fs.stat);
const wrapRealpathSync = function (realpathSync: Function) {
return function (this: any, pathArgument: string, options: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return realpathSync.apply(this, arguments);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) {
throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
}
const fileRealPath = archive.realpath(filePath);
if (fileRealPath === false) {
throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
}
return path.join(realpathSync(asarPath, options), fileRealPath);
};
};
const { realpathSync } = fs;
fs.realpathSync = wrapRealpathSync(realpathSync);
fs.realpathSync.native = wrapRealpathSync(realpathSync.native);
const wrapRealpath = function (realpath: Function) {
return function (this: any, pathArgument: string, options: any, callback: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return realpath.apply(this, arguments);
const { asarPath, filePath } = pathInfo;
if (arguments.length < 3) {
callback = options;
options = {};
}
const archive = getOrCreateArchive(asarPath);
if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
nextTick(callback, [error]);
return;
}
const fileRealPath = archive.realpath(filePath);
if (fileRealPath === false) {
const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
nextTick(callback, [error]);
return;
}
realpath(asarPath, options, (error: Error | null, archiveRealPath: string) => {
if (error === null) {
const fullPath = path.join(archiveRealPath, fileRealPath);
callback(null, fullPath);
} else {
callback(error);
}
});
};
};
const { realpath } = fs;
fs.realpath = wrapRealpath(realpath);
fs.realpath.native = wrapRealpath(realpath.native);
fs.promises.realpath = util.promisify(fs.realpath.native);
const { exists: nativeExists } = fs;
fs.exists = function exists (pathArgument: string, callback: any) {
let pathInfo: ReturnType<typeof splitPath>;
try {
pathInfo = splitPath(pathArgument);
} catch {
nextTick(callback, [false]);
return;
}
if (!pathInfo.isAsar) return nativeExists(pathArgument, callback);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
nextTick(callback, [error]);
return;
}
const pathExists = (archive.stat(filePath) !== false);
nextTick(callback, [pathExists]);
};
fs.exists[util.promisify.custom] = function exists (pathArgument: string) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return nativeExists[util.promisify.custom](pathArgument);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
return Promise.reject(error);
}
return Promise.resolve(archive.stat(filePath) !== false);
};
const { existsSync } = fs;
fs.existsSync = (pathArgument: string) => {
let pathInfo: ReturnType<typeof splitPath>;
try {
pathInfo = splitPath(pathArgument);
} catch {
return false;
}
if (!pathInfo.isAsar) return existsSync(pathArgument);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) return false;
return archive.stat(filePath) !== false;
};
const { access } = fs;
fs.access = function (pathArgument: string, mode: any, callback: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return access.apply(this, arguments);
const { asarPath, filePath } = pathInfo;
if (typeof mode === 'function') {
callback = mode;
mode = fs.constants.F_OK;
}
const archive = getOrCreateArchive(asarPath);
if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
nextTick(callback, [error]);
return;
}
const info = archive.getFileInfo(filePath);
if (!info) {
const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
nextTick(callback, [error]);
return;
}
if (info.unpacked) {
const realPath = archive.copyFileOut(filePath);
return fs.access(realPath, mode, callback);
}
const stats = archive.stat(filePath);
if (!stats) {
const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
nextTick(callback, [error]);
return;
}
if (mode & fs.constants.W_OK) {
const error = createError(AsarError.NO_ACCESS, { asarPath, filePath });
nextTick(callback, [error]);
return;
}
nextTick(callback);
};
fs.promises.access = util.promisify(fs.access);
const { accessSync } = fs;
fs.accessSync = function (pathArgument: string, mode: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return accessSync.apply(this, arguments);
const { asarPath, filePath } = pathInfo;
if (mode == null) mode = fs.constants.F_OK;
const archive = getOrCreateArchive(asarPath);
if (!archive) {
throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
}
const info = archive.getFileInfo(filePath);
if (!info) {
throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
}
if (info.unpacked) {
const realPath = archive.copyFileOut(filePath);
return fs.accessSync(realPath, mode);
}
const stats = archive.stat(filePath);
if (!stats) {
throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
}
if (mode & fs.constants.W_OK) {
throw createError(AsarError.NO_ACCESS, { asarPath, filePath });
}
};
function fsReadFileAsar (pathArgument: string, options: any, callback: any) {
const pathInfo = splitPath(pathArgument);
if (pathInfo.isAsar) {
const { asarPath, filePath } = pathInfo;
if (typeof options === 'function') {
callback = options;
options = { encoding: null };
} else if (typeof options === 'string') {
options = { encoding: options };
} else if (options === null || options === undefined) {
options = { encoding: null };
} else if (typeof options !== 'object') {
throw new TypeError('Bad arguments');
}
const { encoding } = options;
const archive = getOrCreateArchive(asarPath);
if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
nextTick(callback, [error]);
return;
}
const info = archive.getFileInfo(filePath);
if (!info) {
const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
nextTick(callback, [error]);
return;
}
if (info.size === 0) {
nextTick(callback, [null, encoding ? '' : Buffer.alloc(0)]);
return;
}
if (info.unpacked) {
const realPath = archive.copyFileOut(filePath);
return fs.readFile(realPath, options, callback);
}
const buffer = Buffer.alloc(info.size);
const fd = archive.getFdAndValidateIntegrityLater();
if (!(fd >= 0)) {
const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
nextTick(callback, [error]);
return;
}
logASARAccess(asarPath, filePath, info.offset);
fs.read(fd, buffer, 0, info.size, info.offset, (error: Error) => {
validateBufferIntegrity(buffer, info.integrity);
callback(error, encoding ? buffer.toString(encoding) : buffer);
});
}
}
const { readFile } = fs;
fs.readFile = function (pathArgument: string, options: any, callback: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) {
return readFile.apply(this, arguments);
}
return fsReadFileAsar(pathArgument, options, callback);
};
const { readFile: readFilePromise } = fs.promises;
fs.promises.readFile = function (pathArgument: string, options: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) {
return readFilePromise.apply(this, arguments);
}
const p = util.promisify(fsReadFileAsar);
return p(pathArgument, options);
};
const { readFileSync } = fs;
fs.readFileSync = function (pathArgument: string, options: any) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return readFileSync.apply(this, arguments);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
const info = archive.getFileInfo(filePath);
if (!info) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
if (info.size === 0) return (options) ? '' : Buffer.alloc(0);
if (info.unpacked) {
const realPath = archive.copyFileOut(filePath);
return fs.readFileSync(realPath, options);
}
if (!options) {
options = { encoding: null };
} else if (typeof options === 'string') {
options = { encoding: options };
} else if (typeof options !== 'object') {
throw new TypeError('Bad arguments');
}
const { encoding } = options;
const buffer = Buffer.alloc(info.size);
const fd = archive.getFdAndValidateIntegrityLater();
if (!(fd >= 0)) throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
logASARAccess(asarPath, filePath, info.offset);
fs.readSync(fd, buffer, 0, info.size, info.offset);
validateBufferIntegrity(buffer, info.integrity);
return (encoding) ? buffer.toString(encoding) : buffer;
};
const { readdir } = fs;
fs.readdir = function (pathArgument: string, options?: { encoding?: string | null; withFileTypes?: boolean } | null, callback?: Function) {
const pathInfo = splitPath(pathArgument);
if (typeof options === 'function') {
callback = options;
options = undefined;
}
if (!pathInfo.isAsar) return readdir.apply(this, arguments);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) {
const error = createError(AsarError.INVALID_ARCHIVE, { asarPath });
nextTick(callback!, [error]);
return;
}
const files = archive.readdir(filePath);
if (!files) {
const error = createError(AsarError.NOT_FOUND, { asarPath, filePath });
nextTick(callback!, [error]);
return;
}
if (options?.withFileTypes) {
const dirents = [];
for (const file of files) {
const childPath = path.join(filePath, file);
const stats = archive.stat(childPath);
if (!stats) {
const error = createError(AsarError.NOT_FOUND, { asarPath, filePath: childPath });
nextTick(callback!, [error]);
return;
}
dirents.push(new fs.Dirent(file, stats.type));
}
nextTick(callback!, [null, dirents]);
return;
}
nextTick(callback!, [null, files]);
};
fs.promises.readdir = util.promisify(fs.readdir);
type ReaddirSyncOptions = { encoding: BufferEncoding | null; withFileTypes?: false };
const { readdirSync } = fs;
fs.readdirSync = function (pathArgument: string, options: ReaddirSyncOptions | BufferEncoding | null) {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return readdirSync.apply(this, arguments);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) {
throw createError(AsarError.INVALID_ARCHIVE, { asarPath });
}
const files = archive.readdir(filePath);
if (!files) {
throw createError(AsarError.NOT_FOUND, { asarPath, filePath });
}
if (options && (options as ReaddirSyncOptions).withFileTypes) {
const dirents = [];
for (const file of files) {
const childPath = path.join(filePath, file);
const stats = archive.stat(childPath);
if (!stats) {
throw createError(AsarError.NOT_FOUND, { asarPath, filePath: childPath });
}
dirents.push(new fs.Dirent(file, stats.type));
}
return dirents;
}
return files;
};
const { internalModuleReadJSON } = internalBinding('fs');
internalBinding('fs').internalModuleReadJSON = (pathArgument: string) => {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return internalModuleReadJSON(pathArgument);
const { asarPath, filePath } = pathInfo;
const archive = getOrCreateArchive(asarPath);
if (!archive) return [];
const info = archive.getFileInfo(filePath);
if (!info) return [];
if (info.size === 0) return ['', false];
if (info.unpacked) {
const realPath = archive.copyFileOut(filePath);
const str = fs.readFileSync(realPath, { encoding: 'utf8' });
return [str, str.length > 0];
}
const buffer = Buffer.alloc(info.size);
const fd = archive.getFdAndValidateIntegrityLater();
if (!(fd >= 0)) return [];
logASARAccess(asarPath, filePath, info.offset);
fs.readSync(fd, buffer, 0, info.size, info.offset);
validateBufferIntegrity(buffer, info.integrity);
const str = buffer.toString('utf8');
return [str, str.length > 0];
};
const { internalModuleStat } = internalBinding('fs');
internalBinding('fs').internalModuleStat = (pathArgument: string) => {
const pathInfo = splitPath(pathArgument);
if (!pathInfo.isAsar) return internalModuleStat(pathArgument);
const { asarPath, filePath } = pathInfo;
// -ENOENT
const archive = getOrCreateArchive(asarPath);
if (!archive) return -34;
// -ENOENT
const stats = archive.stat(filePath);
if (!stats) return -34;
return (stats.type === AsarFileType.kDirectory) ? 1 : 0;
};
// Calling mkdir for directory inside asar archive should throw ENOTDIR
// error, but on Windows it throws ENOENT.
if (process.platform === 'win32') {
const { mkdir } = fs;
fs.mkdir = (pathArgument: string, options: any, callback: any) => {
if (typeof options === 'function') {
callback = options;
options = {};
}
const pathInfo = splitPath(pathArgument);
if (pathInfo.isAsar && pathInfo.filePath.length > 0) {
const error = createError(AsarError.NOT_DIR);
nextTick(callback, [error]);
return;
}
mkdir(pathArgument, options, callback);
};
fs.promises.mkdir = util.promisify(fs.mkdir);
const { mkdirSync } = fs;
fs.mkdirSync = function (pathArgument: string, options: any) {
const pathInfo = splitPath(pathArgument);
if (pathInfo.isAsar && pathInfo.filePath.length) throw createError(AsarError.NOT_DIR);
return mkdirSync(pathArgument, options);
};
}
function invokeWithNoAsar (func: Function) {
return function (this: any) {
const processNoAsarOriginalValue = process.noAsar;
process.noAsar = true;
try {
return func.apply(this, arguments);
} finally {
process.noAsar = processNoAsarOriginalValue;
}
};
}
// Strictly implementing the flags of fs.copyFile is hard, just do a simple
// implementation for now. Doing 2 copies won't spend much time more as OS
// has filesystem caching.
overrideAPI(fs, 'copyFile');
overrideAPISync(fs, 'copyFileSync');
overrideAPI(fs, 'open');
overrideAPISync(process, 'dlopen', 1);
overrideAPISync(Module._extensions, '.node', 1);
overrideAPISync(fs, 'openSync');
const overrideChildProcess = (childProcess: Record<string, any>) => {
// Executing a command string containing a path to an asar archive
// confuses `childProcess.execFile`, which is internally called by
// `childProcess.{exec,execSync}`, causing Electron to consider the full
// command as a single path to an archive.
const { exec, execSync } = childProcess;
childProcess.exec = invokeWithNoAsar(exec);
childProcess.exec[util.promisify.custom] = invokeWithNoAsar(exec[util.promisify.custom]);
childProcess.execSync = invokeWithNoAsar(execSync);
overrideAPI(childProcess, 'execFile');
overrideAPISync(childProcess, 'execFileSync');
};
const asarReady = new WeakSet();
// Lazily override the child_process APIs only when child_process is
// fetched the first time. We will eagerly override the child_process APIs
// when this env var is set so that stack traces generated inside node unit
// tests will match. This env var will only slow things down in users apps
// and should not be used.
if (process.env.ELECTRON_EAGER_ASAR_HOOK_FOR_TESTING) {
overrideChildProcess(require('child_process'));
} else {
const originalModuleLoad = Module._load;
Module._load = (request: string, ...args: any[]) => {
const loadResult = originalModuleLoad(request, ...args);
if (request === 'child_process' || request === 'node:child_process') {
if (!asarReady.has(loadResult)) {
asarReady.add(loadResult);
// Just to make it obvious what we are dealing with here
const childProcess = loadResult;
overrideChildProcess(childProcess);
}
}
return loadResult;
};
}
};
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,211 |
[Bug]: Electron 28 breaks `import` of transitive dependencies inside ES modules
|
### 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
28.0.0-alpha.2
### What operating system are you using?
Windows
### Operating System Version
Windows 10
### What arch are you using?
x64
### Last Known Working Electron version
27.0.0
### Expected Behavior
Importing an ESM dependency which imports some other dependency (ESM or CJS) should work from inside `app.asar`
### Actual Behavior
The module lookup starts at ```node_modules/<directory where the dependency's `main` file lives>/node_modules```, doesn't find the transitive dependency there and then crashes, never reaching the top-level `node_modules` which is where the transitive dependency actually lives:

### Testcase Gist URL
_No response_
### Additional Information
I've run into this using [this repro](https://github.com/electron/asar/issues/249#issuecomment-1434998313), where the ESM dependency `got` is imported causing the app to crash when looking for the transitive ESM dependency `@sindresorhus/is`. I've put together a minimal reproduction with two local dependencies, which should make it easier to test different variables: https://github.com/erikian/esm-asar-demo
Note that this problem seems to be limited to dependencies inside `node_modules`, i.e. ESM imports across project files work fine:
```ts
// src/main.mjs
import printStuff from './printStuff.js'
printStuff('it works!')
// src/printStuff.js
import logger from './logger.js'
export default function printStuff(...stuff) {
logger(...stuff)
}
// src/logger.js
export default function logger(...args) {
console.log(...args)
}
```
Some findings:
- `const { default: printStuff } = await import('my-esm-dependency')` doesn't work out of the box, but it does work when setting `process.noAsar = true` before importing. Moving the import into the `app.whenReady` callback also doesn't work
- `import printStuff from 'my-esm-dependency'` doesn't work at all, not even with `process.noAsar = true`
- This is not limited to ESM entrypoints. I also get the same errors on the `commonjs-entrypoint` branch, and changing to Electron 27.0.0 fixes the problem.
|
https://github.com/electron/electron/issues/40211
|
https://github.com/electron/electron/pull/40221
|
f7b1c75c72a8dcab4157408f92bd3771606d8029
|
b6ec19a582579c8f7972a1c140b9404e8b2ccd87
| 2023-10-16T01:14:29Z |
c++
| 2023-10-16T16:35:25Z |
spec/asar-spec.ts
|
import { expect } from 'chai';
import * as path from 'node:path';
import * as url from 'node:url';
import { Worker } from 'node:worker_threads';
import { BrowserWindow, ipcMain } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import { getRemoteContext, ifdescribe, ifit, itremote, useRemoteContext } from './lib/spec-helpers';
import * as importedFs from 'node:fs';
import { once } from 'node:events';
describe('asar package', () => {
const fixtures = path.join(__dirname, 'fixtures');
const asarDir = path.join(fixtures, 'test.asar');
afterEach(closeAllWindows);
describe('asar protocol', () => {
it('sets __dirname correctly', async function () {
after(function () {
ipcMain.removeAllListeners('dirname');
});
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
const p = path.resolve(asarDir, 'web.asar', 'index.html');
const dirnameEvent = once(ipcMain, 'dirname');
w.loadFile(p);
const [, dirname] = await dirnameEvent;
expect(dirname).to.equal(path.dirname(p));
});
it('loads script tag in html', async function () {
after(function () {
ipcMain.removeAllListeners('ping');
});
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
const p = path.resolve(asarDir, 'script.asar', 'index.html');
const ping = once(ipcMain, 'ping');
w.loadFile(p);
const [, message] = await ping;
expect(message).to.equal('pong');
});
it('loads video tag in html', async function () {
this.timeout(60000);
after(function () {
ipcMain.removeAllListeners('asar-video');
});
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
const p = path.resolve(asarDir, 'video.asar', 'index.html');
w.loadFile(p);
const [, message, error] = await once(ipcMain, 'asar-video');
if (message === 'ended') {
expect(error).to.be.null();
} else if (message === 'error') {
throw new Error(error);
}
});
});
describe('worker', () => {
it('Worker can load asar file', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'workers', 'load_worker.html'));
const workerUrl = url.format({
pathname: path.resolve(fixtures, 'workers', 'workers.asar', 'worker.js').replaceAll('\\', '/'),
protocol: 'file',
slashes: true
});
const result = await w.webContents.executeJavaScript(`loadWorker('${workerUrl}')`);
expect(result).to.equal('success');
});
it('SharedWorker can load asar file', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'workers', 'load_shared_worker.html'));
const workerUrl = url.format({
pathname: path.resolve(fixtures, 'workers', 'workers.asar', 'shared_worker.js').replaceAll('\\', '/'),
protocol: 'file',
slashes: true
});
const result = await w.webContents.executeJavaScript(`loadSharedWorker('${workerUrl}')`);
expect(result).to.equal('success');
});
});
describe('worker threads', function () {
// DISABLED-FIXME(#38192): only disabled for ASan.
ifit(!process.env.IS_ASAN)('should start worker thread from asar file', function (callback) {
const p = path.join(asarDir, 'worker_threads.asar', 'worker.js');
const w = new Worker(p);
w.on('error', (err) => callback(err));
w.on('message', (message) => {
expect(message).to.equal('ping');
w.terminate();
callback(null);
});
});
});
});
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async function expectToThrowErrorWithCode (_func: Function, _code: string) {
/* dummy for typescript */
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function promisify (_f: Function): any {
/* dummy for typescript */
}
describe('asar package', function () {
const fixtures = path.join(__dirname, 'fixtures');
const asarDir = path.join(fixtures, 'test.asar');
const fs = require('node:fs') as typeof importedFs; // dummy, to fool typescript
useRemoteContext({
url: url.pathToFileURL(path.join(fixtures, 'pages', 'blank.html')),
setup: `
async function expectToThrowErrorWithCode (func, code) {
let error;
try {
await func();
} catch (e) {
error = e;
}
const chai = require('chai')
chai.expect(error).to.have.property('code').which.equals(code);
}
fs = require('node:fs')
path = require('node:path')
asarDir = ${JSON.stringify(asarDir)}
// This is used instead of util.promisify for some tests to dodge the
// util.promisify.custom behavior.
promisify = (f) => {
return (...args) => new Promise((resolve, reject) => {
f(...args, (err, result) => {
if (err) reject(err)
else resolve(result)
})
})
}
null
`
});
describe('node api', function () {
itremote('supports paths specified as a Buffer', function () {
const file = Buffer.from(path.join(asarDir, 'a.asar', 'file1'));
expect(fs.existsSync(file)).to.be.true();
});
describe('fs.readFileSync', function () {
itremote('does not leak fd', function () {
let readCalls = 1;
while (readCalls <= 10000) {
fs.readFileSync(path.join(process.resourcesPath, 'default_app.asar', 'main.js'));
readCalls++;
}
});
itremote('reads a normal file', function () {
const file1 = path.join(asarDir, 'a.asar', 'file1');
expect(fs.readFileSync(file1).toString().trim()).to.equal('file1');
const file2 = path.join(asarDir, 'a.asar', 'file2');
expect(fs.readFileSync(file2).toString().trim()).to.equal('file2');
const file3 = path.join(asarDir, 'a.asar', 'file3');
expect(fs.readFileSync(file3).toString().trim()).to.equal('file3');
});
itremote('reads from a empty file', function () {
const file = path.join(asarDir, 'empty.asar', 'file1');
const buffer = fs.readFileSync(file);
expect(buffer).to.be.empty();
expect(buffer.toString()).to.equal('');
});
itremote('reads a linked file', function () {
const p = path.join(asarDir, 'a.asar', 'link1');
expect(fs.readFileSync(p).toString().trim()).to.equal('file1');
});
itremote('reads a file from linked directory', function () {
const p1 = path.join(asarDir, 'a.asar', 'link2', 'file1');
expect(fs.readFileSync(p1).toString().trim()).to.equal('file1');
const p2 = path.join(asarDir, 'a.asar', 'link2', 'link2', 'file1');
expect(fs.readFileSync(p2).toString().trim()).to.equal('file1');
});
itremote('throws ENOENT error when can not find file', function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
expect(() => {
fs.readFileSync(p);
}).to.throw(/ENOENT/);
});
itremote('passes ENOENT error to callback when can not find file', function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
let async = false;
fs.readFile(p, function (error) {
expect(async).to.be.true();
expect(error).to.match(/ENOENT/);
});
async = true;
});
itremote('reads a normal file with unpacked files', function () {
const p = path.join(asarDir, 'unpack.asar', 'a.txt');
expect(fs.readFileSync(p).toString().trim()).to.equal('a');
});
itremote('reads a file in filesystem', function () {
const p = path.resolve(asarDir, 'file');
expect(fs.readFileSync(p).toString().trim()).to.equal('file');
});
});
describe('fs.readFile', function () {
itremote('reads a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
const content = await new Promise((resolve, reject) => fs.readFile(p, (err, content) => {
if (err) return reject(err);
resolve(content);
}));
expect(String(content).trim()).to.equal('file1');
});
itremote('reads from a empty file', async function () {
const p = path.join(asarDir, 'empty.asar', 'file1');
const content = await new Promise((resolve, reject) => fs.readFile(p, (err, content) => {
if (err) return reject(err);
resolve(content);
}));
expect(String(content)).to.equal('');
});
itremote('reads from a empty file with encoding', async function () {
const p = path.join(asarDir, 'empty.asar', 'file1');
const content = await new Promise((resolve, reject) => fs.readFile(p, (err, content) => {
if (err) return reject(err);
resolve(content);
}));
expect(String(content)).to.equal('');
});
itremote('reads a linked file', async function () {
const p = path.join(asarDir, 'a.asar', 'link1');
const content = await new Promise((resolve, reject) => fs.readFile(p, (err, content) => {
if (err) return reject(err);
resolve(content);
}));
expect(String(content).trim()).to.equal('file1');
});
itremote('reads a file from linked directory', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2', 'file1');
const content = await new Promise((resolve, reject) => fs.readFile(p, (err, content) => {
if (err) return reject(err);
resolve(content);
}));
expect(String(content).trim()).to.equal('file1');
});
itremote('throws ENOENT error when can not find file', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
const err = await new Promise<any>((resolve) => fs.readFile(p, resolve));
expect(err.code).to.equal('ENOENT');
});
});
describe('fs.promises.readFile', function () {
itremote('reads a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
const content = await fs.promises.readFile(p);
expect(String(content).trim()).to.equal('file1');
});
itremote('reads from a empty file', async function () {
const p = path.join(asarDir, 'empty.asar', 'file1');
const content = await fs.promises.readFile(p);
expect(String(content)).to.equal('');
});
itremote('reads from a empty file with encoding', async function () {
const p = path.join(asarDir, 'empty.asar', 'file1');
const content = await fs.promises.readFile(p, 'utf8');
expect(content).to.equal('');
});
itremote('reads a linked file', async function () {
const p = path.join(asarDir, 'a.asar', 'link1');
const content = await fs.promises.readFile(p);
expect(String(content).trim()).to.equal('file1');
});
itremote('reads a file from linked directory', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2', 'file1');
const content = await fs.promises.readFile(p);
expect(String(content).trim()).to.equal('file1');
});
itremote('throws ENOENT error when can not find file', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
await expectToThrowErrorWithCode(() => fs.promises.readFile(p), 'ENOENT');
});
});
describe('fs.copyFile', function () {
itremote('copies a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
const temp = require('temp').track();
const dest = temp.path();
await new Promise<void>((resolve, reject) => {
fs.copyFile(p, dest, (err) => {
if (err) reject(err);
else resolve();
});
});
expect(fs.readFileSync(p).equals(fs.readFileSync(dest))).to.be.true();
});
itremote('copies a unpacked file', async function () {
const p = path.join(asarDir, 'unpack.asar', 'a.txt');
const temp = require('temp').track();
const dest = temp.path();
await new Promise<void>((resolve, reject) => {
fs.copyFile(p, dest, (err) => {
if (err) reject(err);
else resolve();
});
});
expect(fs.readFileSync(p).equals(fs.readFileSync(dest))).to.be.true();
});
});
describe('fs.promises.copyFile', function () {
itremote('copies a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
const temp = require('temp').track();
const dest = temp.path();
await fs.promises.copyFile(p, dest);
expect(fs.readFileSync(p).equals(fs.readFileSync(dest))).to.be.true();
});
itremote('copies a unpacked file', async function () {
const p = path.join(asarDir, 'unpack.asar', 'a.txt');
const temp = require('temp').track();
const dest = temp.path();
await fs.promises.copyFile(p, dest);
expect(fs.readFileSync(p).equals(fs.readFileSync(dest))).to.be.true();
});
});
describe('fs.copyFileSync', function () {
itremote('copies a normal file', function () {
const p = path.join(asarDir, 'a.asar', 'file1');
const temp = require('temp').track();
const dest = temp.path();
fs.copyFileSync(p, dest);
expect(fs.readFileSync(p).equals(fs.readFileSync(dest))).to.be.true();
});
itremote('copies a unpacked file', function () {
const p = path.join(asarDir, 'unpack.asar', 'a.txt');
const temp = require('temp').track();
const dest = temp.path();
fs.copyFileSync(p, dest);
expect(fs.readFileSync(p).equals(fs.readFileSync(dest))).to.be.true();
});
});
describe('fs.lstatSync', function () {
itremote('handles path with trailing slash correctly', function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2', 'file1');
fs.lstatSync(p);
fs.lstatSync(p + '/');
});
itremote('returns information of root', function () {
const p = path.join(asarDir, 'a.asar');
const stats = fs.lstatSync(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.true();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(0);
});
itremote('returns information of root with stats as bigint', function () {
const p = path.join(asarDir, 'a.asar');
const stats = fs.lstatSync(p, { bigint: false });
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.true();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(0);
});
itremote('returns information of a normal file', function () {
const ref2 = ['file1', 'file2', 'file3', path.join('dir1', 'file1'), path.join('link2', 'file1')];
for (let j = 0, len = ref2.length; j < len; j++) {
const file = ref2[j];
const p = path.join(asarDir, 'a.asar', file);
const stats = fs.lstatSync(p);
expect(stats.isFile()).to.be.true();
expect(stats.isDirectory()).to.be.false();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(6);
}
});
itremote('returns information of a normal directory', function () {
const ref2 = ['dir1', 'dir2', 'dir3'];
for (let j = 0, len = ref2.length; j < len; j++) {
const file = ref2[j];
const p = path.join(asarDir, 'a.asar', file);
const stats = fs.lstatSync(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.true();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(0);
}
});
itremote('returns information of a linked file', function () {
const ref2 = ['link1', path.join('dir1', 'link1'), path.join('link2', 'link2')];
for (let j = 0, len = ref2.length; j < len; j++) {
const file = ref2[j];
const p = path.join(asarDir, 'a.asar', file);
const stats = fs.lstatSync(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.false();
expect(stats.isSymbolicLink()).to.be.true();
expect(stats.size).to.equal(0);
}
});
itremote('returns information of a linked directory', function () {
const ref2 = ['link2', path.join('dir1', 'link2'), path.join('link2', 'link2')];
for (let j = 0, len = ref2.length; j < len; j++) {
const file = ref2[j];
const p = path.join(asarDir, 'a.asar', file);
const stats = fs.lstatSync(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.false();
expect(stats.isSymbolicLink()).to.be.true();
expect(stats.size).to.equal(0);
}
});
itremote('throws ENOENT error when can not find file', function () {
const ref2 = ['file4', 'file5', path.join('dir1', 'file4')];
for (let j = 0, len = ref2.length; j < len; j++) {
const file = ref2[j];
const p = path.join(asarDir, 'a.asar', file);
expect(() => {
fs.lstatSync(p);
}).to.throw(/ENOENT/);
}
});
});
describe('fs.lstat', function () {
itremote('handles path with trailing slash correctly', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2', 'file1');
await promisify(fs.lstat)(p + '/');
});
itremote('returns information of root', async function () {
const p = path.join(asarDir, 'a.asar');
const stats = await promisify(fs.lstat)(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.true();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(0);
});
itremote('returns information of root with stats as bigint', async function () {
const p = path.join(asarDir, 'a.asar');
const stats = await promisify(fs.lstat)(p, { bigint: false });
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.true();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(0);
});
itremote('returns information of a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'file1');
const stats = await promisify(fs.lstat)(p);
expect(stats.isFile()).to.be.true();
expect(stats.isDirectory()).to.be.false();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(6);
});
itremote('returns information of a normal directory', async function () {
const p = path.join(asarDir, 'a.asar', 'dir1');
const stats = await promisify(fs.lstat)(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.true();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(0);
});
itremote('returns information of a linked file', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link1');
const stats = await promisify(fs.lstat)(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.false();
expect(stats.isSymbolicLink()).to.be.true();
expect(stats.size).to.equal(0);
});
itremote('returns information of a linked directory', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2');
const stats = await promisify(fs.lstat)(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.false();
expect(stats.isSymbolicLink()).to.be.true();
expect(stats.size).to.equal(0);
});
itremote('throws ENOENT error when can not find file', async function () {
const p = path.join(asarDir, 'a.asar', 'file4');
const err = await new Promise<any>(resolve => fs.lstat(p, resolve));
expect(err.code).to.equal('ENOENT');
});
});
describe('fs.promises.lstat', function () {
itremote('handles path with trailing slash correctly', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2', 'file1');
await fs.promises.lstat(p + '/');
});
itremote('returns information of root', async function () {
const p = path.join(asarDir, 'a.asar');
const stats = await fs.promises.lstat(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.true();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(0);
});
itremote('returns information of root with stats as bigint', async function () {
const p = path.join(asarDir, 'a.asar');
const stats = await fs.promises.lstat(p, { bigint: false });
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.true();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(0);
});
itremote('returns information of a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'file1');
const stats = await fs.promises.lstat(p);
expect(stats.isFile()).to.be.true();
expect(stats.isDirectory()).to.be.false();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(6);
});
itremote('returns information of a normal directory', async function () {
const p = path.join(asarDir, 'a.asar', 'dir1');
const stats = await fs.promises.lstat(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.true();
expect(stats.isSymbolicLink()).to.be.false();
expect(stats.size).to.equal(0);
});
itremote('returns information of a linked file', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link1');
const stats = await fs.promises.lstat(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.false();
expect(stats.isSymbolicLink()).to.be.true();
expect(stats.size).to.equal(0);
});
itremote('returns information of a linked directory', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2');
const stats = await fs.promises.lstat(p);
expect(stats.isFile()).to.be.false();
expect(stats.isDirectory()).to.be.false();
expect(stats.isSymbolicLink()).to.be.true();
expect(stats.size).to.equal(0);
});
itremote('throws ENOENT error when can not find file', async function () {
const p = path.join(asarDir, 'a.asar', 'file4');
await expectToThrowErrorWithCode(() => fs.promises.lstat(p), 'ENOENT');
});
});
describe('fs.realpathSync', () => {
itremote('returns real path root', () => {
const parent = fs.realpathSync(asarDir);
const p = 'a.asar';
const r = fs.realpathSync(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal file', () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'file1');
const r = fs.realpathSync(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal directory', () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'dir1');
const r = fs.realpathSync(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a linked file', () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'link2', 'link1');
const r = fs.realpathSync(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'file1'));
});
itremote('returns real path of a linked directory', () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'link2', 'link2');
const r = fs.realpathSync(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'dir1'));
});
itremote('returns real path of an unpacked file', () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('unpack.asar', 'a.txt');
const r = fs.realpathSync(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('throws ENOENT error when can not find file', () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'not-exist');
expect(() => {
fs.realpathSync(path.join(parent, p));
}).to.throw(/ENOENT/);
});
});
describe('fs.realpathSync.native', () => {
itremote('returns real path root', () => {
const parent = fs.realpathSync.native(asarDir);
const p = 'a.asar';
const r = fs.realpathSync.native(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal file', () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'file1');
const r = fs.realpathSync.native(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal directory', () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'dir1');
const r = fs.realpathSync.native(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a linked file', () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'link2', 'link1');
const r = fs.realpathSync.native(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'file1'));
});
itremote('returns real path of a linked directory', () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'link2', 'link2');
const r = fs.realpathSync.native(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'dir1'));
});
itremote('returns real path of an unpacked file', () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('unpack.asar', 'a.txt');
const r = fs.realpathSync.native(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('throws ENOENT error when can not find file', () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'not-exist');
expect(() => {
fs.realpathSync.native(path.join(parent, p));
}).to.throw(/ENOENT/);
});
});
describe('fs.realpath', () => {
itremote('returns real path root', async () => {
const parent = fs.realpathSync(asarDir);
const p = 'a.asar';
const r = await promisify(fs.realpath)(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal file', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'file1');
const r = await promisify(fs.realpath)(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal directory', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'dir1');
const r = await promisify(fs.realpath)(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a linked file', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'link2', 'link1');
const r = await promisify(fs.realpath)(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'file1'));
});
itremote('returns real path of a linked directory', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'link2', 'link2');
const r = await promisify(fs.realpath)(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'dir1'));
});
itremote('returns real path of an unpacked file', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('unpack.asar', 'a.txt');
const r = await promisify(fs.realpath)(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('throws ENOENT error when can not find file', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'not-exist');
const err = await new Promise<any>(resolve => fs.realpath(path.join(parent, p), resolve));
expect(err.code).to.equal('ENOENT');
});
});
describe('fs.promises.realpath', () => {
itremote('returns real path root', async () => {
const parent = fs.realpathSync(asarDir);
const p = 'a.asar';
const r = await fs.promises.realpath(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal file', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'file1');
const r = await fs.promises.realpath(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal directory', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'dir1');
const r = await fs.promises.realpath(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a linked file', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'link2', 'link1');
const r = await fs.promises.realpath(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'file1'));
});
itremote('returns real path of a linked directory', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'link2', 'link2');
const r = await fs.promises.realpath(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'dir1'));
});
itremote('returns real path of an unpacked file', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('unpack.asar', 'a.txt');
const r = await fs.promises.realpath(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('throws ENOENT error when can not find file', async () => {
const parent = fs.realpathSync(asarDir);
const p = path.join('a.asar', 'not-exist');
await expectToThrowErrorWithCode(() => fs.promises.realpath(path.join(parent, p)), 'ENOENT');
});
});
describe('fs.realpath.native', () => {
itremote('returns real path root', async () => {
const parent = fs.realpathSync.native(asarDir);
const p = 'a.asar';
const r = await promisify(fs.realpath.native)(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal file', async () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'file1');
const r = await promisify(fs.realpath.native)(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a normal directory', async () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'dir1');
const r = await promisify(fs.realpath.native)(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('returns real path of a linked file', async () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'link2', 'link1');
const r = await promisify(fs.realpath.native)(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'file1'));
});
itremote('returns real path of a linked directory', async () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'link2', 'link2');
const r = await promisify(fs.realpath.native)(path.join(parent, p));
expect(r).to.equal(path.join(parent, 'a.asar', 'dir1'));
});
itremote('returns real path of an unpacked file', async () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('unpack.asar', 'a.txt');
const r = await promisify(fs.realpath.native)(path.join(parent, p));
expect(r).to.equal(path.join(parent, p));
});
itremote('throws ENOENT error when can not find file', async () => {
const parent = fs.realpathSync.native(asarDir);
const p = path.join('a.asar', 'not-exist');
const err = await new Promise<any>(resolve => fs.realpath.native(path.join(parent, p), resolve));
expect(err.code).to.equal('ENOENT');
});
});
describe('fs.readdirSync', function () {
itremote('reads dirs from root', function () {
const p = path.join(asarDir, 'a.asar');
const dirs = fs.readdirSync(p);
expect(dirs).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']);
});
itremote('reads dirs from a normal dir', function () {
const p = path.join(asarDir, 'a.asar', 'dir1');
const dirs = fs.readdirSync(p);
expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']);
});
itremote('supports withFileTypes', function () {
const p = path.join(asarDir, 'a.asar');
const dirs = fs.readdirSync(p, { withFileTypes: true });
for (const dir of dirs) {
expect(dir).to.be.an.instanceof(fs.Dirent);
}
const names = dirs.map(a => a.name);
expect(names).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']);
});
itremote('supports withFileTypes for a deep directory', function () {
const p = path.join(asarDir, 'a.asar', 'dir3');
const dirs = fs.readdirSync(p, { withFileTypes: true });
for (const dir of dirs) {
expect(dir).to.be.an.instanceof(fs.Dirent);
}
const names = dirs.map(a => a.name);
expect(names).to.deep.equal(['file1', 'file2', 'file3']);
});
itremote('reads dirs from a linked dir', function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2');
const dirs = fs.readdirSync(p);
expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']);
});
itremote('throws ENOENT error when can not find file', function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
expect(() => {
fs.readdirSync(p);
}).to.throw(/ENOENT/);
});
});
describe('fs.readdir', function () {
itremote('reads dirs from root', async () => {
const p = path.join(asarDir, 'a.asar');
const dirs = await promisify(fs.readdir)(p);
expect(dirs).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']);
});
itremote('supports withFileTypes', async () => {
const p = path.join(asarDir, 'a.asar');
const dirs = await promisify(fs.readdir)(p, { withFileTypes: true });
for (const dir of dirs) {
expect(dir).to.be.an.instanceof(fs.Dirent);
}
const names = dirs.map((a: any) => a.name);
expect(names).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']);
});
itremote('reads dirs from a normal dir', async () => {
const p = path.join(asarDir, 'a.asar', 'dir1');
const dirs = await promisify(fs.readdir)(p);
expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']);
});
itremote('reads dirs from a linked dir', async () => {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2');
const dirs = await promisify(fs.readdir)(p);
expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']);
});
itremote('throws ENOENT error when can not find file', async () => {
const p = path.join(asarDir, 'a.asar', 'not-exist');
const err = await new Promise<any>(resolve => fs.readdir(p, resolve));
expect(err.code).to.equal('ENOENT');
});
it('handles null for options', function (done) {
const p = path.join(asarDir, 'a.asar', 'dir1');
fs.readdir(p, null, function (err, dirs) {
try {
expect(err).to.be.null();
expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']);
done();
} catch (e) {
done(e);
}
});
});
it('handles undefined for options', function (done) {
const p = path.join(asarDir, 'a.asar', 'dir1');
fs.readdir(p, undefined, function (err, dirs) {
try {
expect(err).to.be.null();
expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']);
done();
} catch (e) {
done(e);
}
});
});
});
describe('fs.promises.readdir', function () {
itremote('reads dirs from root', async function () {
const p = path.join(asarDir, 'a.asar');
const dirs = await fs.promises.readdir(p);
expect(dirs).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']);
});
itremote('supports withFileTypes', async function () {
const p = path.join(asarDir, 'a.asar');
const dirs = await fs.promises.readdir(p, { withFileTypes: true });
for (const dir of dirs) {
expect(dir).to.be.an.instanceof(fs.Dirent);
}
const names = dirs.map(a => a.name);
expect(names).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']);
});
itremote('reads dirs from a normal dir', async function () {
const p = path.join(asarDir, 'a.asar', 'dir1');
const dirs = await fs.promises.readdir(p);
expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']);
});
itremote('reads dirs from a linked dir', async function () {
const p = path.join(asarDir, 'a.asar', 'link2', 'link2');
const dirs = await fs.promises.readdir(p);
expect(dirs).to.deep.equal(['file1', 'file2', 'file3', 'link1', 'link2']);
});
itremote('throws ENOENT error when can not find file', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
await expectToThrowErrorWithCode(() => fs.promises.readdir(p), 'ENOENT');
});
});
describe('fs.openSync', function () {
itremote('opens a normal/linked/under-linked-directory file', function () {
const ref2 = ['file1', 'link1', path.join('link2', 'file1')];
for (let j = 0, len = ref2.length; j < len; j++) {
const file = ref2[j];
const p = path.join(asarDir, 'a.asar', file);
const fd = fs.openSync(p, 'r');
const buffer = Buffer.alloc(6);
fs.readSync(fd, buffer, 0, 6, 0);
expect(String(buffer).trim()).to.equal('file1');
fs.closeSync(fd);
}
});
itremote('throws ENOENT error when can not find file', function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
expect(() => {
(fs.openSync as any)(p);
}).to.throw(/ENOENT/);
});
});
describe('fs.open', function () {
itremote('opens a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
const fd = await promisify(fs.open)(p, 'r');
const buffer = Buffer.alloc(6);
await promisify(fs.read)(fd, buffer, 0, 6, 0);
expect(String(buffer).trim()).to.equal('file1');
await promisify(fs.close)(fd);
});
itremote('throws ENOENT error when can not find file', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
const err = await new Promise<any>(resolve => fs.open(p, 'r', resolve));
expect(err.code).to.equal('ENOENT');
});
});
describe('fs.promises.open', function () {
itremote('opens a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
const fh = await fs.promises.open(p, 'r');
const buffer = Buffer.alloc(6);
await fh.read(buffer, 0, 6, 0);
expect(String(buffer).trim()).to.equal('file1');
await fh.close();
});
itremote('throws ENOENT error when can not find file', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
await expectToThrowErrorWithCode(() => fs.promises.open(p, 'r'), 'ENOENT');
});
});
describe('fs.mkdir', function () {
itremote('throws error when calling inside asar archive', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
const err = await new Promise<any>(resolve => fs.mkdir(p, resolve));
expect(err.code).to.equal('ENOTDIR');
});
});
describe('fs.promises.mkdir', function () {
itremote('throws error when calling inside asar archive', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
await expectToThrowErrorWithCode(() => fs.promises.mkdir(p), 'ENOTDIR');
});
});
describe('fs.mkdirSync', function () {
itremote('throws error when calling inside asar archive', function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
expect(() => {
fs.mkdirSync(p);
}).to.throw(/ENOTDIR/);
});
});
describe('fs.exists', function () {
itremote('handles an existing file', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
const exists = await new Promise(resolve => fs.exists(p, resolve));
expect(exists).to.be.true();
});
itremote('handles a non-existent file', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
const exists = await new Promise(resolve => fs.exists(p, resolve));
expect(exists).to.be.false();
});
itremote('promisified version handles an existing file', async () => {
const p = path.join(asarDir, 'a.asar', 'file1');
const exists = await require('node:util').promisify(fs.exists)(p);
expect(exists).to.be.true();
});
itremote('promisified version handles a non-existent file', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
const exists = await require('node:util').promisify(fs.exists)(p);
expect(exists).to.be.false();
});
});
describe('fs.existsSync', function () {
itremote('handles an existing file', function () {
const p = path.join(asarDir, 'a.asar', 'file1');
expect(fs.existsSync(p)).to.be.true();
});
itremote('handles a non-existent file', function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
expect(fs.existsSync(p)).to.be.false();
});
});
describe('fs.access', function () {
itremote('accesses a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
await promisify(fs.access)(p);
});
itremote('throws an error when called with write mode', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
const err = await new Promise<any>(resolve => fs.access(p, fs.constants.R_OK | fs.constants.W_OK, resolve));
expect(err.code).to.equal('EACCES');
});
itremote('throws an error when called on non-existent file', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
const err = await new Promise<any>(resolve => fs.access(p, fs.constants.R_OK | fs.constants.W_OK, resolve));
expect(err.code).to.equal('ENOENT');
});
itremote('allows write mode for unpacked files', async function () {
const p = path.join(asarDir, 'unpack.asar', 'a.txt');
await promisify(fs.access)(p, fs.constants.R_OK | fs.constants.W_OK);
});
});
describe('fs.promises.access', function () {
itremote('accesses a normal file', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
await fs.promises.access(p);
});
itremote('throws an error when called with write mode', async function () {
const p = path.join(asarDir, 'a.asar', 'file1');
await expectToThrowErrorWithCode(() => fs.promises.access(p, fs.constants.R_OK | fs.constants.W_OK), 'EACCES');
});
itremote('throws an error when called on non-existent file', async function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
await expectToThrowErrorWithCode(() => fs.promises.access(p), 'ENOENT');
});
itremote('allows write mode for unpacked files', async function () {
const p = path.join(asarDir, 'unpack.asar', 'a.txt');
await fs.promises.access(p, fs.constants.R_OK | fs.constants.W_OK);
});
});
describe('fs.accessSync', function () {
itremote('accesses a normal file', function () {
const p = path.join(asarDir, 'a.asar', 'file1');
expect(() => {
fs.accessSync(p);
}).to.not.throw();
});
itremote('throws an error when called with write mode', function () {
const p = path.join(asarDir, 'a.asar', 'file1');
expect(() => {
fs.accessSync(p, fs.constants.R_OK | fs.constants.W_OK);
}).to.throw(/EACCES/);
});
itremote('throws an error when called on non-existent file', function () {
const p = path.join(asarDir, 'a.asar', 'not-exist');
expect(() => {
fs.accessSync(p);
}).to.throw(/ENOENT/);
});
itremote('allows write mode for unpacked files', function () {
const p = path.join(asarDir, 'unpack.asar', 'a.txt');
expect(() => {
fs.accessSync(p, fs.constants.R_OK | fs.constants.W_OK);
}).to.not.throw();
});
});
function generateSpecs (childProcess: string) {
describe(`${childProcess}.fork`, function () {
itremote('opens a normal js file', async function (childProcess: string) {
const child = require(childProcess).fork(path.join(asarDir, 'a.asar', 'ping.js'));
child.send('message');
const msg = await new Promise(resolve => child.once('message', resolve));
expect(msg).to.equal('message');
}, [childProcess]);
itremote('supports asar in the forked js', async function (childProcess: string, fixtures: string) {
const file = path.join(asarDir, 'a.asar', 'file1');
const child = require(childProcess).fork(path.join(fixtures, 'module', 'asar.js'));
child.send(file);
const content = await new Promise(resolve => child.once('message', resolve));
expect(content).to.equal(fs.readFileSync(file).toString());
}, [childProcess, fixtures]);
});
describe(`${childProcess}.exec`, function () {
itremote('should not try to extract the command if there is a reference to a file inside an .asar', async function (childProcess: string) {
const echo = path.join(asarDir, 'echo.asar', 'echo');
const stdout = await promisify(require(childProcess).exec)('echo ' + echo + ' foo bar');
expect(stdout.toString().replaceAll('\r', '')).to.equal(echo + ' foo bar\n');
}, [childProcess]);
});
describe(`${childProcess}.execSync`, function () {
itremote('should not try to extract the command if there is a reference to a file inside an .asar', async function (childProcess: string) {
const echo = path.join(asarDir, 'echo.asar', 'echo');
const stdout = require(childProcess).execSync('echo ' + echo + ' foo bar');
expect(stdout.toString().replaceAll('\r', '')).to.equal(echo + ' foo bar\n');
}, [childProcess]);
});
ifdescribe(process.platform === 'darwin' && process.arch !== 'arm64')(`${childProcess}.execFile`, function () {
itremote('executes binaries', async function (childProcess: string) {
const echo = path.join(asarDir, 'echo.asar', 'echo');
const stdout = await promisify(require(childProcess).execFile)(echo, ['test']);
expect(stdout).to.equal('test\n');
}, [childProcess]);
itremote('executes binaries without callback', async function (childProcess: string) {
const echo = path.join(asarDir, 'echo.asar', 'echo');
const process = require(childProcess).execFile(echo, ['test']);
const code = await new Promise(resolve => process.once('close', resolve));
expect(code).to.equal(0);
process.on('error', function () {
throw new Error('error');
});
}, [childProcess]);
itremote('execFileSync executes binaries', function (childProcess: string) {
const echo = path.join(asarDir, 'echo.asar', 'echo');
const output = require(childProcess).execFileSync(echo, ['test']);
expect(String(output)).to.equal('test\n');
}, [childProcess]);
});
}
generateSpecs('child_process');
generateSpecs('node:child_process');
describe('internalModuleReadJSON', function () {
itremote('reads a normal file', function () {
const { internalModuleReadJSON } = (process as any).binding('fs');
const file1 = path.join(asarDir, 'a.asar', 'file1');
const [s1, c1] = internalModuleReadJSON(file1);
expect([s1.toString().trim(), c1]).to.eql(['file1', true]);
const file2 = path.join(asarDir, 'a.asar', 'file2');
const [s2, c2] = internalModuleReadJSON(file2);
expect([s2.toString().trim(), c2]).to.eql(['file2', true]);
const file3 = path.join(asarDir, 'a.asar', 'file3');
const [s3, c3] = internalModuleReadJSON(file3);
expect([s3.toString().trim(), c3]).to.eql(['file3', true]);
});
itremote('reads a normal file with unpacked files', function () {
const { internalModuleReadJSON } = (process as any).binding('fs');
const p = path.join(asarDir, 'unpack.asar', 'a.txt');
const [s, c] = internalModuleReadJSON(p);
expect([s.toString().trim(), c]).to.eql(['a', true]);
});
});
describe('util.promisify', function () {
itremote('can promisify all fs functions', function () {
const originalFs = require('original-fs');
const util = require('node:util');
for (const [propertyName, originalValue] of Object.entries(originalFs)) {
// Some properties exist but have a value of `undefined` on some platforms.
// E.g. `fs.lchmod`, which in only available on MacOS, see
// https://nodejs.org/docs/latest-v10.x/api/fs.html#fs_fs_lchmod_path_mode_callback
// Also check for `null`s, `hasOwnProperty()` can't handle them.
if (typeof originalValue === 'undefined' || originalValue === null) continue;
if (Object.hasOwn(originalValue, util.promisify.custom)) {
expect(fs).to.have.own.property(propertyName)
.that.has.own.property(util.promisify.custom);
}
}
});
});
describe('process.noAsar', function () {
const errorName = process.platform === 'win32' ? 'ENOENT' : 'ENOTDIR';
beforeEach(async function () {
return (await getRemoteContext()).webContents.executeJavaScript(`
process.noAsar = true;
`);
});
afterEach(async function () {
return (await getRemoteContext()).webContents.executeJavaScript(`
process.noAsar = false;
`);
});
itremote('disables asar support in sync API', function (errorName: string) {
const file = path.join(asarDir, 'a.asar', 'file1');
const dir = path.join(asarDir, 'a.asar', 'dir1');
console.log(1);
expect(() => {
fs.readFileSync(file);
}).to.throw(new RegExp(errorName));
expect(() => {
fs.lstatSync(file);
}).to.throw(new RegExp(errorName));
expect(() => {
fs.realpathSync(file);
}).to.throw(new RegExp(errorName));
expect(() => {
fs.readdirSync(dir);
}).to.throw(new RegExp(errorName));
}, [errorName]);
itremote('disables asar support in async API', async function (errorName: string) {
const file = path.join(asarDir, 'a.asar', 'file1');
const dir = path.join(asarDir, 'a.asar', 'dir1');
await new Promise<void>(resolve => {
fs.readFile(file, function (error) {
expect(error?.code).to.equal(errorName);
fs.lstat(file, function (error) {
expect(error?.code).to.equal(errorName);
fs.realpath(file, function (error) {
expect(error?.code).to.equal(errorName);
fs.readdir(dir, function (error) {
expect(error?.code).to.equal(errorName);
resolve();
});
});
});
});
});
}, [errorName]);
itremote('disables asar support in promises API', async function (errorName: string) {
const file = path.join(asarDir, 'a.asar', 'file1');
const dir = path.join(asarDir, 'a.asar', 'dir1');
await expect(fs.promises.readFile(file)).to.be.eventually.rejectedWith(Error, new RegExp(errorName));
await expect(fs.promises.lstat(file)).to.be.eventually.rejectedWith(Error, new RegExp(errorName));
await expect(fs.promises.realpath(file)).to.be.eventually.rejectedWith(Error, new RegExp(errorName));
await expect(fs.promises.readdir(dir)).to.be.eventually.rejectedWith(Error, new RegExp(errorName));
}, [errorName]);
itremote('treats *.asar as normal file', function () {
const originalFs = require('original-fs');
const asar = path.join(asarDir, 'a.asar');
const content1 = fs.readFileSync(asar);
const content2 = originalFs.readFileSync(asar);
expect(content1.compare(content2)).to.equal(0);
expect(() => {
fs.readdirSync(asar);
}).to.throw(/ENOTDIR/);
});
itremote('is reset to its original value when execSync throws an error', function () {
process.noAsar = false;
expect(() => {
require('node:child_process').execSync(path.join(__dirname, 'does-not-exist.txt'));
}).to.throw();
expect(process.noAsar).to.be.false();
});
});
/*
describe('process.env.ELECTRON_NO_ASAR', function () {
itremote('disables asar support in forked processes', function (done) {
const forked = ChildProcess.fork(path.join(__dirname, 'fixtures', 'module', 'no-asar.js'), [], {
env: {
ELECTRON_NO_ASAR: true
}
});
forked.on('message', function (stats) {
try {
expect(stats.isFile).to.be.true();
expect(stats.size).to.equal(3458);
done();
} catch (e) {
done(e);
}
});
});
itremote('disables asar support in spawned processes', function (done) {
const spawned = ChildProcess.spawn(process.execPath, [path.join(__dirname, 'fixtures', 'module', 'no-asar.js')], {
env: {
ELECTRON_NO_ASAR: true,
ELECTRON_RUN_AS_NODE: true
}
});
let output = '';
spawned.stdout.on('data', function (data) {
output += data;
});
spawned.stdout.on('close', function () {
try {
const stats = JSON.parse(output);
expect(stats.isFile).to.be.true();
expect(stats.size).to.equal(3458);
done();
} catch (e) {
done(e);
}
});
});
});
*/
});
describe('asar protocol', function () {
itremote('can request a file in package', async function () {
const p = path.resolve(asarDir, 'a.asar', 'file1');
const response = await fetch('file://' + p);
const data = await response.text();
expect(data.trim()).to.equal('file1');
});
itremote('can request a file in package with unpacked files', async function () {
const p = path.resolve(asarDir, 'unpack.asar', 'a.txt');
const response = await fetch('file://' + p);
const data = await response.text();
expect(data.trim()).to.equal('a');
});
itremote('can request a linked file in package', async function () {
const p = path.resolve(asarDir, 'a.asar', 'link2', 'link1');
const response = await fetch('file://' + p);
const data = await response.text();
expect(data.trim()).to.equal('file1');
});
itremote('can request a file in filesystem', async function () {
const p = path.resolve(asarDir, 'file');
const response = await fetch('file://' + p);
const data = await response.text();
expect(data.trim()).to.equal('file');
});
itremote('gets error when file is not found', async function () {
const p = path.resolve(asarDir, 'a.asar', 'no-exist');
try {
const response = await fetch('file://' + p);
expect(response.status).to.equal(404);
} catch (error: any) {
expect(error.message).to.equal('Failed to fetch');
}
});
});
describe('original-fs module', function () {
itremote('treats .asar as file', function () {
const file = path.join(asarDir, 'a.asar');
const originalFs = require('original-fs');
const stats = originalFs.statSync(file);
expect(stats.isFile()).to.be.true();
});
/*
it('is available in forked scripts', async function () {
const child = ChildProcess.fork(path.join(fixtures, 'module', 'original-fs.js'));
const message = once(child, 'message');
child.send('message');
const [msg] = await message;
expect(msg).to.equal('object');
});
*/
itremote('can be used with streams', () => {
const originalFs = require('original-fs');
originalFs.createReadStream(path.join(asarDir, 'a.asar'));
});
itremote('can recursively delete a directory with an asar file in itremote', () => {
const deleteDir = path.join(asarDir, 'deleteme');
fs.mkdirSync(deleteDir);
const originalFs = require('original-fs');
originalFs.rmdirSync(deleteDir, { recursive: true });
expect(fs.existsSync(deleteDir)).to.be.false();
});
itremote('has the same APIs as fs', function () {
expect(Object.keys(require('node:fs'))).to.deep.equal(Object.keys(require('original-fs')));
expect(Object.keys(require('node:fs').promises)).to.deep.equal(Object.keys(require('original-fs').promises));
});
});
describe('graceful-fs module', function () {
itremote('recognize asar archives', function () {
const gfs = require('graceful-fs');
const p = path.join(asarDir, 'a.asar', 'link1');
expect(gfs.readFileSync(p).toString().trim()).to.equal('file1');
});
itremote('does not touch global fs object', function () {
const gfs = require('graceful-fs');
expect(fs.readdir).to.not.equal(gfs.readdir);
});
});
describe('mkdirp module', function () {
itremote('throws error when calling inside asar archive', function () {
const mkdirp = require('mkdirp');
const p = path.join(asarDir, 'a.asar', 'not-exist');
expect(() => {
mkdirp.sync(p);
}).to.throw(/ENOTDIR/);
});
});
describe('native-image', function () {
itremote('reads image from asar archive', function () {
const p = path.join(asarDir, 'logo.asar', 'logo.png');
const logo = require('electron').nativeImage.createFromPath(p);
expect(logo.getSize()).to.deep.equal({
width: 55,
height: 55
});
});
itremote('reads image from asar archive with unpacked files', function () {
const p = path.join(asarDir, 'unpack.asar', 'atom.png');
const logo = require('electron').nativeImage.createFromPath(p);
expect(logo.getSize()).to.deep.equal({
width: 1024,
height: 1024
});
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,133 |
[Bug]: notification.close() does not work in Windows after the popup has disappeared
|
### 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.3.0, 27.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 11 22H2 (22621.2361)
### What arch are you using?
x64
### Last Known Working Electron version
11.x
### Expected Behavior
1. Create Notification with `Electron.Notification`.
2. Wait for the notification popup to disappear and be logged to the Windows notification center.
3. Call `Electron.Notification.close()` on it
The notification is removed from the Windows notification center and the "unread" count in the taskbar decreases
### Actual Behavior
The notification remains in the Windows notification center and the unread count does not change.
### Testcase Gist URL
https://gist.github.com/474863b1c8a398ee00a74950596ab0c3
### Additional Information
Duplicated of #29557, #32260 (These issues are marked as "stale", but still occurred)
|
https://github.com/electron/electron/issues/40133
|
https://github.com/electron/electron/pull/40197
|
73a42d0b7bff9b381349c8c32a46623d63471572
|
666907d50d2d62e31e1c3e7329f45e8350fe73cd
| 2023-10-07T04:31:01Z |
c++
| 2023-10-17T23:33:00Z |
docs/api/notification.md
|
# Notification
> Create OS desktop notifications
Process: [Main](../glossary.md#main-process)
:::info Renderer process notifications
If you want to show notifications from a renderer process you should use the
[web Notifications API](../tutorial/notifications.md)
:::
## Class: Notification
> Create OS desktop notifications
Process: [Main](../glossary.md#main-process)
`Notification` is an [EventEmitter][event-emitter].
It creates a new `Notification` with native properties as set by the `options`.
### Static Methods
The `Notification` class has the following static methods:
#### `Notification.isSupported()`
Returns `boolean` - Whether or not desktop notifications are supported on the current system
### `new Notification([options])`
* `options` Object (optional)
* `title` string (optional) - A title for the notification, which will be displayed at the top of the notification window when it is shown.
* `subtitle` string (optional) _macOS_ - A subtitle for the notification, which will be displayed below the title.
* `body` string (optional) - The body text of the notification, which will be displayed below the title or subtitle.
* `silent` boolean (optional) - Whether or not to suppress the OS notification noise when showing the notification.
* `icon` (string | [NativeImage](native-image.md)) (optional) - An icon to use in the notification.
* `hasReply` boolean (optional) _macOS_ - Whether or not to add an inline reply option to the notification.
* `timeoutType` string (optional) _Linux_ _Windows_ - The timeout duration of the notification. Can be 'default' or 'never'.
* `replyPlaceholder` string (optional) _macOS_ - The placeholder to write in the inline reply input field.
* `sound` string (optional) _macOS_ - The name of the sound file to play when the notification is shown.
* `urgency` string (optional) _Linux_ - The urgency level of the notification. Can be 'normal', 'critical', or 'low'.
* `actions` [NotificationAction[]](structures/notification-action.md) (optional) _macOS_ - Actions to add to the notification. Please read the available actions and limitations in the `NotificationAction` documentation.
* `closeButtonText` string (optional) _macOS_ - A custom title for the close button of an alert. An empty string will cause the default localized text to be used.
* `toastXml` string (optional) _Windows_ - A custom description of the Notification on Windows superseding all properties above. Provides full customization of design and behavior of the notification.
### Instance Events
Objects created with `new Notification` emit the following events:
:::info
Some events are only available on specific operating systems and are labeled as such.
:::
#### Event: 'show'
Returns:
* `event` Event
Emitted when the notification is shown to the user. Note that this event can be fired
multiple times as a notification can be shown multiple times through the
`show()` method.
#### Event: 'click'
Returns:
* `event` Event
Emitted when the notification is clicked by the user.
#### Event: 'close'
Returns:
* `event` Event
Emitted when the notification is closed by manual intervention from the user.
This event is not guaranteed to be emitted in all cases where the notification
is closed.
#### Event: 'reply' _macOS_
Returns:
* `event` Event
* `reply` string - The string the user entered into the inline reply field.
Emitted when the user clicks the "Reply" button on a notification with `hasReply: true`.
#### Event: 'action' _macOS_
Returns:
* `event` Event
* `index` number - The index of the action that was activated.
#### Event: 'failed' _Windows_
Returns:
* `event` Event
* `error` string - The error encountered during execution of the `show()` method.
Emitted when an error is encountered while creating and showing the native notification.
### Instance Methods
Objects created with the `new Notification()` constructor have the following instance methods:
#### `notification.show()`
Immediately shows the notification to the user. Unlike the web notification API,
instantiating a `new Notification()` does not immediately show it to the user. Instead, you need to
call this method before the OS will display it.
If the notification has been shown before, this method will dismiss the previously
shown notification and create a new one with identical properties.
#### `notification.close()`
Dismisses the notification.
### Instance Properties
#### `notification.title`
A `string` property representing the title of the notification.
#### `notification.subtitle`
A `string` property representing the subtitle of the notification.
#### `notification.body`
A `string` property representing the body of the notification.
#### `notification.replyPlaceholder`
A `string` property representing the reply placeholder of the notification.
#### `notification.sound`
A `string` property representing the sound of the notification.
#### `notification.closeButtonText`
A `string` property representing the close button text of the notification.
#### `notification.silent`
A `boolean` property representing whether the notification is silent.
#### `notification.hasReply`
A `boolean` property representing whether the notification has a reply action.
#### `notification.urgency` _Linux_
A `string` property representing the urgency level of the notification. Can be 'normal', 'critical', or 'low'.
Default is 'low' - see [NotifyUrgency](https://developer-old.gnome.org/notification-spec/#urgency-levels) for more information.
#### `notification.timeoutType` _Linux_ _Windows_
A `string` property representing the type of timeout duration for the notification. Can be 'default' or 'never'.
If `timeoutType` is set to 'never', the notification never expires. It stays open until closed by the calling API or the user.
#### `notification.actions`
A [`NotificationAction[]`](structures/notification-action.md) property representing the actions of the notification.
#### `notification.toastXml` _Windows_
A `string` property representing the custom Toast XML of the notification.
### Playing Sounds
On macOS, you can specify the name of the sound you'd like to play when the
notification is shown. Any of the default sounds (under System Preferences >
Sound) can be used, in addition to custom sound files. Be sure that the sound
file is copied under the app bundle (e.g., `YourApp.app/Contents/Resources`),
or one of the following locations:
* `~/Library/Sounds`
* `/Library/Sounds`
* `/Network/Library/Sounds`
* `/System/Library/Sounds`
See the [`NSSound`](https://developer.apple.com/documentation/appkit/nssound) docs for more information.
[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,133 |
[Bug]: notification.close() does not work in Windows after the popup has disappeared
|
### 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.3.0, 27.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 11 22H2 (22621.2361)
### What arch are you using?
x64
### Last Known Working Electron version
11.x
### Expected Behavior
1. Create Notification with `Electron.Notification`.
2. Wait for the notification popup to disappear and be logged to the Windows notification center.
3. Call `Electron.Notification.close()` on it
The notification is removed from the Windows notification center and the "unread" count in the taskbar decreases
### Actual Behavior
The notification remains in the Windows notification center and the unread count does not change.
### Testcase Gist URL
https://gist.github.com/474863b1c8a398ee00a74950596ab0c3
### Additional Information
Duplicated of #29557, #32260 (These issues are marked as "stale", but still occurred)
|
https://github.com/electron/electron/issues/40133
|
https://github.com/electron/electron/pull/40197
|
73a42d0b7bff9b381349c8c32a46623d63471572
|
666907d50d2d62e31e1c3e7329f45e8350fe73cd
| 2023-10-07T04:31:01Z |
c++
| 2023-10-17T23:33:00Z |
shell/browser/api/electron_api_notification.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_notification.h"
#include "base/strings/utf_string_conversions.h"
#include "base/uuid.h"
#include "gin/handle.h"
#include "shell/browser/api/electron_api_menu.h"
#include "shell/browser/browser.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/node_includes.h"
#include "url/gurl.h"
namespace gin {
template <>
struct Converter<electron::NotificationAction> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::NotificationAction* out) {
gin::Dictionary dict(isolate);
if (!ConvertFromV8(isolate, val, &dict))
return false;
if (!dict.Get("type", &(out->type))) {
return false;
}
dict.Get("text", &(out->text));
return true;
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
electron::NotificationAction val) {
auto dict = gin::Dictionary::CreateEmpty(isolate);
dict.Set("text", val.text);
dict.Set("type", val.type);
return ConvertToV8(isolate, dict);
}
};
} // namespace gin
namespace electron::api {
gin::WrapperInfo Notification::kWrapperInfo = {gin::kEmbedderNativeGin};
Notification::Notification(gin::Arguments* args) {
presenter_ = static_cast<ElectronBrowserClient*>(ElectronBrowserClient::Get())
->GetNotificationPresenter();
gin::Dictionary opts(nullptr);
if (args->GetNext(&opts)) {
opts.Get("title", &title_);
opts.Get("subtitle", &subtitle_);
opts.Get("body", &body_);
has_icon_ = opts.Get("icon", &icon_);
if (has_icon_) {
opts.Get("icon", &icon_path_);
}
opts.Get("silent", &silent_);
opts.Get("replyPlaceholder", &reply_placeholder_);
opts.Get("urgency", &urgency_);
opts.Get("hasReply", &has_reply_);
opts.Get("timeoutType", &timeout_type_);
opts.Get("actions", &actions_);
opts.Get("sound", &sound_);
opts.Get("closeButtonText", &close_button_text_);
opts.Get("toastXml", &toast_xml_);
}
}
Notification::~Notification() {
if (notification_)
notification_->set_delegate(nullptr);
}
// static
gin::Handle<Notification> Notification::New(gin_helper::ErrorThrower thrower,
gin::Arguments* args) {
if (!Browser::Get()->is_ready()) {
thrower.ThrowError("Cannot create Notification before app is ready");
return gin::Handle<Notification>();
}
return gin::CreateHandle(thrower.isolate(), new Notification(args));
}
// Getters
std::u16string Notification::GetTitle() const {
return title_;
}
std::u16string Notification::GetSubtitle() const {
return subtitle_;
}
std::u16string Notification::GetBody() const {
return body_;
}
bool Notification::GetSilent() const {
return silent_;
}
bool Notification::GetHasReply() const {
return has_reply_;
}
std::u16string Notification::GetTimeoutType() const {
return timeout_type_;
}
std::u16string Notification::GetReplyPlaceholder() const {
return reply_placeholder_;
}
std::u16string Notification::GetSound() const {
return sound_;
}
std::u16string Notification::GetUrgency() const {
return urgency_;
}
std::vector<electron::NotificationAction> Notification::GetActions() const {
return actions_;
}
std::u16string Notification::GetCloseButtonText() const {
return close_button_text_;
}
std::u16string Notification::GetToastXml() const {
return toast_xml_;
}
// Setters
void Notification::SetTitle(const std::u16string& new_title) {
title_ = new_title;
}
void Notification::SetSubtitle(const std::u16string& new_subtitle) {
subtitle_ = new_subtitle;
}
void Notification::SetBody(const std::u16string& new_body) {
body_ = new_body;
}
void Notification::SetSilent(bool new_silent) {
silent_ = new_silent;
}
void Notification::SetHasReply(bool new_has_reply) {
has_reply_ = new_has_reply;
}
void Notification::SetTimeoutType(const std::u16string& new_timeout_type) {
timeout_type_ = new_timeout_type;
}
void Notification::SetReplyPlaceholder(const std::u16string& new_placeholder) {
reply_placeholder_ = new_placeholder;
}
void Notification::SetSound(const std::u16string& new_sound) {
sound_ = new_sound;
}
void Notification::SetUrgency(const std::u16string& new_urgency) {
urgency_ = new_urgency;
}
void Notification::SetActions(
const std::vector<electron::NotificationAction>& actions) {
actions_ = actions;
}
void Notification::SetCloseButtonText(const std::u16string& text) {
close_button_text_ = text;
}
void Notification::SetToastXml(const std::u16string& new_toast_xml) {
toast_xml_ = new_toast_xml;
}
void Notification::NotificationAction(int index) {
Emit("action", index);
}
void Notification::NotificationClick() {
Emit("click");
}
void Notification::NotificationReplied(const std::string& reply) {
Emit("reply", reply);
}
void Notification::NotificationDisplayed() {
Emit("show");
}
void Notification::NotificationFailed(const std::string& error) {
Emit("failed", error);
}
void Notification::NotificationDestroyed() {}
void Notification::NotificationClosed() {
Emit("close");
}
void Notification::Close() {
if (notification_) {
notification_->Dismiss();
notification_->set_delegate(nullptr);
notification_.reset();
}
}
// Showing notifications
void Notification::Show() {
Close();
if (presenter_) {
notification_ = presenter_->CreateNotification(
this, base::Uuid::GenerateRandomV4().AsLowercaseString());
if (notification_) {
electron::NotificationOptions options;
options.title = title_;
options.subtitle = subtitle_;
options.msg = body_;
options.icon_url = GURL();
options.icon = icon_.AsBitmap();
options.silent = silent_;
options.has_reply = has_reply_;
options.timeout_type = timeout_type_;
options.reply_placeholder = reply_placeholder_;
options.actions = actions_;
options.sound = sound_;
options.close_button_text = close_button_text_;
options.urgency = urgency_;
options.toast_xml = toast_xml_;
notification_->Show(options);
}
}
}
bool Notification::IsSupported() {
return !!static_cast<ElectronBrowserClient*>(ElectronBrowserClient::Get())
->GetNotificationPresenter();
}
void Notification::FillObjectTemplate(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin::ObjectTemplateBuilder(isolate, GetClassName(), templ)
.SetMethod("show", &Notification::Show)
.SetMethod("close", &Notification::Close)
.SetProperty("title", &Notification::GetTitle, &Notification::SetTitle)
.SetProperty("subtitle", &Notification::GetSubtitle,
&Notification::SetSubtitle)
.SetProperty("body", &Notification::GetBody, &Notification::SetBody)
.SetProperty("silent", &Notification::GetSilent, &Notification::SetSilent)
.SetProperty("hasReply", &Notification::GetHasReply,
&Notification::SetHasReply)
.SetProperty("timeoutType", &Notification::GetTimeoutType,
&Notification::SetTimeoutType)
.SetProperty("replyPlaceholder", &Notification::GetReplyPlaceholder,
&Notification::SetReplyPlaceholder)
.SetProperty("urgency", &Notification::GetUrgency,
&Notification::SetUrgency)
.SetProperty("sound", &Notification::GetSound, &Notification::SetSound)
.SetProperty("actions", &Notification::GetActions,
&Notification::SetActions)
.SetProperty("closeButtonText", &Notification::GetCloseButtonText,
&Notification::SetCloseButtonText)
.SetProperty("toastXml", &Notification::GetToastXml,
&Notification::SetToastXml)
.Build();
}
const char* Notification::GetTypeName() {
return GetClassName();
}
} // namespace electron::api
namespace {
using electron::api::Notification;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("Notification", Notification::GetConstructor(context));
dict.SetMethod("isSupported", &Notification::IsSupported);
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_notification, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,133 |
[Bug]: notification.close() does not work in Windows after the popup has disappeared
|
### 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.3.0, 27.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 11 22H2 (22621.2361)
### What arch are you using?
x64
### Last Known Working Electron version
11.x
### Expected Behavior
1. Create Notification with `Electron.Notification`.
2. Wait for the notification popup to disappear and be logged to the Windows notification center.
3. Call `Electron.Notification.close()` on it
The notification is removed from the Windows notification center and the "unread" count in the taskbar decreases
### Actual Behavior
The notification remains in the Windows notification center and the unread count does not change.
### Testcase Gist URL
https://gist.github.com/474863b1c8a398ee00a74950596ab0c3
### Additional Information
Duplicated of #29557, #32260 (These issues are marked as "stale", but still occurred)
|
https://github.com/electron/electron/issues/40133
|
https://github.com/electron/electron/pull/40197
|
73a42d0b7bff9b381349c8c32a46623d63471572
|
666907d50d2d62e31e1c3e7329f45e8350fe73cd
| 2023-10-07T04:31:01Z |
c++
| 2023-10-17T23:33:00Z |
shell/browser/notifications/notification.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/notifications/notification.h"
#include "shell/browser/notifications/notification_delegate.h"
#include "shell/browser/notifications/notification_presenter.h"
namespace electron {
NotificationOptions::NotificationOptions() = default;
NotificationOptions::~NotificationOptions() = default;
Notification::Notification(NotificationDelegate* delegate,
NotificationPresenter* presenter)
: delegate_(delegate), presenter_(presenter) {}
Notification::~Notification() {
if (delegate())
delegate()->NotificationDestroyed();
}
void Notification::NotificationClicked() {
if (delegate())
delegate()->NotificationClick();
Destroy();
}
void Notification::NotificationDismissed() {
if (delegate())
delegate()->NotificationClosed();
Destroy();
}
void Notification::NotificationFailed(const std::string& error) {
if (delegate())
delegate()->NotificationFailed(error);
Destroy();
}
void Notification::Destroy() {
presenter()->RemoveNotification(this);
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,133 |
[Bug]: notification.close() does not work in Windows after the popup has disappeared
|
### 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.3.0, 27.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 11 22H2 (22621.2361)
### What arch are you using?
x64
### Last Known Working Electron version
11.x
### Expected Behavior
1. Create Notification with `Electron.Notification`.
2. Wait for the notification popup to disappear and be logged to the Windows notification center.
3. Call `Electron.Notification.close()` on it
The notification is removed from the Windows notification center and the "unread" count in the taskbar decreases
### Actual Behavior
The notification remains in the Windows notification center and the unread count does not change.
### Testcase Gist URL
https://gist.github.com/474863b1c8a398ee00a74950596ab0c3
### Additional Information
Duplicated of #29557, #32260 (These issues are marked as "stale", but still occurred)
|
https://github.com/electron/electron/issues/40133
|
https://github.com/electron/electron/pull/40197
|
73a42d0b7bff9b381349c8c32a46623d63471572
|
666907d50d2d62e31e1c3e7329f45e8350fe73cd
| 2023-10-07T04:31:01Z |
c++
| 2023-10-17T23:33:00Z |
shell/browser/notifications/notification.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_NOTIFICATIONS_NOTIFICATION_H_
#define ELECTRON_SHELL_BROWSER_NOTIFICATIONS_NOTIFICATION_H_
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "url/gurl.h"
namespace electron {
class NotificationDelegate;
class NotificationPresenter;
struct NotificationAction {
std::u16string type;
std::u16string text;
};
struct NotificationOptions {
std::u16string title;
std::u16string subtitle;
std::u16string msg;
std::string tag;
bool silent;
GURL icon_url;
SkBitmap icon;
bool has_reply;
std::u16string timeout_type;
std::u16string reply_placeholder;
std::u16string sound;
std::u16string urgency; // Linux
std::vector<NotificationAction> actions;
std::u16string close_button_text;
std::u16string toast_xml;
NotificationOptions();
~NotificationOptions();
};
class Notification {
public:
virtual ~Notification();
// Shows the notification.
virtual void Show(const NotificationOptions& options) = 0;
// Closes the notification, this instance will be destroyed after the
// notification gets closed.
virtual void Dismiss() = 0;
// Should be called by derived classes.
void NotificationClicked();
void NotificationDismissed();
void NotificationFailed(const std::string& error = "");
// delete this.
void Destroy();
base::WeakPtr<Notification> GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
void set_delegate(NotificationDelegate* delegate) { delegate_ = delegate; }
void set_notification_id(const std::string& id) { notification_id_ = id; }
NotificationDelegate* delegate() const { return delegate_; }
NotificationPresenter* presenter() const { return presenter_; }
const std::string& notification_id() const { return notification_id_; }
// disable copy
Notification(const Notification&) = delete;
Notification& operator=(const Notification&) = delete;
protected:
Notification(NotificationDelegate* delegate,
NotificationPresenter* presenter);
private:
raw_ptr<NotificationDelegate> delegate_;
raw_ptr<NotificationPresenter> presenter_;
std::string notification_id_;
base::WeakPtrFactory<Notification> weak_factory_{this};
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_NOTIFICATIONS_NOTIFICATION_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,133 |
[Bug]: notification.close() does not work in Windows after the popup has disappeared
|
### 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.3.0, 27.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 11 22H2 (22621.2361)
### What arch are you using?
x64
### Last Known Working Electron version
11.x
### Expected Behavior
1. Create Notification with `Electron.Notification`.
2. Wait for the notification popup to disappear and be logged to the Windows notification center.
3. Call `Electron.Notification.close()` on it
The notification is removed from the Windows notification center and the "unread" count in the taskbar decreases
### Actual Behavior
The notification remains in the Windows notification center and the unread count does not change.
### Testcase Gist URL
https://gist.github.com/474863b1c8a398ee00a74950596ab0c3
### Additional Information
Duplicated of #29557, #32260 (These issues are marked as "stale", but still occurred)
|
https://github.com/electron/electron/issues/40133
|
https://github.com/electron/electron/pull/40197
|
73a42d0b7bff9b381349c8c32a46623d63471572
|
666907d50d2d62e31e1c3e7329f45e8350fe73cd
| 2023-10-07T04:31:01Z |
c++
| 2023-10-17T23:33:00Z |
shell/browser/notifications/win/windows_toast_notification.cc
|
// Copyright (c) 2015 Felix Rieseberg <[email protected]> and Jason Poon
// <[email protected]>. All rights reserved.
// Copyright (c) 2015 Ryan McShane <[email protected]> and Brandon Smith
// <[email protected]>
// Thanks to both of those folks mentioned above who first thought up a bunch of
// this code
// and released it as MIT to the world.
#include "shell/browser/notifications/win/windows_toast_notification.h"
#include <shlobj.h>
#include <wrl\wrappers\corewrappers.h>
#include "base/environment.h"
#include "base/logging.h"
#include "base/strings/string_util_win.h"
#include "base/strings/utf_string_conversions.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "shell/browser/notifications/notification_delegate.h"
#include "shell/browser/notifications/win/notification_presenter_win.h"
#include "shell/browser/win/scoped_hstring.h"
#include "shell/common/application_info.h"
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/strings/grit/ui_strings.h"
using ABI::Windows::Data::Xml::Dom::IXmlAttribute;
using ABI::Windows::Data::Xml::Dom::IXmlDocument;
using ABI::Windows::Data::Xml::Dom::IXmlDocumentIO;
using ABI::Windows::Data::Xml::Dom::IXmlElement;
using ABI::Windows::Data::Xml::Dom::IXmlNamedNodeMap;
using ABI::Windows::Data::Xml::Dom::IXmlNode;
using ABI::Windows::Data::Xml::Dom::IXmlNodeList;
using ABI::Windows::Data::Xml::Dom::IXmlText;
using Microsoft::WRL::Wrappers::HStringReference;
#define RETURN_IF_FAILED(hr) \
do { \
HRESULT _hrTemp = hr; \
if (FAILED(_hrTemp)) { \
return _hrTemp; \
} \
} while (false)
#define REPORT_AND_RETURN_IF_FAILED(hr, msg) \
do { \
HRESULT _hrTemp = hr; \
std::string _msgTemp = msg; \
if (FAILED(_hrTemp)) { \
std::string _err = _msgTemp + ",ERROR " + std::to_string(_hrTemp); \
if (IsDebuggingNotifications()) \
LOG(INFO) << _err; \
Notification::NotificationFailed(_err); \
return _hrTemp; \
} \
} while (false)
namespace electron {
namespace {
bool IsDebuggingNotifications() {
return base::Environment::Create()->HasVar("ELECTRON_DEBUG_NOTIFICATIONS");
}
} // namespace
// static
ComPtr<ABI::Windows::UI::Notifications::IToastNotificationManagerStatics>
WindowsToastNotification::toast_manager_;
// static
ComPtr<ABI::Windows::UI::Notifications::IToastNotifier>
WindowsToastNotification::toast_notifier_;
// static
bool WindowsToastNotification::Initialize() {
// Just initialize, don't care if it fails or already initialized.
Windows::Foundation::Initialize(RO_INIT_MULTITHREADED);
ScopedHString toast_manager_str(
RuntimeClass_Windows_UI_Notifications_ToastNotificationManager);
if (!toast_manager_str.success())
return false;
if (FAILED(Windows::Foundation::GetActivationFactory(toast_manager_str,
&toast_manager_)))
return false;
if (IsRunningInDesktopBridge()) {
// Ironically, the Desktop Bridge / UWP environment
// requires us to not give Windows an appUserModelId.
return SUCCEEDED(toast_manager_->CreateToastNotifier(&toast_notifier_));
} else {
ScopedHString app_id;
if (!GetAppUserModelID(&app_id))
return false;
return SUCCEEDED(
toast_manager_->CreateToastNotifierWithId(app_id, &toast_notifier_));
}
}
WindowsToastNotification::WindowsToastNotification(
NotificationDelegate* delegate,
NotificationPresenter* presenter)
: Notification(delegate, presenter) {}
WindowsToastNotification::~WindowsToastNotification() {
// Remove the notification on exit.
if (toast_notification_) {
RemoveCallbacks(toast_notification_.Get());
}
}
void WindowsToastNotification::Show(const NotificationOptions& options) {
if (SUCCEEDED(ShowInternal(options))) {
if (IsDebuggingNotifications())
LOG(INFO) << "Notification created";
if (delegate())
delegate()->NotificationDisplayed();
}
}
void WindowsToastNotification::Dismiss() {
if (IsDebuggingNotifications())
LOG(INFO) << "Hiding notification";
toast_notifier_->Hide(toast_notification_.Get());
}
HRESULT WindowsToastNotification::ShowInternal(
const NotificationOptions& options) {
ComPtr<IXmlDocument> toast_xml;
// The custom xml takes priority over the preset template.
if (!options.toast_xml.empty()) {
REPORT_AND_RETURN_IF_FAILED(
XmlDocumentFromString(base::as_wcstr(options.toast_xml), &toast_xml),
"XML: Invalid XML");
} else {
auto* presenter_win = static_cast<NotificationPresenterWin*>(presenter());
std::wstring icon_path =
presenter_win->SaveIconToFilesystem(options.icon, options.icon_url);
REPORT_AND_RETURN_IF_FAILED(
GetToastXml(toast_manager_.Get(), options.title, options.msg, icon_path,
options.timeout_type, options.silent, &toast_xml),
"XML: Failed to create XML document");
}
ScopedHString toast_str(
RuntimeClass_Windows_UI_Notifications_ToastNotification);
if (!toast_str.success()) {
NotificationFailed("Creating ScopedHString failed");
return E_FAIL;
}
ComPtr<ABI::Windows::UI::Notifications::IToastNotificationFactory>
toast_factory;
REPORT_AND_RETURN_IF_FAILED(
Windows::Foundation::GetActivationFactory(toast_str, &toast_factory),
"WinAPI: GetActivationFactory failed");
REPORT_AND_RETURN_IF_FAILED(toast_factory->CreateToastNotification(
toast_xml.Get(), &toast_notification_),
"WinAPI: CreateToastNotification failed");
REPORT_AND_RETURN_IF_FAILED(SetupCallbacks(toast_notification_.Get()),
"WinAPI: SetupCallbacks failed");
REPORT_AND_RETURN_IF_FAILED(toast_notifier_->Show(toast_notification_.Get()),
"WinAPI: Show failed");
return S_OK;
}
HRESULT WindowsToastNotification::GetToastXml(
ABI::Windows::UI::Notifications::IToastNotificationManagerStatics*
toastManager,
const std::u16string& title,
const std::u16string& msg,
const std::wstring& icon_path,
const std::u16string& timeout_type,
bool silent,
IXmlDocument** toast_xml) {
ABI::Windows::UI::Notifications::ToastTemplateType template_type;
if (title.empty() || msg.empty()) {
// Single line toast.
template_type =
icon_path.empty()
? ABI::Windows::UI::Notifications::ToastTemplateType_ToastText01
: ABI::Windows::UI::Notifications::
ToastTemplateType_ToastImageAndText01;
REPORT_AND_RETURN_IF_FAILED(
toast_manager_->GetTemplateContent(template_type, toast_xml),
"XML: Fetching XML ToastImageAndText01 template failed");
std::u16string toastMsg = title.empty() ? msg : title;
// we can't create an empty notification
toastMsg = toastMsg.empty() ? u"[no message]" : toastMsg;
REPORT_AND_RETURN_IF_FAILED(
SetXmlText(*toast_xml, toastMsg),
"XML: Filling XML ToastImageAndText01 template failed");
} else {
// Title and body toast.
template_type =
icon_path.empty()
? ABI::Windows::UI::Notifications::ToastTemplateType_ToastText02
: ABI::Windows::UI::Notifications::
ToastTemplateType_ToastImageAndText02;
REPORT_AND_RETURN_IF_FAILED(
toastManager->GetTemplateContent(template_type, toast_xml),
"XML: Fetching XML ToastImageAndText02 template failed");
REPORT_AND_RETURN_IF_FAILED(
SetXmlText(*toast_xml, title, msg),
"XML: Filling XML ToastImageAndText02 template failed");
}
// Configure the toast's timeout settings
if (timeout_type == u"never") {
REPORT_AND_RETURN_IF_FAILED(
(SetXmlScenarioReminder(*toast_xml)),
"XML: Setting \"scenario\" option on notification failed");
}
// Configure the toast's notification sound
if (silent) {
REPORT_AND_RETURN_IF_FAILED(
SetXmlAudioSilent(*toast_xml),
"XML: Setting \"silent\" option on notification failed");
}
// Configure the toast's image
if (!icon_path.empty()) {
REPORT_AND_RETURN_IF_FAILED(
SetXmlImage(*toast_xml, icon_path),
"XML: Setting \"icon\" option on notification failed");
}
return S_OK;
}
HRESULT WindowsToastNotification::SetXmlScenarioReminder(IXmlDocument* doc) {
ScopedHString tag(L"toast");
if (!tag.success())
return false;
ComPtr<IXmlNodeList> node_list;
RETURN_IF_FAILED(doc->GetElementsByTagName(tag, &node_list));
// Check that root "toast" node exists
ComPtr<IXmlNode> root;
RETURN_IF_FAILED(node_list->Item(0, &root));
// get attributes of root "toast" node
ComPtr<IXmlNamedNodeMap> toast_attributes;
RETURN_IF_FAILED(root->get_Attributes(&toast_attributes));
ComPtr<IXmlAttribute> scenario_attribute;
ScopedHString scenario_str(L"scenario");
RETURN_IF_FAILED(doc->CreateAttribute(scenario_str, &scenario_attribute));
ComPtr<IXmlNode> scenario_attribute_node;
RETURN_IF_FAILED(scenario_attribute.As(&scenario_attribute_node));
ScopedHString scenario_value(L"reminder");
if (!scenario_value.success())
return E_FAIL;
ComPtr<IXmlText> scenario_text;
RETURN_IF_FAILED(doc->CreateTextNode(scenario_value, &scenario_text));
ComPtr<IXmlNode> scenario_node;
RETURN_IF_FAILED(scenario_text.As(&scenario_node));
ComPtr<IXmlNode> scenario_backup_node;
RETURN_IF_FAILED(scenario_attribute_node->AppendChild(scenario_node.Get(),
&scenario_backup_node));
ComPtr<IXmlNode> scenario_attribute_pnode;
RETURN_IF_FAILED(toast_attributes.Get()->SetNamedItem(
scenario_attribute_node.Get(), &scenario_attribute_pnode));
// Create "actions" wrapper
ComPtr<IXmlElement> actions_wrapper_element;
ScopedHString actions_wrapper_str(L"actions");
RETURN_IF_FAILED(
doc->CreateElement(actions_wrapper_str, &actions_wrapper_element));
ComPtr<IXmlNode> actions_wrapper_node_tmp;
RETURN_IF_FAILED(actions_wrapper_element.As(&actions_wrapper_node_tmp));
// Append actions wrapper node to toast xml
ComPtr<IXmlNode> actions_wrapper_node;
RETURN_IF_FAILED(
root->AppendChild(actions_wrapper_node_tmp.Get(), &actions_wrapper_node));
ComPtr<IXmlNamedNodeMap> attributes_actions_wrapper;
RETURN_IF_FAILED(
actions_wrapper_node->get_Attributes(&attributes_actions_wrapper));
// Add a "Dismiss" button
// Create "action" tag
ComPtr<IXmlElement> action_element;
ScopedHString action_str(L"action");
RETURN_IF_FAILED(doc->CreateElement(action_str, &action_element));
ComPtr<IXmlNode> action_node_tmp;
RETURN_IF_FAILED(action_element.As(&action_node_tmp));
// Append action node to actions wrapper in toast xml
ComPtr<IXmlNode> action_node;
RETURN_IF_FAILED(
actions_wrapper_node->AppendChild(action_node_tmp.Get(), &action_node));
// Setup attributes for action
ComPtr<IXmlNamedNodeMap> action_attributes;
RETURN_IF_FAILED(action_node->get_Attributes(&action_attributes));
// Create activationType attribute
ComPtr<IXmlAttribute> activation_type_attribute;
ScopedHString activation_type_str(L"activationType");
RETURN_IF_FAILED(
doc->CreateAttribute(activation_type_str, &activation_type_attribute));
ComPtr<IXmlNode> activation_type_attribute_node;
RETURN_IF_FAILED(
activation_type_attribute.As(&activation_type_attribute_node));
// Set activationType attribute to system
ScopedHString activation_type_value(L"system");
if (!activation_type_value.success())
return E_FAIL;
ComPtr<IXmlText> activation_type_text;
RETURN_IF_FAILED(
doc->CreateTextNode(activation_type_value, &activation_type_text));
ComPtr<IXmlNode> activation_type_node;
RETURN_IF_FAILED(activation_type_text.As(&activation_type_node));
ComPtr<IXmlNode> activation_type_backup_node;
RETURN_IF_FAILED(activation_type_attribute_node->AppendChild(
activation_type_node.Get(), &activation_type_backup_node));
// Add activation type to the action attributes
ComPtr<IXmlNode> activation_type_attribute_pnode;
RETURN_IF_FAILED(action_attributes.Get()->SetNamedItem(
activation_type_attribute_node.Get(), &activation_type_attribute_pnode));
// Create arguments attribute
ComPtr<IXmlAttribute> arguments_attribute;
ScopedHString arguments_str(L"arguments");
RETURN_IF_FAILED(doc->CreateAttribute(arguments_str, &arguments_attribute));
ComPtr<IXmlNode> arguments_attribute_node;
RETURN_IF_FAILED(arguments_attribute.As(&arguments_attribute_node));
// Set arguments attribute to dismiss
ScopedHString arguments_value(L"dismiss");
if (!arguments_value.success())
return E_FAIL;
ComPtr<IXmlText> arguments_text;
RETURN_IF_FAILED(doc->CreateTextNode(arguments_value, &arguments_text));
ComPtr<IXmlNode> arguments_node;
RETURN_IF_FAILED(arguments_text.As(&arguments_node));
ComPtr<IXmlNode> arguments_backup_node;
RETURN_IF_FAILED(arguments_attribute_node->AppendChild(
arguments_node.Get(), &arguments_backup_node));
// Add arguments to the action attributes
ComPtr<IXmlNode> arguments_attribute_pnode;
RETURN_IF_FAILED(action_attributes.Get()->SetNamedItem(
arguments_attribute_node.Get(), &arguments_attribute_pnode));
// Create content attribute
ComPtr<IXmlAttribute> content_attribute;
ScopedHString content_str(L"content");
RETURN_IF_FAILED(doc->CreateAttribute(content_str, &content_attribute));
ComPtr<IXmlNode> content_attribute_node;
RETURN_IF_FAILED(content_attribute.As(&content_attribute_node));
// Set content attribute to Dismiss
ScopedHString content_value(l10n_util::GetWideString(IDS_APP_CLOSE));
if (!content_value.success())
return E_FAIL;
ComPtr<IXmlText> content_text;
RETURN_IF_FAILED(doc->CreateTextNode(content_value, &content_text));
ComPtr<IXmlNode> content_node;
RETURN_IF_FAILED(content_text.As(&content_node));
ComPtr<IXmlNode> content_backup_node;
RETURN_IF_FAILED(content_attribute_node->AppendChild(content_node.Get(),
&content_backup_node));
// Add content to the action attributes
ComPtr<IXmlNode> content_attribute_pnode;
return action_attributes.Get()->SetNamedItem(content_attribute_node.Get(),
&content_attribute_pnode);
}
HRESULT WindowsToastNotification::SetXmlAudioSilent(IXmlDocument* doc) {
ScopedHString tag(L"toast");
if (!tag.success())
return E_FAIL;
ComPtr<IXmlNodeList> node_list;
RETURN_IF_FAILED(doc->GetElementsByTagName(tag, &node_list));
ComPtr<IXmlNode> root;
RETURN_IF_FAILED(node_list->Item(0, &root));
ComPtr<IXmlElement> audio_element;
ScopedHString audio_str(L"audio");
RETURN_IF_FAILED(doc->CreateElement(audio_str, &audio_element));
ComPtr<IXmlNode> audio_node_tmp;
RETURN_IF_FAILED(audio_element.As(&audio_node_tmp));
// Append audio node to toast xml
ComPtr<IXmlNode> audio_node;
RETURN_IF_FAILED(root->AppendChild(audio_node_tmp.Get(), &audio_node));
// Create silent attribute
ComPtr<IXmlNamedNodeMap> attributes;
RETURN_IF_FAILED(audio_node->get_Attributes(&attributes));
ComPtr<IXmlAttribute> silent_attribute;
ScopedHString silent_str(L"silent");
RETURN_IF_FAILED(doc->CreateAttribute(silent_str, &silent_attribute));
ComPtr<IXmlNode> silent_attribute_node;
RETURN_IF_FAILED(silent_attribute.As(&silent_attribute_node));
// Set silent attribute to true
ScopedHString silent_value(L"true");
if (!silent_value.success())
return E_FAIL;
ComPtr<IXmlText> silent_text;
RETURN_IF_FAILED(doc->CreateTextNode(silent_value, &silent_text));
ComPtr<IXmlNode> silent_node;
RETURN_IF_FAILED(silent_text.As(&silent_node));
ComPtr<IXmlNode> child_node;
RETURN_IF_FAILED(
silent_attribute_node->AppendChild(silent_node.Get(), &child_node));
ComPtr<IXmlNode> silent_attribute_pnode;
return attributes.Get()->SetNamedItem(silent_attribute_node.Get(),
&silent_attribute_pnode);
}
HRESULT WindowsToastNotification::SetXmlText(IXmlDocument* doc,
const std::u16string& text) {
ScopedHString tag;
ComPtr<IXmlNodeList> node_list;
RETURN_IF_FAILED(GetTextNodeList(&tag, doc, &node_list, 1));
ComPtr<IXmlNode> node;
RETURN_IF_FAILED(node_list->Item(0, &node));
return AppendTextToXml(doc, node.Get(), text);
}
HRESULT WindowsToastNotification::SetXmlText(IXmlDocument* doc,
const std::u16string& title,
const std::u16string& body) {
ScopedHString tag;
ComPtr<IXmlNodeList> node_list;
RETURN_IF_FAILED(GetTextNodeList(&tag, doc, &node_list, 2));
ComPtr<IXmlNode> node;
RETURN_IF_FAILED(node_list->Item(0, &node));
RETURN_IF_FAILED(AppendTextToXml(doc, node.Get(), title));
RETURN_IF_FAILED(node_list->Item(1, &node));
return AppendTextToXml(doc, node.Get(), body);
}
HRESULT WindowsToastNotification::SetXmlImage(IXmlDocument* doc,
const std::wstring& icon_path) {
ScopedHString tag(L"image");
if (!tag.success())
return E_FAIL;
ComPtr<IXmlNodeList> node_list;
RETURN_IF_FAILED(doc->GetElementsByTagName(tag, &node_list));
ComPtr<IXmlNode> image_node;
RETURN_IF_FAILED(node_list->Item(0, &image_node));
ComPtr<IXmlNamedNodeMap> attrs;
RETURN_IF_FAILED(image_node->get_Attributes(&attrs));
ScopedHString src(L"src");
if (!src.success())
return E_FAIL;
ComPtr<IXmlNode> src_attr;
RETURN_IF_FAILED(attrs->GetNamedItem(src, &src_attr));
ScopedHString img_path(icon_path.c_str());
if (!img_path.success())
return E_FAIL;
ComPtr<IXmlText> src_text;
RETURN_IF_FAILED(doc->CreateTextNode(img_path, &src_text));
ComPtr<IXmlNode> src_node;
RETURN_IF_FAILED(src_text.As(&src_node));
ComPtr<IXmlNode> child_node;
return src_attr->AppendChild(src_node.Get(), &child_node);
}
HRESULT WindowsToastNotification::GetTextNodeList(ScopedHString* tag,
IXmlDocument* doc,
IXmlNodeList** node_list,
uint32_t req_length) {
tag->Reset(L"text");
if (!tag->success())
return E_FAIL;
RETURN_IF_FAILED(doc->GetElementsByTagName(*tag, node_list));
uint32_t node_length;
RETURN_IF_FAILED((*node_list)->get_Length(&node_length));
return node_length >= req_length;
}
HRESULT WindowsToastNotification::AppendTextToXml(IXmlDocument* doc,
IXmlNode* node,
const std::u16string& text) {
ScopedHString str(base::as_wcstr(text));
if (!str.success())
return E_FAIL;
ComPtr<IXmlText> xml_text;
RETURN_IF_FAILED(doc->CreateTextNode(str, &xml_text));
ComPtr<IXmlNode> text_node;
RETURN_IF_FAILED(xml_text.As(&text_node));
ComPtr<IXmlNode> append_node;
RETURN_IF_FAILED(node->AppendChild(text_node.Get(), &append_node));
return S_OK;
}
HRESULT WindowsToastNotification::XmlDocumentFromString(
const wchar_t* xmlString,
IXmlDocument** doc) {
ComPtr<IXmlDocument> xmlDoc;
RETURN_IF_FAILED(Windows::Foundation::ActivateInstance(
HStringReference(RuntimeClass_Windows_Data_Xml_Dom_XmlDocument).Get(),
&xmlDoc));
ComPtr<IXmlDocumentIO> docIO;
RETURN_IF_FAILED(xmlDoc.As(&docIO));
RETURN_IF_FAILED(docIO->LoadXml(HStringReference(xmlString).Get()));
return xmlDoc.CopyTo(doc);
}
HRESULT WindowsToastNotification::SetupCallbacks(
ABI::Windows::UI::Notifications::IToastNotification* toast) {
event_handler_ = Make<ToastEventHandler>(this);
RETURN_IF_FAILED(
toast->add_Activated(event_handler_.Get(), &activated_token_));
RETURN_IF_FAILED(
toast->add_Dismissed(event_handler_.Get(), &dismissed_token_));
RETURN_IF_FAILED(toast->add_Failed(event_handler_.Get(), &failed_token_));
return S_OK;
}
bool WindowsToastNotification::RemoveCallbacks(
ABI::Windows::UI::Notifications::IToastNotification* toast) {
if (FAILED(toast->remove_Activated(activated_token_)))
return false;
if (FAILED(toast->remove_Dismissed(dismissed_token_)))
return false;
return SUCCEEDED(toast->remove_Failed(failed_token_));
}
/*
/ Toast Event Handler
*/
ToastEventHandler::ToastEventHandler(Notification* notification)
: notification_(notification->GetWeakPtr()) {}
ToastEventHandler::~ToastEventHandler() = default;
IFACEMETHODIMP ToastEventHandler::Invoke(
ABI::Windows::UI::Notifications::IToastNotification* sender,
IInspectable* args) {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&Notification::NotificationClicked, notification_));
if (IsDebuggingNotifications())
LOG(INFO) << "Notification clicked";
return S_OK;
}
IFACEMETHODIMP ToastEventHandler::Invoke(
ABI::Windows::UI::Notifications::IToastNotification* sender,
ABI::Windows::UI::Notifications::IToastDismissedEventArgs* e) {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&Notification::NotificationDismissed, notification_));
if (IsDebuggingNotifications())
LOG(INFO) << "Notification dismissed";
return S_OK;
}
IFACEMETHODIMP ToastEventHandler::Invoke(
ABI::Windows::UI::Notifications::IToastNotification* sender,
ABI::Windows::UI::Notifications::IToastFailedEventArgs* e) {
HRESULT error;
e->get_ErrorCode(&error);
std::string errorMessage =
"Notification failed. HRESULT:" + std::to_string(error);
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&Notification::NotificationFailed,
notification_, errorMessage));
if (IsDebuggingNotifications())
LOG(INFO) << errorMessage;
return S_OK;
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,133 |
[Bug]: notification.close() does not work in Windows after the popup has disappeared
|
### 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.3.0, 27.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 11 22H2 (22621.2361)
### What arch are you using?
x64
### Last Known Working Electron version
11.x
### Expected Behavior
1. Create Notification with `Electron.Notification`.
2. Wait for the notification popup to disappear and be logged to the Windows notification center.
3. Call `Electron.Notification.close()` on it
The notification is removed from the Windows notification center and the "unread" count in the taskbar decreases
### Actual Behavior
The notification remains in the Windows notification center and the unread count does not change.
### Testcase Gist URL
https://gist.github.com/474863b1c8a398ee00a74950596ab0c3
### Additional Information
Duplicated of #29557, #32260 (These issues are marked as "stale", but still occurred)
|
https://github.com/electron/electron/issues/40133
|
https://github.com/electron/electron/pull/40197
|
73a42d0b7bff9b381349c8c32a46623d63471572
|
666907d50d2d62e31e1c3e7329f45e8350fe73cd
| 2023-10-07T04:31:01Z |
c++
| 2023-10-17T23:33:00Z |
shell/browser/notifications/win/windows_toast_notification.h
|
// Copyright (c) 2015 Felix Rieseberg <[email protected]> and Jason Poon
// <[email protected]>. All rights reserved.
// Copyright (c) 2015 Ryan McShane <[email protected]> and Brandon Smith
// <[email protected]>
// Thanks to both of those folks mentioned above who first thought up a bunch of
// this code
// and released it as MIT to the world.
#ifndef ELECTRON_SHELL_BROWSER_NOTIFICATIONS_WIN_WINDOWS_TOAST_NOTIFICATION_H_
#define ELECTRON_SHELL_BROWSER_NOTIFICATIONS_WIN_WINDOWS_TOAST_NOTIFICATION_H_
#include <windows.h>
#include <windows.ui.notifications.h>
#include <wrl/implements.h>
#include <string>
#include "shell/browser/notifications/notification.h"
using Microsoft::WRL::ClassicCom;
using Microsoft::WRL::ComPtr;
using Microsoft::WRL::Make;
using Microsoft::WRL::RuntimeClass;
using Microsoft::WRL::RuntimeClassFlags;
namespace electron {
class ScopedHString;
using DesktopToastActivatedEventHandler =
ABI::Windows::Foundation::ITypedEventHandler<
ABI::Windows::UI::Notifications::ToastNotification*,
IInspectable*>;
using DesktopToastDismissedEventHandler =
ABI::Windows::Foundation::ITypedEventHandler<
ABI::Windows::UI::Notifications::ToastNotification*,
ABI::Windows::UI::Notifications::ToastDismissedEventArgs*>;
using DesktopToastFailedEventHandler =
ABI::Windows::Foundation::ITypedEventHandler<
ABI::Windows::UI::Notifications::ToastNotification*,
ABI::Windows::UI::Notifications::ToastFailedEventArgs*>;
class WindowsToastNotification : public Notification {
public:
// Should only be called by NotificationPresenterWin.
static bool Initialize();
WindowsToastNotification(NotificationDelegate* delegate,
NotificationPresenter* presenter);
~WindowsToastNotification() override;
protected:
// Notification:
void Show(const NotificationOptions& options) override;
void Dismiss() override;
private:
friend class ToastEventHandler;
HRESULT ShowInternal(const NotificationOptions& options);
HRESULT GetToastXml(
ABI::Windows::UI::Notifications::IToastNotificationManagerStatics*
toastManager,
const std::u16string& title,
const std::u16string& msg,
const std::wstring& icon_path,
const std::u16string& timeout_type,
const bool silent,
ABI::Windows::Data::Xml::Dom::IXmlDocument** toast_xml);
HRESULT SetXmlAudioSilent(ABI::Windows::Data::Xml::Dom::IXmlDocument* doc);
HRESULT SetXmlScenarioReminder(
ABI::Windows::Data::Xml::Dom::IXmlDocument* doc);
HRESULT SetXmlText(ABI::Windows::Data::Xml::Dom::IXmlDocument* doc,
const std::u16string& text);
HRESULT SetXmlText(ABI::Windows::Data::Xml::Dom::IXmlDocument* doc,
const std::u16string& title,
const std::u16string& body);
HRESULT SetXmlImage(ABI::Windows::Data::Xml::Dom::IXmlDocument* doc,
const std::wstring& icon_path);
HRESULT GetTextNodeList(
ScopedHString* tag,
ABI::Windows::Data::Xml::Dom::IXmlDocument* doc,
ABI::Windows::Data::Xml::Dom::IXmlNodeList** node_list,
uint32_t req_length);
HRESULT AppendTextToXml(ABI::Windows::Data::Xml::Dom::IXmlDocument* doc,
ABI::Windows::Data::Xml::Dom::IXmlNode* node,
const std::u16string& text);
HRESULT XmlDocumentFromString(
const wchar_t* xmlString,
ABI::Windows::Data::Xml::Dom::IXmlDocument** doc);
HRESULT SetupCallbacks(
ABI::Windows::UI::Notifications::IToastNotification* toast);
bool RemoveCallbacks(
ABI::Windows::UI::Notifications::IToastNotification* toast);
static ComPtr<
ABI::Windows::UI::Notifications::IToastNotificationManagerStatics>
toast_manager_;
static ComPtr<ABI::Windows::UI::Notifications::IToastNotifier>
toast_notifier_;
EventRegistrationToken activated_token_;
EventRegistrationToken dismissed_token_;
EventRegistrationToken failed_token_;
ComPtr<ToastEventHandler> event_handler_;
ComPtr<ABI::Windows::UI::Notifications::IToastNotification>
toast_notification_;
};
class ToastEventHandler : public RuntimeClass<RuntimeClassFlags<ClassicCom>,
DesktopToastActivatedEventHandler,
DesktopToastDismissedEventHandler,
DesktopToastFailedEventHandler> {
public:
explicit ToastEventHandler(Notification* notification);
~ToastEventHandler() override;
// disable copy
ToastEventHandler(const ToastEventHandler&) = delete;
ToastEventHandler& operator=(const ToastEventHandler&) = delete;
IFACEMETHODIMP Invoke(
ABI::Windows::UI::Notifications::IToastNotification* sender,
IInspectable* args) override;
IFACEMETHODIMP Invoke(
ABI::Windows::UI::Notifications::IToastNotification* sender,
ABI::Windows::UI::Notifications::IToastDismissedEventArgs* e) override;
IFACEMETHODIMP Invoke(
ABI::Windows::UI::Notifications::IToastNotification* sender,
ABI::Windows::UI::Notifications::IToastFailedEventArgs* e) override;
private:
base::WeakPtr<Notification> notification_; // weak ref.
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_NOTIFICATIONS_WIN_WINDOWS_TOAST_NOTIFICATION_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,133 |
[Bug]: notification.close() does not work in Windows after the popup has disappeared
|
### 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.3.0, 27.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 11 22H2 (22621.2361)
### What arch are you using?
x64
### Last Known Working Electron version
11.x
### Expected Behavior
1. Create Notification with `Electron.Notification`.
2. Wait for the notification popup to disappear and be logged to the Windows notification center.
3. Call `Electron.Notification.close()` on it
The notification is removed from the Windows notification center and the "unread" count in the taskbar decreases
### Actual Behavior
The notification remains in the Windows notification center and the unread count does not change.
### Testcase Gist URL
https://gist.github.com/474863b1c8a398ee00a74950596ab0c3
### Additional Information
Duplicated of #29557, #32260 (These issues are marked as "stale", but still occurred)
|
https://github.com/electron/electron/issues/40133
|
https://github.com/electron/electron/pull/40197
|
73a42d0b7bff9b381349c8c32a46623d63471572
|
666907d50d2d62e31e1c3e7329f45e8350fe73cd
| 2023-10-07T04:31:01Z |
c++
| 2023-10-17T23:33:00Z |
docs/api/notification.md
|
# Notification
> Create OS desktop notifications
Process: [Main](../glossary.md#main-process)
:::info Renderer process notifications
If you want to show notifications from a renderer process you should use the
[web Notifications API](../tutorial/notifications.md)
:::
## Class: Notification
> Create OS desktop notifications
Process: [Main](../glossary.md#main-process)
`Notification` is an [EventEmitter][event-emitter].
It creates a new `Notification` with native properties as set by the `options`.
### Static Methods
The `Notification` class has the following static methods:
#### `Notification.isSupported()`
Returns `boolean` - Whether or not desktop notifications are supported on the current system
### `new Notification([options])`
* `options` Object (optional)
* `title` string (optional) - A title for the notification, which will be displayed at the top of the notification window when it is shown.
* `subtitle` string (optional) _macOS_ - A subtitle for the notification, which will be displayed below the title.
* `body` string (optional) - The body text of the notification, which will be displayed below the title or subtitle.
* `silent` boolean (optional) - Whether or not to suppress the OS notification noise when showing the notification.
* `icon` (string | [NativeImage](native-image.md)) (optional) - An icon to use in the notification.
* `hasReply` boolean (optional) _macOS_ - Whether or not to add an inline reply option to the notification.
* `timeoutType` string (optional) _Linux_ _Windows_ - The timeout duration of the notification. Can be 'default' or 'never'.
* `replyPlaceholder` string (optional) _macOS_ - The placeholder to write in the inline reply input field.
* `sound` string (optional) _macOS_ - The name of the sound file to play when the notification is shown.
* `urgency` string (optional) _Linux_ - The urgency level of the notification. Can be 'normal', 'critical', or 'low'.
* `actions` [NotificationAction[]](structures/notification-action.md) (optional) _macOS_ - Actions to add to the notification. Please read the available actions and limitations in the `NotificationAction` documentation.
* `closeButtonText` string (optional) _macOS_ - A custom title for the close button of an alert. An empty string will cause the default localized text to be used.
* `toastXml` string (optional) _Windows_ - A custom description of the Notification on Windows superseding all properties above. Provides full customization of design and behavior of the notification.
### Instance Events
Objects created with `new Notification` emit the following events:
:::info
Some events are only available on specific operating systems and are labeled as such.
:::
#### Event: 'show'
Returns:
* `event` Event
Emitted when the notification is shown to the user. Note that this event can be fired
multiple times as a notification can be shown multiple times through the
`show()` method.
#### Event: 'click'
Returns:
* `event` Event
Emitted when the notification is clicked by the user.
#### Event: 'close'
Returns:
* `event` Event
Emitted when the notification is closed by manual intervention from the user.
This event is not guaranteed to be emitted in all cases where the notification
is closed.
#### Event: 'reply' _macOS_
Returns:
* `event` Event
* `reply` string - The string the user entered into the inline reply field.
Emitted when the user clicks the "Reply" button on a notification with `hasReply: true`.
#### Event: 'action' _macOS_
Returns:
* `event` Event
* `index` number - The index of the action that was activated.
#### Event: 'failed' _Windows_
Returns:
* `event` Event
* `error` string - The error encountered during execution of the `show()` method.
Emitted when an error is encountered while creating and showing the native notification.
### Instance Methods
Objects created with the `new Notification()` constructor have the following instance methods:
#### `notification.show()`
Immediately shows the notification to the user. Unlike the web notification API,
instantiating a `new Notification()` does not immediately show it to the user. Instead, you need to
call this method before the OS will display it.
If the notification has been shown before, this method will dismiss the previously
shown notification and create a new one with identical properties.
#### `notification.close()`
Dismisses the notification.
### Instance Properties
#### `notification.title`
A `string` property representing the title of the notification.
#### `notification.subtitle`
A `string` property representing the subtitle of the notification.
#### `notification.body`
A `string` property representing the body of the notification.
#### `notification.replyPlaceholder`
A `string` property representing the reply placeholder of the notification.
#### `notification.sound`
A `string` property representing the sound of the notification.
#### `notification.closeButtonText`
A `string` property representing the close button text of the notification.
#### `notification.silent`
A `boolean` property representing whether the notification is silent.
#### `notification.hasReply`
A `boolean` property representing whether the notification has a reply action.
#### `notification.urgency` _Linux_
A `string` property representing the urgency level of the notification. Can be 'normal', 'critical', or 'low'.
Default is 'low' - see [NotifyUrgency](https://developer-old.gnome.org/notification-spec/#urgency-levels) for more information.
#### `notification.timeoutType` _Linux_ _Windows_
A `string` property representing the type of timeout duration for the notification. Can be 'default' or 'never'.
If `timeoutType` is set to 'never', the notification never expires. It stays open until closed by the calling API or the user.
#### `notification.actions`
A [`NotificationAction[]`](structures/notification-action.md) property representing the actions of the notification.
#### `notification.toastXml` _Windows_
A `string` property representing the custom Toast XML of the notification.
### Playing Sounds
On macOS, you can specify the name of the sound you'd like to play when the
notification is shown. Any of the default sounds (under System Preferences >
Sound) can be used, in addition to custom sound files. Be sure that the sound
file is copied under the app bundle (e.g., `YourApp.app/Contents/Resources`),
or one of the following locations:
* `~/Library/Sounds`
* `/Library/Sounds`
* `/Network/Library/Sounds`
* `/System/Library/Sounds`
See the [`NSSound`](https://developer.apple.com/documentation/appkit/nssound) docs for more information.
[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,133 |
[Bug]: notification.close() does not work in Windows after the popup has disappeared
|
### 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.3.0, 27.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 11 22H2 (22621.2361)
### What arch are you using?
x64
### Last Known Working Electron version
11.x
### Expected Behavior
1. Create Notification with `Electron.Notification`.
2. Wait for the notification popup to disappear and be logged to the Windows notification center.
3. Call `Electron.Notification.close()` on it
The notification is removed from the Windows notification center and the "unread" count in the taskbar decreases
### Actual Behavior
The notification remains in the Windows notification center and the unread count does not change.
### Testcase Gist URL
https://gist.github.com/474863b1c8a398ee00a74950596ab0c3
### Additional Information
Duplicated of #29557, #32260 (These issues are marked as "stale", but still occurred)
|
https://github.com/electron/electron/issues/40133
|
https://github.com/electron/electron/pull/40197
|
73a42d0b7bff9b381349c8c32a46623d63471572
|
666907d50d2d62e31e1c3e7329f45e8350fe73cd
| 2023-10-07T04:31:01Z |
c++
| 2023-10-17T23:33:00Z |
shell/browser/api/electron_api_notification.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_notification.h"
#include "base/strings/utf_string_conversions.h"
#include "base/uuid.h"
#include "gin/handle.h"
#include "shell/browser/api/electron_api_menu.h"
#include "shell/browser/browser.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/node_includes.h"
#include "url/gurl.h"
namespace gin {
template <>
struct Converter<electron::NotificationAction> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::NotificationAction* out) {
gin::Dictionary dict(isolate);
if (!ConvertFromV8(isolate, val, &dict))
return false;
if (!dict.Get("type", &(out->type))) {
return false;
}
dict.Get("text", &(out->text));
return true;
}
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
electron::NotificationAction val) {
auto dict = gin::Dictionary::CreateEmpty(isolate);
dict.Set("text", val.text);
dict.Set("type", val.type);
return ConvertToV8(isolate, dict);
}
};
} // namespace gin
namespace electron::api {
gin::WrapperInfo Notification::kWrapperInfo = {gin::kEmbedderNativeGin};
Notification::Notification(gin::Arguments* args) {
presenter_ = static_cast<ElectronBrowserClient*>(ElectronBrowserClient::Get())
->GetNotificationPresenter();
gin::Dictionary opts(nullptr);
if (args->GetNext(&opts)) {
opts.Get("title", &title_);
opts.Get("subtitle", &subtitle_);
opts.Get("body", &body_);
has_icon_ = opts.Get("icon", &icon_);
if (has_icon_) {
opts.Get("icon", &icon_path_);
}
opts.Get("silent", &silent_);
opts.Get("replyPlaceholder", &reply_placeholder_);
opts.Get("urgency", &urgency_);
opts.Get("hasReply", &has_reply_);
opts.Get("timeoutType", &timeout_type_);
opts.Get("actions", &actions_);
opts.Get("sound", &sound_);
opts.Get("closeButtonText", &close_button_text_);
opts.Get("toastXml", &toast_xml_);
}
}
Notification::~Notification() {
if (notification_)
notification_->set_delegate(nullptr);
}
// static
gin::Handle<Notification> Notification::New(gin_helper::ErrorThrower thrower,
gin::Arguments* args) {
if (!Browser::Get()->is_ready()) {
thrower.ThrowError("Cannot create Notification before app is ready");
return gin::Handle<Notification>();
}
return gin::CreateHandle(thrower.isolate(), new Notification(args));
}
// Getters
std::u16string Notification::GetTitle() const {
return title_;
}
std::u16string Notification::GetSubtitle() const {
return subtitle_;
}
std::u16string Notification::GetBody() const {
return body_;
}
bool Notification::GetSilent() const {
return silent_;
}
bool Notification::GetHasReply() const {
return has_reply_;
}
std::u16string Notification::GetTimeoutType() const {
return timeout_type_;
}
std::u16string Notification::GetReplyPlaceholder() const {
return reply_placeholder_;
}
std::u16string Notification::GetSound() const {
return sound_;
}
std::u16string Notification::GetUrgency() const {
return urgency_;
}
std::vector<electron::NotificationAction> Notification::GetActions() const {
return actions_;
}
std::u16string Notification::GetCloseButtonText() const {
return close_button_text_;
}
std::u16string Notification::GetToastXml() const {
return toast_xml_;
}
// Setters
void Notification::SetTitle(const std::u16string& new_title) {
title_ = new_title;
}
void Notification::SetSubtitle(const std::u16string& new_subtitle) {
subtitle_ = new_subtitle;
}
void Notification::SetBody(const std::u16string& new_body) {
body_ = new_body;
}
void Notification::SetSilent(bool new_silent) {
silent_ = new_silent;
}
void Notification::SetHasReply(bool new_has_reply) {
has_reply_ = new_has_reply;
}
void Notification::SetTimeoutType(const std::u16string& new_timeout_type) {
timeout_type_ = new_timeout_type;
}
void Notification::SetReplyPlaceholder(const std::u16string& new_placeholder) {
reply_placeholder_ = new_placeholder;
}
void Notification::SetSound(const std::u16string& new_sound) {
sound_ = new_sound;
}
void Notification::SetUrgency(const std::u16string& new_urgency) {
urgency_ = new_urgency;
}
void Notification::SetActions(
const std::vector<electron::NotificationAction>& actions) {
actions_ = actions;
}
void Notification::SetCloseButtonText(const std::u16string& text) {
close_button_text_ = text;
}
void Notification::SetToastXml(const std::u16string& new_toast_xml) {
toast_xml_ = new_toast_xml;
}
void Notification::NotificationAction(int index) {
Emit("action", index);
}
void Notification::NotificationClick() {
Emit("click");
}
void Notification::NotificationReplied(const std::string& reply) {
Emit("reply", reply);
}
void Notification::NotificationDisplayed() {
Emit("show");
}
void Notification::NotificationFailed(const std::string& error) {
Emit("failed", error);
}
void Notification::NotificationDestroyed() {}
void Notification::NotificationClosed() {
Emit("close");
}
void Notification::Close() {
if (notification_) {
notification_->Dismiss();
notification_->set_delegate(nullptr);
notification_.reset();
}
}
// Showing notifications
void Notification::Show() {
Close();
if (presenter_) {
notification_ = presenter_->CreateNotification(
this, base::Uuid::GenerateRandomV4().AsLowercaseString());
if (notification_) {
electron::NotificationOptions options;
options.title = title_;
options.subtitle = subtitle_;
options.msg = body_;
options.icon_url = GURL();
options.icon = icon_.AsBitmap();
options.silent = silent_;
options.has_reply = has_reply_;
options.timeout_type = timeout_type_;
options.reply_placeholder = reply_placeholder_;
options.actions = actions_;
options.sound = sound_;
options.close_button_text = close_button_text_;
options.urgency = urgency_;
options.toast_xml = toast_xml_;
notification_->Show(options);
}
}
}
bool Notification::IsSupported() {
return !!static_cast<ElectronBrowserClient*>(ElectronBrowserClient::Get())
->GetNotificationPresenter();
}
void Notification::FillObjectTemplate(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin::ObjectTemplateBuilder(isolate, GetClassName(), templ)
.SetMethod("show", &Notification::Show)
.SetMethod("close", &Notification::Close)
.SetProperty("title", &Notification::GetTitle, &Notification::SetTitle)
.SetProperty("subtitle", &Notification::GetSubtitle,
&Notification::SetSubtitle)
.SetProperty("body", &Notification::GetBody, &Notification::SetBody)
.SetProperty("silent", &Notification::GetSilent, &Notification::SetSilent)
.SetProperty("hasReply", &Notification::GetHasReply,
&Notification::SetHasReply)
.SetProperty("timeoutType", &Notification::GetTimeoutType,
&Notification::SetTimeoutType)
.SetProperty("replyPlaceholder", &Notification::GetReplyPlaceholder,
&Notification::SetReplyPlaceholder)
.SetProperty("urgency", &Notification::GetUrgency,
&Notification::SetUrgency)
.SetProperty("sound", &Notification::GetSound, &Notification::SetSound)
.SetProperty("actions", &Notification::GetActions,
&Notification::SetActions)
.SetProperty("closeButtonText", &Notification::GetCloseButtonText,
&Notification::SetCloseButtonText)
.SetProperty("toastXml", &Notification::GetToastXml,
&Notification::SetToastXml)
.Build();
}
const char* Notification::GetTypeName() {
return GetClassName();
}
} // namespace electron::api
namespace {
using electron::api::Notification;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("Notification", Notification::GetConstructor(context));
dict.SetMethod("isSupported", &Notification::IsSupported);
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_notification, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,133 |
[Bug]: notification.close() does not work in Windows after the popup has disappeared
|
### 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.3.0, 27.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 11 22H2 (22621.2361)
### What arch are you using?
x64
### Last Known Working Electron version
11.x
### Expected Behavior
1. Create Notification with `Electron.Notification`.
2. Wait for the notification popup to disappear and be logged to the Windows notification center.
3. Call `Electron.Notification.close()` on it
The notification is removed from the Windows notification center and the "unread" count in the taskbar decreases
### Actual Behavior
The notification remains in the Windows notification center and the unread count does not change.
### Testcase Gist URL
https://gist.github.com/474863b1c8a398ee00a74950596ab0c3
### Additional Information
Duplicated of #29557, #32260 (These issues are marked as "stale", but still occurred)
|
https://github.com/electron/electron/issues/40133
|
https://github.com/electron/electron/pull/40197
|
73a42d0b7bff9b381349c8c32a46623d63471572
|
666907d50d2d62e31e1c3e7329f45e8350fe73cd
| 2023-10-07T04:31:01Z |
c++
| 2023-10-17T23:33:00Z |
shell/browser/notifications/notification.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/notifications/notification.h"
#include "shell/browser/notifications/notification_delegate.h"
#include "shell/browser/notifications/notification_presenter.h"
namespace electron {
NotificationOptions::NotificationOptions() = default;
NotificationOptions::~NotificationOptions() = default;
Notification::Notification(NotificationDelegate* delegate,
NotificationPresenter* presenter)
: delegate_(delegate), presenter_(presenter) {}
Notification::~Notification() {
if (delegate())
delegate()->NotificationDestroyed();
}
void Notification::NotificationClicked() {
if (delegate())
delegate()->NotificationClick();
Destroy();
}
void Notification::NotificationDismissed() {
if (delegate())
delegate()->NotificationClosed();
Destroy();
}
void Notification::NotificationFailed(const std::string& error) {
if (delegate())
delegate()->NotificationFailed(error);
Destroy();
}
void Notification::Destroy() {
presenter()->RemoveNotification(this);
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,133 |
[Bug]: notification.close() does not work in Windows after the popup has disappeared
|
### 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.3.0, 27.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 11 22H2 (22621.2361)
### What arch are you using?
x64
### Last Known Working Electron version
11.x
### Expected Behavior
1. Create Notification with `Electron.Notification`.
2. Wait for the notification popup to disappear and be logged to the Windows notification center.
3. Call `Electron.Notification.close()` on it
The notification is removed from the Windows notification center and the "unread" count in the taskbar decreases
### Actual Behavior
The notification remains in the Windows notification center and the unread count does not change.
### Testcase Gist URL
https://gist.github.com/474863b1c8a398ee00a74950596ab0c3
### Additional Information
Duplicated of #29557, #32260 (These issues are marked as "stale", but still occurred)
|
https://github.com/electron/electron/issues/40133
|
https://github.com/electron/electron/pull/40197
|
73a42d0b7bff9b381349c8c32a46623d63471572
|
666907d50d2d62e31e1c3e7329f45e8350fe73cd
| 2023-10-07T04:31:01Z |
c++
| 2023-10-17T23:33:00Z |
shell/browser/notifications/notification.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_NOTIFICATIONS_NOTIFICATION_H_
#define ELECTRON_SHELL_BROWSER_NOTIFICATIONS_NOTIFICATION_H_
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "url/gurl.h"
namespace electron {
class NotificationDelegate;
class NotificationPresenter;
struct NotificationAction {
std::u16string type;
std::u16string text;
};
struct NotificationOptions {
std::u16string title;
std::u16string subtitle;
std::u16string msg;
std::string tag;
bool silent;
GURL icon_url;
SkBitmap icon;
bool has_reply;
std::u16string timeout_type;
std::u16string reply_placeholder;
std::u16string sound;
std::u16string urgency; // Linux
std::vector<NotificationAction> actions;
std::u16string close_button_text;
std::u16string toast_xml;
NotificationOptions();
~NotificationOptions();
};
class Notification {
public:
virtual ~Notification();
// Shows the notification.
virtual void Show(const NotificationOptions& options) = 0;
// Closes the notification, this instance will be destroyed after the
// notification gets closed.
virtual void Dismiss() = 0;
// Should be called by derived classes.
void NotificationClicked();
void NotificationDismissed();
void NotificationFailed(const std::string& error = "");
// delete this.
void Destroy();
base::WeakPtr<Notification> GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
void set_delegate(NotificationDelegate* delegate) { delegate_ = delegate; }
void set_notification_id(const std::string& id) { notification_id_ = id; }
NotificationDelegate* delegate() const { return delegate_; }
NotificationPresenter* presenter() const { return presenter_; }
const std::string& notification_id() const { return notification_id_; }
// disable copy
Notification(const Notification&) = delete;
Notification& operator=(const Notification&) = delete;
protected:
Notification(NotificationDelegate* delegate,
NotificationPresenter* presenter);
private:
raw_ptr<NotificationDelegate> delegate_;
raw_ptr<NotificationPresenter> presenter_;
std::string notification_id_;
base::WeakPtrFactory<Notification> weak_factory_{this};
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_NOTIFICATIONS_NOTIFICATION_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,133 |
[Bug]: notification.close() does not work in Windows after the popup has disappeared
|
### 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.3.0, 27.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 11 22H2 (22621.2361)
### What arch are you using?
x64
### Last Known Working Electron version
11.x
### Expected Behavior
1. Create Notification with `Electron.Notification`.
2. Wait for the notification popup to disappear and be logged to the Windows notification center.
3. Call `Electron.Notification.close()` on it
The notification is removed from the Windows notification center and the "unread" count in the taskbar decreases
### Actual Behavior
The notification remains in the Windows notification center and the unread count does not change.
### Testcase Gist URL
https://gist.github.com/474863b1c8a398ee00a74950596ab0c3
### Additional Information
Duplicated of #29557, #32260 (These issues are marked as "stale", but still occurred)
|
https://github.com/electron/electron/issues/40133
|
https://github.com/electron/electron/pull/40197
|
73a42d0b7bff9b381349c8c32a46623d63471572
|
666907d50d2d62e31e1c3e7329f45e8350fe73cd
| 2023-10-07T04:31:01Z |
c++
| 2023-10-17T23:33:00Z |
shell/browser/notifications/win/windows_toast_notification.cc
|
// Copyright (c) 2015 Felix Rieseberg <[email protected]> and Jason Poon
// <[email protected]>. All rights reserved.
// Copyright (c) 2015 Ryan McShane <[email protected]> and Brandon Smith
// <[email protected]>
// Thanks to both of those folks mentioned above who first thought up a bunch of
// this code
// and released it as MIT to the world.
#include "shell/browser/notifications/win/windows_toast_notification.h"
#include <shlobj.h>
#include <wrl\wrappers\corewrappers.h>
#include "base/environment.h"
#include "base/logging.h"
#include "base/strings/string_util_win.h"
#include "base/strings/utf_string_conversions.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "shell/browser/notifications/notification_delegate.h"
#include "shell/browser/notifications/win/notification_presenter_win.h"
#include "shell/browser/win/scoped_hstring.h"
#include "shell/common/application_info.h"
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/strings/grit/ui_strings.h"
using ABI::Windows::Data::Xml::Dom::IXmlAttribute;
using ABI::Windows::Data::Xml::Dom::IXmlDocument;
using ABI::Windows::Data::Xml::Dom::IXmlDocumentIO;
using ABI::Windows::Data::Xml::Dom::IXmlElement;
using ABI::Windows::Data::Xml::Dom::IXmlNamedNodeMap;
using ABI::Windows::Data::Xml::Dom::IXmlNode;
using ABI::Windows::Data::Xml::Dom::IXmlNodeList;
using ABI::Windows::Data::Xml::Dom::IXmlText;
using Microsoft::WRL::Wrappers::HStringReference;
#define RETURN_IF_FAILED(hr) \
do { \
HRESULT _hrTemp = hr; \
if (FAILED(_hrTemp)) { \
return _hrTemp; \
} \
} while (false)
#define REPORT_AND_RETURN_IF_FAILED(hr, msg) \
do { \
HRESULT _hrTemp = hr; \
std::string _msgTemp = msg; \
if (FAILED(_hrTemp)) { \
std::string _err = _msgTemp + ",ERROR " + std::to_string(_hrTemp); \
if (IsDebuggingNotifications()) \
LOG(INFO) << _err; \
Notification::NotificationFailed(_err); \
return _hrTemp; \
} \
} while (false)
namespace electron {
namespace {
bool IsDebuggingNotifications() {
return base::Environment::Create()->HasVar("ELECTRON_DEBUG_NOTIFICATIONS");
}
} // namespace
// static
ComPtr<ABI::Windows::UI::Notifications::IToastNotificationManagerStatics>
WindowsToastNotification::toast_manager_;
// static
ComPtr<ABI::Windows::UI::Notifications::IToastNotifier>
WindowsToastNotification::toast_notifier_;
// static
bool WindowsToastNotification::Initialize() {
// Just initialize, don't care if it fails or already initialized.
Windows::Foundation::Initialize(RO_INIT_MULTITHREADED);
ScopedHString toast_manager_str(
RuntimeClass_Windows_UI_Notifications_ToastNotificationManager);
if (!toast_manager_str.success())
return false;
if (FAILED(Windows::Foundation::GetActivationFactory(toast_manager_str,
&toast_manager_)))
return false;
if (IsRunningInDesktopBridge()) {
// Ironically, the Desktop Bridge / UWP environment
// requires us to not give Windows an appUserModelId.
return SUCCEEDED(toast_manager_->CreateToastNotifier(&toast_notifier_));
} else {
ScopedHString app_id;
if (!GetAppUserModelID(&app_id))
return false;
return SUCCEEDED(
toast_manager_->CreateToastNotifierWithId(app_id, &toast_notifier_));
}
}
WindowsToastNotification::WindowsToastNotification(
NotificationDelegate* delegate,
NotificationPresenter* presenter)
: Notification(delegate, presenter) {}
WindowsToastNotification::~WindowsToastNotification() {
// Remove the notification on exit.
if (toast_notification_) {
RemoveCallbacks(toast_notification_.Get());
}
}
void WindowsToastNotification::Show(const NotificationOptions& options) {
if (SUCCEEDED(ShowInternal(options))) {
if (IsDebuggingNotifications())
LOG(INFO) << "Notification created";
if (delegate())
delegate()->NotificationDisplayed();
}
}
void WindowsToastNotification::Dismiss() {
if (IsDebuggingNotifications())
LOG(INFO) << "Hiding notification";
toast_notifier_->Hide(toast_notification_.Get());
}
HRESULT WindowsToastNotification::ShowInternal(
const NotificationOptions& options) {
ComPtr<IXmlDocument> toast_xml;
// The custom xml takes priority over the preset template.
if (!options.toast_xml.empty()) {
REPORT_AND_RETURN_IF_FAILED(
XmlDocumentFromString(base::as_wcstr(options.toast_xml), &toast_xml),
"XML: Invalid XML");
} else {
auto* presenter_win = static_cast<NotificationPresenterWin*>(presenter());
std::wstring icon_path =
presenter_win->SaveIconToFilesystem(options.icon, options.icon_url);
REPORT_AND_RETURN_IF_FAILED(
GetToastXml(toast_manager_.Get(), options.title, options.msg, icon_path,
options.timeout_type, options.silent, &toast_xml),
"XML: Failed to create XML document");
}
ScopedHString toast_str(
RuntimeClass_Windows_UI_Notifications_ToastNotification);
if (!toast_str.success()) {
NotificationFailed("Creating ScopedHString failed");
return E_FAIL;
}
ComPtr<ABI::Windows::UI::Notifications::IToastNotificationFactory>
toast_factory;
REPORT_AND_RETURN_IF_FAILED(
Windows::Foundation::GetActivationFactory(toast_str, &toast_factory),
"WinAPI: GetActivationFactory failed");
REPORT_AND_RETURN_IF_FAILED(toast_factory->CreateToastNotification(
toast_xml.Get(), &toast_notification_),
"WinAPI: CreateToastNotification failed");
REPORT_AND_RETURN_IF_FAILED(SetupCallbacks(toast_notification_.Get()),
"WinAPI: SetupCallbacks failed");
REPORT_AND_RETURN_IF_FAILED(toast_notifier_->Show(toast_notification_.Get()),
"WinAPI: Show failed");
return S_OK;
}
HRESULT WindowsToastNotification::GetToastXml(
ABI::Windows::UI::Notifications::IToastNotificationManagerStatics*
toastManager,
const std::u16string& title,
const std::u16string& msg,
const std::wstring& icon_path,
const std::u16string& timeout_type,
bool silent,
IXmlDocument** toast_xml) {
ABI::Windows::UI::Notifications::ToastTemplateType template_type;
if (title.empty() || msg.empty()) {
// Single line toast.
template_type =
icon_path.empty()
? ABI::Windows::UI::Notifications::ToastTemplateType_ToastText01
: ABI::Windows::UI::Notifications::
ToastTemplateType_ToastImageAndText01;
REPORT_AND_RETURN_IF_FAILED(
toast_manager_->GetTemplateContent(template_type, toast_xml),
"XML: Fetching XML ToastImageAndText01 template failed");
std::u16string toastMsg = title.empty() ? msg : title;
// we can't create an empty notification
toastMsg = toastMsg.empty() ? u"[no message]" : toastMsg;
REPORT_AND_RETURN_IF_FAILED(
SetXmlText(*toast_xml, toastMsg),
"XML: Filling XML ToastImageAndText01 template failed");
} else {
// Title and body toast.
template_type =
icon_path.empty()
? ABI::Windows::UI::Notifications::ToastTemplateType_ToastText02
: ABI::Windows::UI::Notifications::
ToastTemplateType_ToastImageAndText02;
REPORT_AND_RETURN_IF_FAILED(
toastManager->GetTemplateContent(template_type, toast_xml),
"XML: Fetching XML ToastImageAndText02 template failed");
REPORT_AND_RETURN_IF_FAILED(
SetXmlText(*toast_xml, title, msg),
"XML: Filling XML ToastImageAndText02 template failed");
}
// Configure the toast's timeout settings
if (timeout_type == u"never") {
REPORT_AND_RETURN_IF_FAILED(
(SetXmlScenarioReminder(*toast_xml)),
"XML: Setting \"scenario\" option on notification failed");
}
// Configure the toast's notification sound
if (silent) {
REPORT_AND_RETURN_IF_FAILED(
SetXmlAudioSilent(*toast_xml),
"XML: Setting \"silent\" option on notification failed");
}
// Configure the toast's image
if (!icon_path.empty()) {
REPORT_AND_RETURN_IF_FAILED(
SetXmlImage(*toast_xml, icon_path),
"XML: Setting \"icon\" option on notification failed");
}
return S_OK;
}
HRESULT WindowsToastNotification::SetXmlScenarioReminder(IXmlDocument* doc) {
ScopedHString tag(L"toast");
if (!tag.success())
return false;
ComPtr<IXmlNodeList> node_list;
RETURN_IF_FAILED(doc->GetElementsByTagName(tag, &node_list));
// Check that root "toast" node exists
ComPtr<IXmlNode> root;
RETURN_IF_FAILED(node_list->Item(0, &root));
// get attributes of root "toast" node
ComPtr<IXmlNamedNodeMap> toast_attributes;
RETURN_IF_FAILED(root->get_Attributes(&toast_attributes));
ComPtr<IXmlAttribute> scenario_attribute;
ScopedHString scenario_str(L"scenario");
RETURN_IF_FAILED(doc->CreateAttribute(scenario_str, &scenario_attribute));
ComPtr<IXmlNode> scenario_attribute_node;
RETURN_IF_FAILED(scenario_attribute.As(&scenario_attribute_node));
ScopedHString scenario_value(L"reminder");
if (!scenario_value.success())
return E_FAIL;
ComPtr<IXmlText> scenario_text;
RETURN_IF_FAILED(doc->CreateTextNode(scenario_value, &scenario_text));
ComPtr<IXmlNode> scenario_node;
RETURN_IF_FAILED(scenario_text.As(&scenario_node));
ComPtr<IXmlNode> scenario_backup_node;
RETURN_IF_FAILED(scenario_attribute_node->AppendChild(scenario_node.Get(),
&scenario_backup_node));
ComPtr<IXmlNode> scenario_attribute_pnode;
RETURN_IF_FAILED(toast_attributes.Get()->SetNamedItem(
scenario_attribute_node.Get(), &scenario_attribute_pnode));
// Create "actions" wrapper
ComPtr<IXmlElement> actions_wrapper_element;
ScopedHString actions_wrapper_str(L"actions");
RETURN_IF_FAILED(
doc->CreateElement(actions_wrapper_str, &actions_wrapper_element));
ComPtr<IXmlNode> actions_wrapper_node_tmp;
RETURN_IF_FAILED(actions_wrapper_element.As(&actions_wrapper_node_tmp));
// Append actions wrapper node to toast xml
ComPtr<IXmlNode> actions_wrapper_node;
RETURN_IF_FAILED(
root->AppendChild(actions_wrapper_node_tmp.Get(), &actions_wrapper_node));
ComPtr<IXmlNamedNodeMap> attributes_actions_wrapper;
RETURN_IF_FAILED(
actions_wrapper_node->get_Attributes(&attributes_actions_wrapper));
// Add a "Dismiss" button
// Create "action" tag
ComPtr<IXmlElement> action_element;
ScopedHString action_str(L"action");
RETURN_IF_FAILED(doc->CreateElement(action_str, &action_element));
ComPtr<IXmlNode> action_node_tmp;
RETURN_IF_FAILED(action_element.As(&action_node_tmp));
// Append action node to actions wrapper in toast xml
ComPtr<IXmlNode> action_node;
RETURN_IF_FAILED(
actions_wrapper_node->AppendChild(action_node_tmp.Get(), &action_node));
// Setup attributes for action
ComPtr<IXmlNamedNodeMap> action_attributes;
RETURN_IF_FAILED(action_node->get_Attributes(&action_attributes));
// Create activationType attribute
ComPtr<IXmlAttribute> activation_type_attribute;
ScopedHString activation_type_str(L"activationType");
RETURN_IF_FAILED(
doc->CreateAttribute(activation_type_str, &activation_type_attribute));
ComPtr<IXmlNode> activation_type_attribute_node;
RETURN_IF_FAILED(
activation_type_attribute.As(&activation_type_attribute_node));
// Set activationType attribute to system
ScopedHString activation_type_value(L"system");
if (!activation_type_value.success())
return E_FAIL;
ComPtr<IXmlText> activation_type_text;
RETURN_IF_FAILED(
doc->CreateTextNode(activation_type_value, &activation_type_text));
ComPtr<IXmlNode> activation_type_node;
RETURN_IF_FAILED(activation_type_text.As(&activation_type_node));
ComPtr<IXmlNode> activation_type_backup_node;
RETURN_IF_FAILED(activation_type_attribute_node->AppendChild(
activation_type_node.Get(), &activation_type_backup_node));
// Add activation type to the action attributes
ComPtr<IXmlNode> activation_type_attribute_pnode;
RETURN_IF_FAILED(action_attributes.Get()->SetNamedItem(
activation_type_attribute_node.Get(), &activation_type_attribute_pnode));
// Create arguments attribute
ComPtr<IXmlAttribute> arguments_attribute;
ScopedHString arguments_str(L"arguments");
RETURN_IF_FAILED(doc->CreateAttribute(arguments_str, &arguments_attribute));
ComPtr<IXmlNode> arguments_attribute_node;
RETURN_IF_FAILED(arguments_attribute.As(&arguments_attribute_node));
// Set arguments attribute to dismiss
ScopedHString arguments_value(L"dismiss");
if (!arguments_value.success())
return E_FAIL;
ComPtr<IXmlText> arguments_text;
RETURN_IF_FAILED(doc->CreateTextNode(arguments_value, &arguments_text));
ComPtr<IXmlNode> arguments_node;
RETURN_IF_FAILED(arguments_text.As(&arguments_node));
ComPtr<IXmlNode> arguments_backup_node;
RETURN_IF_FAILED(arguments_attribute_node->AppendChild(
arguments_node.Get(), &arguments_backup_node));
// Add arguments to the action attributes
ComPtr<IXmlNode> arguments_attribute_pnode;
RETURN_IF_FAILED(action_attributes.Get()->SetNamedItem(
arguments_attribute_node.Get(), &arguments_attribute_pnode));
// Create content attribute
ComPtr<IXmlAttribute> content_attribute;
ScopedHString content_str(L"content");
RETURN_IF_FAILED(doc->CreateAttribute(content_str, &content_attribute));
ComPtr<IXmlNode> content_attribute_node;
RETURN_IF_FAILED(content_attribute.As(&content_attribute_node));
// Set content attribute to Dismiss
ScopedHString content_value(l10n_util::GetWideString(IDS_APP_CLOSE));
if (!content_value.success())
return E_FAIL;
ComPtr<IXmlText> content_text;
RETURN_IF_FAILED(doc->CreateTextNode(content_value, &content_text));
ComPtr<IXmlNode> content_node;
RETURN_IF_FAILED(content_text.As(&content_node));
ComPtr<IXmlNode> content_backup_node;
RETURN_IF_FAILED(content_attribute_node->AppendChild(content_node.Get(),
&content_backup_node));
// Add content to the action attributes
ComPtr<IXmlNode> content_attribute_pnode;
return action_attributes.Get()->SetNamedItem(content_attribute_node.Get(),
&content_attribute_pnode);
}
HRESULT WindowsToastNotification::SetXmlAudioSilent(IXmlDocument* doc) {
ScopedHString tag(L"toast");
if (!tag.success())
return E_FAIL;
ComPtr<IXmlNodeList> node_list;
RETURN_IF_FAILED(doc->GetElementsByTagName(tag, &node_list));
ComPtr<IXmlNode> root;
RETURN_IF_FAILED(node_list->Item(0, &root));
ComPtr<IXmlElement> audio_element;
ScopedHString audio_str(L"audio");
RETURN_IF_FAILED(doc->CreateElement(audio_str, &audio_element));
ComPtr<IXmlNode> audio_node_tmp;
RETURN_IF_FAILED(audio_element.As(&audio_node_tmp));
// Append audio node to toast xml
ComPtr<IXmlNode> audio_node;
RETURN_IF_FAILED(root->AppendChild(audio_node_tmp.Get(), &audio_node));
// Create silent attribute
ComPtr<IXmlNamedNodeMap> attributes;
RETURN_IF_FAILED(audio_node->get_Attributes(&attributes));
ComPtr<IXmlAttribute> silent_attribute;
ScopedHString silent_str(L"silent");
RETURN_IF_FAILED(doc->CreateAttribute(silent_str, &silent_attribute));
ComPtr<IXmlNode> silent_attribute_node;
RETURN_IF_FAILED(silent_attribute.As(&silent_attribute_node));
// Set silent attribute to true
ScopedHString silent_value(L"true");
if (!silent_value.success())
return E_FAIL;
ComPtr<IXmlText> silent_text;
RETURN_IF_FAILED(doc->CreateTextNode(silent_value, &silent_text));
ComPtr<IXmlNode> silent_node;
RETURN_IF_FAILED(silent_text.As(&silent_node));
ComPtr<IXmlNode> child_node;
RETURN_IF_FAILED(
silent_attribute_node->AppendChild(silent_node.Get(), &child_node));
ComPtr<IXmlNode> silent_attribute_pnode;
return attributes.Get()->SetNamedItem(silent_attribute_node.Get(),
&silent_attribute_pnode);
}
HRESULT WindowsToastNotification::SetXmlText(IXmlDocument* doc,
const std::u16string& text) {
ScopedHString tag;
ComPtr<IXmlNodeList> node_list;
RETURN_IF_FAILED(GetTextNodeList(&tag, doc, &node_list, 1));
ComPtr<IXmlNode> node;
RETURN_IF_FAILED(node_list->Item(0, &node));
return AppendTextToXml(doc, node.Get(), text);
}
HRESULT WindowsToastNotification::SetXmlText(IXmlDocument* doc,
const std::u16string& title,
const std::u16string& body) {
ScopedHString tag;
ComPtr<IXmlNodeList> node_list;
RETURN_IF_FAILED(GetTextNodeList(&tag, doc, &node_list, 2));
ComPtr<IXmlNode> node;
RETURN_IF_FAILED(node_list->Item(0, &node));
RETURN_IF_FAILED(AppendTextToXml(doc, node.Get(), title));
RETURN_IF_FAILED(node_list->Item(1, &node));
return AppendTextToXml(doc, node.Get(), body);
}
HRESULT WindowsToastNotification::SetXmlImage(IXmlDocument* doc,
const std::wstring& icon_path) {
ScopedHString tag(L"image");
if (!tag.success())
return E_FAIL;
ComPtr<IXmlNodeList> node_list;
RETURN_IF_FAILED(doc->GetElementsByTagName(tag, &node_list));
ComPtr<IXmlNode> image_node;
RETURN_IF_FAILED(node_list->Item(0, &image_node));
ComPtr<IXmlNamedNodeMap> attrs;
RETURN_IF_FAILED(image_node->get_Attributes(&attrs));
ScopedHString src(L"src");
if (!src.success())
return E_FAIL;
ComPtr<IXmlNode> src_attr;
RETURN_IF_FAILED(attrs->GetNamedItem(src, &src_attr));
ScopedHString img_path(icon_path.c_str());
if (!img_path.success())
return E_FAIL;
ComPtr<IXmlText> src_text;
RETURN_IF_FAILED(doc->CreateTextNode(img_path, &src_text));
ComPtr<IXmlNode> src_node;
RETURN_IF_FAILED(src_text.As(&src_node));
ComPtr<IXmlNode> child_node;
return src_attr->AppendChild(src_node.Get(), &child_node);
}
HRESULT WindowsToastNotification::GetTextNodeList(ScopedHString* tag,
IXmlDocument* doc,
IXmlNodeList** node_list,
uint32_t req_length) {
tag->Reset(L"text");
if (!tag->success())
return E_FAIL;
RETURN_IF_FAILED(doc->GetElementsByTagName(*tag, node_list));
uint32_t node_length;
RETURN_IF_FAILED((*node_list)->get_Length(&node_length));
return node_length >= req_length;
}
HRESULT WindowsToastNotification::AppendTextToXml(IXmlDocument* doc,
IXmlNode* node,
const std::u16string& text) {
ScopedHString str(base::as_wcstr(text));
if (!str.success())
return E_FAIL;
ComPtr<IXmlText> xml_text;
RETURN_IF_FAILED(doc->CreateTextNode(str, &xml_text));
ComPtr<IXmlNode> text_node;
RETURN_IF_FAILED(xml_text.As(&text_node));
ComPtr<IXmlNode> append_node;
RETURN_IF_FAILED(node->AppendChild(text_node.Get(), &append_node));
return S_OK;
}
HRESULT WindowsToastNotification::XmlDocumentFromString(
const wchar_t* xmlString,
IXmlDocument** doc) {
ComPtr<IXmlDocument> xmlDoc;
RETURN_IF_FAILED(Windows::Foundation::ActivateInstance(
HStringReference(RuntimeClass_Windows_Data_Xml_Dom_XmlDocument).Get(),
&xmlDoc));
ComPtr<IXmlDocumentIO> docIO;
RETURN_IF_FAILED(xmlDoc.As(&docIO));
RETURN_IF_FAILED(docIO->LoadXml(HStringReference(xmlString).Get()));
return xmlDoc.CopyTo(doc);
}
HRESULT WindowsToastNotification::SetupCallbacks(
ABI::Windows::UI::Notifications::IToastNotification* toast) {
event_handler_ = Make<ToastEventHandler>(this);
RETURN_IF_FAILED(
toast->add_Activated(event_handler_.Get(), &activated_token_));
RETURN_IF_FAILED(
toast->add_Dismissed(event_handler_.Get(), &dismissed_token_));
RETURN_IF_FAILED(toast->add_Failed(event_handler_.Get(), &failed_token_));
return S_OK;
}
bool WindowsToastNotification::RemoveCallbacks(
ABI::Windows::UI::Notifications::IToastNotification* toast) {
if (FAILED(toast->remove_Activated(activated_token_)))
return false;
if (FAILED(toast->remove_Dismissed(dismissed_token_)))
return false;
return SUCCEEDED(toast->remove_Failed(failed_token_));
}
/*
/ Toast Event Handler
*/
ToastEventHandler::ToastEventHandler(Notification* notification)
: notification_(notification->GetWeakPtr()) {}
ToastEventHandler::~ToastEventHandler() = default;
IFACEMETHODIMP ToastEventHandler::Invoke(
ABI::Windows::UI::Notifications::IToastNotification* sender,
IInspectable* args) {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&Notification::NotificationClicked, notification_));
if (IsDebuggingNotifications())
LOG(INFO) << "Notification clicked";
return S_OK;
}
IFACEMETHODIMP ToastEventHandler::Invoke(
ABI::Windows::UI::Notifications::IToastNotification* sender,
ABI::Windows::UI::Notifications::IToastDismissedEventArgs* e) {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&Notification::NotificationDismissed, notification_));
if (IsDebuggingNotifications())
LOG(INFO) << "Notification dismissed";
return S_OK;
}
IFACEMETHODIMP ToastEventHandler::Invoke(
ABI::Windows::UI::Notifications::IToastNotification* sender,
ABI::Windows::UI::Notifications::IToastFailedEventArgs* e) {
HRESULT error;
e->get_ErrorCode(&error);
std::string errorMessage =
"Notification failed. HRESULT:" + std::to_string(error);
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&Notification::NotificationFailed,
notification_, errorMessage));
if (IsDebuggingNotifications())
LOG(INFO) << errorMessage;
return S_OK;
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,133 |
[Bug]: notification.close() does not work in Windows after the popup has disappeared
|
### 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.3.0, 27.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 11 22H2 (22621.2361)
### What arch are you using?
x64
### Last Known Working Electron version
11.x
### Expected Behavior
1. Create Notification with `Electron.Notification`.
2. Wait for the notification popup to disappear and be logged to the Windows notification center.
3. Call `Electron.Notification.close()` on it
The notification is removed from the Windows notification center and the "unread" count in the taskbar decreases
### Actual Behavior
The notification remains in the Windows notification center and the unread count does not change.
### Testcase Gist URL
https://gist.github.com/474863b1c8a398ee00a74950596ab0c3
### Additional Information
Duplicated of #29557, #32260 (These issues are marked as "stale", but still occurred)
|
https://github.com/electron/electron/issues/40133
|
https://github.com/electron/electron/pull/40197
|
73a42d0b7bff9b381349c8c32a46623d63471572
|
666907d50d2d62e31e1c3e7329f45e8350fe73cd
| 2023-10-07T04:31:01Z |
c++
| 2023-10-17T23:33:00Z |
shell/browser/notifications/win/windows_toast_notification.h
|
// Copyright (c) 2015 Felix Rieseberg <[email protected]> and Jason Poon
// <[email protected]>. All rights reserved.
// Copyright (c) 2015 Ryan McShane <[email protected]> and Brandon Smith
// <[email protected]>
// Thanks to both of those folks mentioned above who first thought up a bunch of
// this code
// and released it as MIT to the world.
#ifndef ELECTRON_SHELL_BROWSER_NOTIFICATIONS_WIN_WINDOWS_TOAST_NOTIFICATION_H_
#define ELECTRON_SHELL_BROWSER_NOTIFICATIONS_WIN_WINDOWS_TOAST_NOTIFICATION_H_
#include <windows.h>
#include <windows.ui.notifications.h>
#include <wrl/implements.h>
#include <string>
#include "shell/browser/notifications/notification.h"
using Microsoft::WRL::ClassicCom;
using Microsoft::WRL::ComPtr;
using Microsoft::WRL::Make;
using Microsoft::WRL::RuntimeClass;
using Microsoft::WRL::RuntimeClassFlags;
namespace electron {
class ScopedHString;
using DesktopToastActivatedEventHandler =
ABI::Windows::Foundation::ITypedEventHandler<
ABI::Windows::UI::Notifications::ToastNotification*,
IInspectable*>;
using DesktopToastDismissedEventHandler =
ABI::Windows::Foundation::ITypedEventHandler<
ABI::Windows::UI::Notifications::ToastNotification*,
ABI::Windows::UI::Notifications::ToastDismissedEventArgs*>;
using DesktopToastFailedEventHandler =
ABI::Windows::Foundation::ITypedEventHandler<
ABI::Windows::UI::Notifications::ToastNotification*,
ABI::Windows::UI::Notifications::ToastFailedEventArgs*>;
class WindowsToastNotification : public Notification {
public:
// Should only be called by NotificationPresenterWin.
static bool Initialize();
WindowsToastNotification(NotificationDelegate* delegate,
NotificationPresenter* presenter);
~WindowsToastNotification() override;
protected:
// Notification:
void Show(const NotificationOptions& options) override;
void Dismiss() override;
private:
friend class ToastEventHandler;
HRESULT ShowInternal(const NotificationOptions& options);
HRESULT GetToastXml(
ABI::Windows::UI::Notifications::IToastNotificationManagerStatics*
toastManager,
const std::u16string& title,
const std::u16string& msg,
const std::wstring& icon_path,
const std::u16string& timeout_type,
const bool silent,
ABI::Windows::Data::Xml::Dom::IXmlDocument** toast_xml);
HRESULT SetXmlAudioSilent(ABI::Windows::Data::Xml::Dom::IXmlDocument* doc);
HRESULT SetXmlScenarioReminder(
ABI::Windows::Data::Xml::Dom::IXmlDocument* doc);
HRESULT SetXmlText(ABI::Windows::Data::Xml::Dom::IXmlDocument* doc,
const std::u16string& text);
HRESULT SetXmlText(ABI::Windows::Data::Xml::Dom::IXmlDocument* doc,
const std::u16string& title,
const std::u16string& body);
HRESULT SetXmlImage(ABI::Windows::Data::Xml::Dom::IXmlDocument* doc,
const std::wstring& icon_path);
HRESULT GetTextNodeList(
ScopedHString* tag,
ABI::Windows::Data::Xml::Dom::IXmlDocument* doc,
ABI::Windows::Data::Xml::Dom::IXmlNodeList** node_list,
uint32_t req_length);
HRESULT AppendTextToXml(ABI::Windows::Data::Xml::Dom::IXmlDocument* doc,
ABI::Windows::Data::Xml::Dom::IXmlNode* node,
const std::u16string& text);
HRESULT XmlDocumentFromString(
const wchar_t* xmlString,
ABI::Windows::Data::Xml::Dom::IXmlDocument** doc);
HRESULT SetupCallbacks(
ABI::Windows::UI::Notifications::IToastNotification* toast);
bool RemoveCallbacks(
ABI::Windows::UI::Notifications::IToastNotification* toast);
static ComPtr<
ABI::Windows::UI::Notifications::IToastNotificationManagerStatics>
toast_manager_;
static ComPtr<ABI::Windows::UI::Notifications::IToastNotifier>
toast_notifier_;
EventRegistrationToken activated_token_;
EventRegistrationToken dismissed_token_;
EventRegistrationToken failed_token_;
ComPtr<ToastEventHandler> event_handler_;
ComPtr<ABI::Windows::UI::Notifications::IToastNotification>
toast_notification_;
};
class ToastEventHandler : public RuntimeClass<RuntimeClassFlags<ClassicCom>,
DesktopToastActivatedEventHandler,
DesktopToastDismissedEventHandler,
DesktopToastFailedEventHandler> {
public:
explicit ToastEventHandler(Notification* notification);
~ToastEventHandler() override;
// disable copy
ToastEventHandler(const ToastEventHandler&) = delete;
ToastEventHandler& operator=(const ToastEventHandler&) = delete;
IFACEMETHODIMP Invoke(
ABI::Windows::UI::Notifications::IToastNotification* sender,
IInspectable* args) override;
IFACEMETHODIMP Invoke(
ABI::Windows::UI::Notifications::IToastNotification* sender,
ABI::Windows::UI::Notifications::IToastDismissedEventArgs* e) override;
IFACEMETHODIMP Invoke(
ABI::Windows::UI::Notifications::IToastNotification* sender,
ABI::Windows::UI::Notifications::IToastFailedEventArgs* e) override;
private:
base::WeakPtr<Notification> notification_; // weak ref.
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_NOTIFICATIONS_WIN_WINDOWS_TOAST_NOTIFICATION_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,406 |
[Bug]: the example in the document of represented file creates BrowserWindow twice
|
doc link: https://www.electronjs.org/docs/latest/tutorial/represented-file
code: https://github.com/electron/electron/blob/d8e7457ab0fa13b16d7c8e10395dd315e6fe2077/docs/fiddles/features/represented-file/main.js#L4-L18
The code in the example creates BrowserWindow both in the `createWindow` function and after `app.whenReady()`, which not loads `index.html` properly.
|
https://github.com/electron/electron/issues/38406
|
https://github.com/electron/electron/pull/40233
|
666907d50d2d62e31e1c3e7329f45e8350fe73cd
|
09bab60a9eb110b031330545885bf07205492a1c
| 2023-05-23T06:45:31Z |
c++
| 2023-10-18T09:32:10Z |
docs/fiddles/features/represented-file/main.js
|
const { app, BrowserWindow } = require('electron/main')
const os = require('node:os')
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
const win = new BrowserWindow()
win.setRepresentedFilename(os.homedir())
win.setDocumentEdited(true)
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,406 |
[Bug]: the example in the document of represented file creates BrowserWindow twice
|
doc link: https://www.electronjs.org/docs/latest/tutorial/represented-file
code: https://github.com/electron/electron/blob/d8e7457ab0fa13b16d7c8e10395dd315e6fe2077/docs/fiddles/features/represented-file/main.js#L4-L18
The code in the example creates BrowserWindow both in the `createWindow` function and after `app.whenReady()`, which not loads `index.html` properly.
|
https://github.com/electron/electron/issues/38406
|
https://github.com/electron/electron/pull/40233
|
666907d50d2d62e31e1c3e7329f45e8350fe73cd
|
09bab60a9eb110b031330545885bf07205492a1c
| 2023-05-23T06:45:31Z |
c++
| 2023-10-18T09:32:10Z |
docs/fiddles/features/represented-file/main.js
|
const { app, BrowserWindow } = require('electron/main')
const os = require('node:os')
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
const win = new BrowserWindow()
win.setRepresentedFilename(os.homedir())
win.setDocumentEdited(true)
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 39,891 |
[Bug]: NativeImage methods returned by capturePage fail with "Error: Illegal invocation"
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Ubuntu
### Operating System Version
Ubuntu 23.04
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
While calling `<webview-tag>.capturePage()` from renderer process, we should be able to run methods from the returned NativeImage (like `.getSize()`)
### Actual Behavior
While calling `<webview-tag>.capturePage()` from a renderer process, all of the NativeImage methods return the following error. In this example we call `.getSize()`:
```
Uncaught (in promise) Error: Illegal invocation: Function must be called on an object of type NativeImage
```
**Code snippet**
```js
const webviewElement = document.getElementById("webview")
webviewElement.capturePage()
.then((image) => console.log(image.getSize()))
```
**To reproduce**
**1.** Create a webview element in a page (BrowserView) and make set the id-attribute to `webview`
**2.** Execute the snippet above
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39891
|
https://github.com/electron/electron/pull/39978
|
5b105f911f7aa134ee44558fefaf171360d3d9d2
|
fd2861117e04a3c62bfab67a1b50cb9c3a55cd4d
| 2023-09-18T10:48:18Z |
c++
| 2023-10-18T14:21:42Z |
shell/renderer/api/electron_api_context_bridge.cc
|
// Copyright (c) 2019 Slack Technologies, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/renderer/api/electron_api_context_bridge.h"
#include <memory>
#include <set>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "base/containers/contains.h"
#include "base/feature_list.h"
#include "base/no_destructor.h"
#include "base/strings/string_number_conversions.h"
#include "base/trace_event/trace_event.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_frame_observer.h"
#include "shell/common/api/object_life_monitor.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/node_includes.h"
#include "shell/common/world_ids.h"
#include "third_party/blink/public/web/web_blob.h"
#include "third_party/blink/public/web/web_element.h"
#include "third_party/blink/public/web/web_local_frame.h"
namespace features {
const base::Feature kContextBridgeMutability{"ContextBridgeMutability",
base::FEATURE_DISABLED_BY_DEFAULT};
}
namespace electron {
content::RenderFrame* GetRenderFrame(v8::Local<v8::Object> value);
namespace api {
namespace context_bridge {
const char kProxyFunctionPrivateKey[] = "electron_contextBridge_proxy_fn";
const char kSupportsDynamicPropertiesPrivateKey[] =
"electron_contextBridge_supportsDynamicProperties";
const char kOriginalFunctionPrivateKey[] = "electron_contextBridge_original_fn";
} // namespace context_bridge
namespace {
static int kMaxRecursion = 1000;
// Returns true if |maybe| is both a value, and that value is true.
inline bool IsTrue(v8::Maybe<bool> maybe) {
return maybe.IsJust() && maybe.FromJust();
}
// Sourced from "extensions/renderer/v8_schema_registry.cc"
// Recursively freezes every v8 object on |object|.
bool DeepFreeze(const v8::Local<v8::Object>& object,
const v8::Local<v8::Context>& context,
std::set<int> frozen = std::set<int>()) {
int hash = object->GetIdentityHash();
if (base::Contains(frozen, hash))
return true;
frozen.insert(hash);
v8::Local<v8::Array> property_names =
object->GetOwnPropertyNames(context).ToLocalChecked();
for (uint32_t i = 0; i < property_names->Length(); ++i) {
v8::Local<v8::Value> child =
object->Get(context, property_names->Get(context, i).ToLocalChecked())
.ToLocalChecked();
if (child->IsObject() && !child->IsTypedArray()) {
if (!DeepFreeze(child.As<v8::Object>(), context, frozen))
return false;
}
}
return IsTrue(
object->SetIntegrityLevel(context, v8::IntegrityLevel::kFrozen));
}
bool IsPlainObject(const v8::Local<v8::Value>& object) {
if (!object->IsObject())
return false;
return !(object->IsNullOrUndefined() || object->IsDate() ||
object->IsArgumentsObject() || object->IsBigIntObject() ||
object->IsBooleanObject() || object->IsNumberObject() ||
object->IsStringObject() || object->IsSymbolObject() ||
object->IsNativeError() || object->IsRegExp() ||
object->IsPromise() || object->IsMap() || object->IsSet() ||
object->IsMapIterator() || object->IsSetIterator() ||
object->IsWeakMap() || object->IsWeakSet() ||
object->IsArrayBuffer() || object->IsArrayBufferView() ||
object->IsArray() || object->IsDataView() ||
object->IsSharedArrayBuffer() || object->IsGeneratorObject() ||
object->IsWasmModuleObject() || object->IsWasmMemoryObject() ||
object->IsModuleNamespaceObject() || object->IsProxy());
}
bool IsPlainArray(const v8::Local<v8::Value>& arr) {
if (!arr->IsArray())
return false;
return !arr->IsTypedArray();
}
void SetPrivate(v8::Local<v8::Context> context,
v8::Local<v8::Object> target,
const std::string& key,
v8::Local<v8::Value> value) {
target
->SetPrivate(
context,
v8::Private::ForApi(context->GetIsolate(),
gin::StringToV8(context->GetIsolate(), key)),
value)
.Check();
}
v8::MaybeLocal<v8::Value> GetPrivate(v8::Local<v8::Context> context,
v8::Local<v8::Object> target,
const std::string& key) {
return target->GetPrivate(
context,
v8::Private::ForApi(context->GetIsolate(),
gin::StringToV8(context->GetIsolate(), key)));
}
} // namespace
v8::MaybeLocal<v8::Value> PassValueToOtherContext(
v8::Local<v8::Context> source_context,
v8::Local<v8::Context> destination_context,
v8::Local<v8::Value> value,
context_bridge::ObjectCache* object_cache,
bool support_dynamic_properties,
int recursion_depth,
BridgeErrorTarget error_target) {
TRACE_EVENT0("electron", "ContextBridge::PassValueToOtherContext");
if (recursion_depth >= kMaxRecursion) {
v8::Context::Scope error_scope(error_target == BridgeErrorTarget::kSource
? source_context
: destination_context);
source_context->GetIsolate()->ThrowException(v8::Exception::TypeError(
gin::StringToV8(source_context->GetIsolate(),
"Electron contextBridge recursion depth exceeded. "
"Nested objects "
"deeper than 1000 are not supported.")));
return v8::MaybeLocal<v8::Value>();
}
// Certain primitives always use the current contexts prototype and we can
// pass these through directly which is significantly more performant than
// copying them. This list of primitives is based on the classification of
// "primitive value" as defined in the ECMA262 spec
// https://tc39.es/ecma262/#sec-primitive-value
if (value->IsString() || value->IsNumber() || value->IsNullOrUndefined() ||
value->IsBoolean() || value->IsSymbol() || value->IsBigInt()) {
return v8::MaybeLocal<v8::Value>(value);
}
// Check Cache
auto cached_value = object_cache->GetCachedProxiedObject(value);
if (!cached_value.IsEmpty()) {
return cached_value;
}
// Proxy functions and monitor the lifetime in the new context to release
// the global handle at the right time.
if (value->IsFunction()) {
auto func = value.As<v8::Function>();
v8::MaybeLocal<v8::Value> maybe_original_fn = GetPrivate(
source_context, func, context_bridge::kOriginalFunctionPrivateKey);
{
v8::Context::Scope destination_scope(destination_context);
v8::Local<v8::Value> proxy_func;
// If this function has already been sent over the bridge,
// then it is being sent _back_ over the bridge and we can
// simply return the original method here for performance reasons
// For safety reasons we check if the destination context is the
// creation context of the original method. If it's not we proceed
// with the proxy logic
if (maybe_original_fn.ToLocal(&proxy_func) && proxy_func->IsFunction() &&
proxy_func.As<v8::Object>()->GetCreationContextChecked() ==
destination_context) {
return v8::MaybeLocal<v8::Value>(proxy_func);
}
v8::Local<v8::Object> state =
v8::Object::New(destination_context->GetIsolate());
SetPrivate(destination_context, state,
context_bridge::kProxyFunctionPrivateKey, func);
SetPrivate(destination_context, state,
context_bridge::kSupportsDynamicPropertiesPrivateKey,
gin::ConvertToV8(destination_context->GetIsolate(),
support_dynamic_properties));
if (!v8::Function::New(destination_context, ProxyFunctionWrapper, state)
.ToLocal(&proxy_func))
return v8::MaybeLocal<v8::Value>();
SetPrivate(destination_context, proxy_func.As<v8::Object>(),
context_bridge::kOriginalFunctionPrivateKey, func);
object_cache->CacheProxiedObject(value, proxy_func);
return v8::MaybeLocal<v8::Value>(proxy_func);
}
}
// Proxy promises as they have a safe and guaranteed memory lifecycle
if (value->IsPromise()) {
v8::Context::Scope destination_scope(destination_context);
auto source_promise = value.As<v8::Promise>();
// Make the promise a shared_ptr so that when the original promise is
// freed the proxy promise is correctly freed as well instead of being
// left dangling
auto proxied_promise =
std::make_shared<gin_helper::Promise<v8::Local<v8::Value>>>(
destination_context->GetIsolate());
v8::Local<v8::Promise> proxied_promise_handle =
proxied_promise->GetHandle();
v8::Global<v8::Context> global_then_source_context(
source_context->GetIsolate(), source_context);
v8::Global<v8::Context> global_then_destination_context(
destination_context->GetIsolate(), destination_context);
global_then_source_context.SetWeak();
global_then_destination_context.SetWeak();
auto then_cb = base::BindOnce(
[](std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>>
proxied_promise,
v8::Isolate* isolate, v8::Global<v8::Context> global_source_context,
v8::Global<v8::Context> global_destination_context,
v8::Local<v8::Value> result) {
if (global_source_context.IsEmpty() ||
global_destination_context.IsEmpty())
return;
context_bridge::ObjectCache object_cache;
v8::MaybeLocal<v8::Value> val;
{
v8::TryCatch try_catch(isolate);
val = PassValueToOtherContext(
global_source_context.Get(isolate),
global_destination_context.Get(isolate), result, &object_cache,
false, 0, BridgeErrorTarget::kDestination);
if (try_catch.HasCaught()) {
if (try_catch.Message().IsEmpty()) {
proxied_promise->RejectWithErrorMessage(
"An error was thrown while sending a promise result over "
"the context bridge but it was not actually an Error "
"object. This normally means that a promise was resolved "
"with a value that is not supported by the Context "
"Bridge.");
} else {
proxied_promise->Reject(
v8::Exception::Error(try_catch.Message()->Get()));
}
return;
}
}
DCHECK(!val.IsEmpty());
if (!val.IsEmpty())
proxied_promise->Resolve(val.ToLocalChecked());
},
proxied_promise, destination_context->GetIsolate(),
std::move(global_then_source_context),
std::move(global_then_destination_context));
v8::Global<v8::Context> global_catch_source_context(
source_context->GetIsolate(), source_context);
v8::Global<v8::Context> global_catch_destination_context(
destination_context->GetIsolate(), destination_context);
global_catch_source_context.SetWeak();
global_catch_destination_context.SetWeak();
auto catch_cb = base::BindOnce(
[](std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>>
proxied_promise,
v8::Isolate* isolate, v8::Global<v8::Context> global_source_context,
v8::Global<v8::Context> global_destination_context,
v8::Local<v8::Value> result) {
if (global_source_context.IsEmpty() ||
global_destination_context.IsEmpty())
return;
context_bridge::ObjectCache object_cache;
v8::MaybeLocal<v8::Value> val;
{
v8::TryCatch try_catch(isolate);
val = PassValueToOtherContext(
global_source_context.Get(isolate),
global_destination_context.Get(isolate), result, &object_cache,
false, 0, BridgeErrorTarget::kDestination);
if (try_catch.HasCaught()) {
if (try_catch.Message().IsEmpty()) {
proxied_promise->RejectWithErrorMessage(
"An error was thrown while sending a promise rejection "
"over the context bridge but it was not actually an Error "
"object. This normally means that a promise was rejected "
"with a value that is not supported by the Context "
"Bridge.");
} else {
proxied_promise->Reject(
v8::Exception::Error(try_catch.Message()->Get()));
}
return;
}
}
if (!val.IsEmpty())
proxied_promise->Reject(val.ToLocalChecked());
},
proxied_promise, destination_context->GetIsolate(),
std::move(global_catch_source_context),
std::move(global_catch_destination_context));
std::ignore = source_promise->Then(
source_context,
gin::ConvertToV8(destination_context->GetIsolate(), std::move(then_cb))
.As<v8::Function>(),
gin::ConvertToV8(destination_context->GetIsolate(), std::move(catch_cb))
.As<v8::Function>());
object_cache->CacheProxiedObject(value, proxied_promise_handle);
return v8::MaybeLocal<v8::Value>(proxied_promise_handle);
}
// Errors aren't serializable currently, we need to pull the message out and
// re-construct in the destination context
if (value->IsNativeError()) {
v8::Context::Scope destination_context_scope(destination_context);
// We should try to pull "message" straight off of the error as a
// v8::Message includes some pretext that can get duplicated each time it
// crosses the bridge we fallback to the v8::Message approach if we can't
// pull "message" for some reason
v8::MaybeLocal<v8::Value> maybe_message = value.As<v8::Object>()->Get(
source_context,
gin::ConvertToV8(source_context->GetIsolate(), "message"));
v8::Local<v8::Value> message;
if (maybe_message.ToLocal(&message) && message->IsString()) {
return v8::MaybeLocal<v8::Value>(
v8::Exception::Error(message.As<v8::String>()));
}
return v8::MaybeLocal<v8::Value>(v8::Exception::Error(
v8::Exception::CreateMessage(destination_context->GetIsolate(), value)
->Get()));
}
// Manually go through the array and pass each value individually into a new
// array so that functions deep inside arrays get proxied or arrays of
// promises are proxied correctly.
if (IsPlainArray(value)) {
v8::Context::Scope destination_context_scope(destination_context);
v8::Local<v8::Array> arr = value.As<v8::Array>();
size_t length = arr->Length();
v8::Local<v8::Array> cloned_arr =
v8::Array::New(destination_context->GetIsolate(), length);
for (size_t i = 0; i < length; i++) {
auto value_for_array = PassValueToOtherContext(
source_context, destination_context,
arr->Get(source_context, i).ToLocalChecked(), object_cache,
support_dynamic_properties, recursion_depth + 1, error_target);
if (value_for_array.IsEmpty())
return v8::MaybeLocal<v8::Value>();
if (!IsTrue(cloned_arr->Set(destination_context, static_cast<int>(i),
value_for_array.ToLocalChecked()))) {
return v8::MaybeLocal<v8::Value>();
}
}
object_cache->CacheProxiedObject(value, cloned_arr);
return v8::MaybeLocal<v8::Value>(cloned_arr);
}
// Custom logic to "clone" Element references
blink::WebElement elem =
blink::WebElement::FromV8Value(destination_context->GetIsolate(), value);
if (!elem.IsNull()) {
v8::Context::Scope destination_context_scope(destination_context);
return v8::MaybeLocal<v8::Value>(elem.ToV8Value(
destination_context->Global(), destination_context->GetIsolate()));
}
// Custom logic to "clone" Blob references
blink::WebBlob blob =
blink::WebBlob::FromV8Value(destination_context->GetIsolate(), value);
if (!blob.IsNull()) {
v8::Context::Scope destination_context_scope(destination_context);
return v8::MaybeLocal<v8::Value>(
blob.ToV8Value(destination_context->GetIsolate()));
}
// Proxy all objects
if (IsPlainObject(value)) {
auto object_value = value.As<v8::Object>();
auto passed_value = CreateProxyForAPI(
object_value, source_context, destination_context, object_cache,
support_dynamic_properties, recursion_depth + 1, error_target);
if (passed_value.IsEmpty())
return v8::MaybeLocal<v8::Value>();
return v8::MaybeLocal<v8::Value>(passed_value.ToLocalChecked());
}
// Serializable objects
blink::CloneableMessage ret;
{
v8::Local<v8::Context> error_context =
error_target == BridgeErrorTarget::kSource ? source_context
: destination_context;
v8::Context::Scope error_scope(error_context);
// V8 serializer will throw an error if required
if (!gin::ConvertFromV8(error_context->GetIsolate(), value, &ret)) {
return v8::MaybeLocal<v8::Value>();
}
}
{
v8::Context::Scope destination_context_scope(destination_context);
v8::Local<v8::Value> cloned_value =
gin::ConvertToV8(destination_context->GetIsolate(), ret);
object_cache->CacheProxiedObject(value, cloned_value);
return v8::MaybeLocal<v8::Value>(cloned_value);
}
}
void ProxyFunctionWrapper(const v8::FunctionCallbackInfo<v8::Value>& info) {
TRACE_EVENT0("electron", "ContextBridge::ProxyFunctionWrapper");
CHECK(info.Data()->IsObject());
v8::Local<v8::Object> data = info.Data().As<v8::Object>();
bool support_dynamic_properties = false;
gin::Arguments args(info);
// Context the proxy function was called from
v8::Local<v8::Context> calling_context = args.isolate()->GetCurrentContext();
// Pull the original function and its context off of the data private key
v8::MaybeLocal<v8::Value> sdp_value =
GetPrivate(calling_context, data,
context_bridge::kSupportsDynamicPropertiesPrivateKey);
v8::MaybeLocal<v8::Value> maybe_func = GetPrivate(
calling_context, data, context_bridge::kProxyFunctionPrivateKey);
v8::Local<v8::Value> func_value;
if (sdp_value.IsEmpty() || maybe_func.IsEmpty() ||
!gin::ConvertFromV8(args.isolate(), sdp_value.ToLocalChecked(),
&support_dynamic_properties) ||
!maybe_func.ToLocal(&func_value))
return;
v8::Local<v8::Function> func = func_value.As<v8::Function>();
v8::Local<v8::Context> func_owning_context =
func->GetCreationContextChecked();
{
v8::Context::Scope func_owning_context_scope(func_owning_context);
context_bridge::ObjectCache object_cache;
std::vector<v8::Local<v8::Value>> original_args;
std::vector<v8::Local<v8::Value>> proxied_args;
args.GetRemaining(&original_args);
for (auto value : original_args) {
auto arg = PassValueToOtherContext(
calling_context, func_owning_context, value, &object_cache,
support_dynamic_properties, 0, BridgeErrorTarget::kSource);
if (arg.IsEmpty())
return;
proxied_args.push_back(arg.ToLocalChecked());
}
v8::MaybeLocal<v8::Value> maybe_return_value;
bool did_error = false;
v8::Local<v8::Value> error_message;
{
v8::TryCatch try_catch(args.isolate());
maybe_return_value = func->Call(func_owning_context, func,
proxied_args.size(), proxied_args.data());
if (try_catch.HasCaught()) {
did_error = true;
v8::Local<v8::Value> exception = try_catch.Exception();
const char err_msg[] =
"An unknown exception occurred in the isolated context, an error "
"occurred but a valid exception was not thrown.";
if (!exception->IsNull() && exception->IsObject()) {
v8::MaybeLocal<v8::Value> maybe_message =
exception.As<v8::Object>()->Get(
func_owning_context,
gin::ConvertToV8(args.isolate(), "message"));
if (!maybe_message.ToLocal(&error_message) ||
!error_message->IsString()) {
error_message = gin::StringToV8(args.isolate(), err_msg);
}
} else {
error_message = gin::StringToV8(args.isolate(), err_msg);
}
}
}
if (did_error) {
v8::Context::Scope calling_context_scope(calling_context);
args.isolate()->ThrowException(
v8::Exception::Error(error_message.As<v8::String>()));
return;
}
if (maybe_return_value.IsEmpty())
return;
// In the case where we encounted an exception converting the return value
// of the function we need to ensure that the exception / thrown value is
// safely transferred from the function_owning_context (where it was thrown)
// into the calling_context (where it needs to be thrown) To do this we pull
// the message off the exception and later re-throw it in the right context.
// In some cases the caught thing is not an exception i.e. it's technically
// valid to `throw 123`. In these cases to avoid infinite
// PassValueToOtherContext recursion we bail early as being unable to send
// the value from one context to the other.
// TODO(MarshallOfSound): In this case and other cases where the error can't
// be sent _across_ worlds we should probably log it globally in some way to
// allow easier debugging. This is not trivial though so is left to a
// future change.
bool did_error_converting_result = false;
v8::MaybeLocal<v8::Value> ret;
v8::Local<v8::String> exception;
{
v8::TryCatch try_catch(args.isolate());
ret = PassValueToOtherContext(func_owning_context, calling_context,
maybe_return_value.ToLocalChecked(),
&object_cache, support_dynamic_properties,
0, BridgeErrorTarget::kDestination);
if (try_catch.HasCaught()) {
did_error_converting_result = true;
if (!try_catch.Message().IsEmpty()) {
exception = try_catch.Message()->Get();
}
}
}
if (did_error_converting_result) {
v8::Context::Scope calling_context_scope(calling_context);
if (exception.IsEmpty()) {
const char err_msg[] =
"An unknown exception occurred while sending a function return "
"value over the context bridge, an error "
"occurred but a valid exception was not thrown.";
args.isolate()->ThrowException(v8::Exception::Error(
gin::StringToV8(args.isolate(), err_msg).As<v8::String>()));
} else {
args.isolate()->ThrowException(v8::Exception::Error(exception));
}
return;
}
DCHECK(!ret.IsEmpty());
if (ret.IsEmpty())
return;
info.GetReturnValue().Set(ret.ToLocalChecked());
}
}
v8::MaybeLocal<v8::Object> CreateProxyForAPI(
const v8::Local<v8::Object>& api_object,
const v8::Local<v8::Context>& source_context,
const v8::Local<v8::Context>& destination_context,
context_bridge::ObjectCache* object_cache,
bool support_dynamic_properties,
int recursion_depth,
BridgeErrorTarget error_target) {
gin_helper::Dictionary api(source_context->GetIsolate(), api_object);
{
v8::Context::Scope destination_context_scope(destination_context);
auto proxy =
gin_helper::Dictionary::CreateEmpty(destination_context->GetIsolate());
object_cache->CacheProxiedObject(api.GetHandle(), proxy.GetHandle());
auto maybe_keys = api.GetHandle()->GetOwnPropertyNames(
source_context, static_cast<v8::PropertyFilter>(v8::ONLY_ENUMERABLE));
if (maybe_keys.IsEmpty())
return v8::MaybeLocal<v8::Object>(proxy.GetHandle());
auto keys = maybe_keys.ToLocalChecked();
uint32_t length = keys->Length();
for (uint32_t i = 0; i < length; i++) {
v8::Local<v8::Value> key =
keys->Get(destination_context, i).ToLocalChecked();
if (support_dynamic_properties) {
v8::Context::Scope source_context_scope(source_context);
auto maybe_desc = api.GetHandle()->GetOwnPropertyDescriptor(
source_context, key.As<v8::Name>());
v8::Local<v8::Value> desc_value;
if (!maybe_desc.ToLocal(&desc_value) || !desc_value->IsObject())
continue;
gin_helper::Dictionary desc(api.isolate(), desc_value.As<v8::Object>());
if (desc.Has("get") || desc.Has("set")) {
v8::Local<v8::Value> getter;
v8::Local<v8::Value> setter;
desc.Get("get", &getter);
desc.Get("set", &setter);
{
v8::Context::Scope inner_destination_context_scope(
destination_context);
v8::Local<v8::Value> getter_proxy;
v8::Local<v8::Value> setter_proxy;
if (!getter.IsEmpty()) {
if (!PassValueToOtherContext(source_context, destination_context,
getter, object_cache,
support_dynamic_properties, 1,
error_target)
.ToLocal(&getter_proxy))
continue;
}
if (!setter.IsEmpty()) {
if (!PassValueToOtherContext(source_context, destination_context,
setter, object_cache,
support_dynamic_properties, 1,
error_target)
.ToLocal(&setter_proxy))
continue;
}
v8::PropertyDescriptor prop_desc(getter_proxy, setter_proxy);
std::ignore = proxy.GetHandle()->DefineProperty(
destination_context, key.As<v8::Name>(), prop_desc);
}
continue;
}
}
v8::Local<v8::Value> value;
if (!api.Get(key, &value))
continue;
auto passed_value = PassValueToOtherContext(
source_context, destination_context, value, object_cache,
support_dynamic_properties, recursion_depth + 1, error_target);
if (passed_value.IsEmpty())
return v8::MaybeLocal<v8::Object>();
proxy.Set(key, passed_value.ToLocalChecked());
}
return proxy.GetHandle();
}
}
void ExposeAPIInWorld(v8::Isolate* isolate,
const int world_id,
const std::string& key,
v8::Local<v8::Value> api,
gin_helper::Arguments* args) {
TRACE_EVENT2("electron", "ContextBridge::ExposeAPIInWorld", "key", key,
"worldId", world_id);
auto* render_frame = GetRenderFrame(isolate->GetCurrentContext()->Global());
CHECK(render_frame);
auto* frame = render_frame->GetWebFrame();
CHECK(frame);
v8::Local<v8::Context> target_context =
world_id == WorldIDs::MAIN_WORLD_ID
? frame->MainWorldScriptContext()
: frame->GetScriptContextFromWorldId(isolate, world_id);
gin_helper::Dictionary global(target_context->GetIsolate(),
target_context->Global());
if (global.Has(key)) {
args->ThrowError(
"Cannot bind an API on top of an existing property on the window "
"object");
return;
}
v8::Local<v8::Context> electron_isolated_context =
frame->GetScriptContextFromWorldId(args->isolate(),
WorldIDs::ISOLATED_WORLD_ID);
{
context_bridge::ObjectCache object_cache;
v8::Context::Scope target_context_scope(target_context);
v8::MaybeLocal<v8::Value> maybe_proxy = PassValueToOtherContext(
electron_isolated_context, target_context, api, &object_cache, false, 0,
BridgeErrorTarget::kSource);
if (maybe_proxy.IsEmpty())
return;
auto proxy = maybe_proxy.ToLocalChecked();
if (base::FeatureList::IsEnabled(features::kContextBridgeMutability)) {
global.Set(key, proxy);
return;
}
if (proxy->IsObject() && !proxy->IsTypedArray() &&
!DeepFreeze(proxy.As<v8::Object>(), target_context))
return;
global.SetReadOnlyNonConfigurable(key, proxy);
}
}
gin_helper::Dictionary TraceKeyPath(const gin_helper::Dictionary& start,
const std::vector<std::string>& key_path) {
gin_helper::Dictionary current = start;
for (size_t i = 0; i < key_path.size() - 1; i++) {
CHECK(current.Get(key_path[i], ¤t));
}
return current;
}
void OverrideGlobalValueFromIsolatedWorld(
const std::vector<std::string>& key_path,
v8::Local<v8::Object> value,
bool support_dynamic_properties) {
if (key_path.empty())
return;
auto* render_frame = GetRenderFrame(value);
CHECK(render_frame);
auto* frame = render_frame->GetWebFrame();
CHECK(frame);
v8::Local<v8::Context> main_context = frame->MainWorldScriptContext();
gin_helper::Dictionary global(main_context->GetIsolate(),
main_context->Global());
const std::string final_key = key_path[key_path.size() - 1];
gin_helper::Dictionary target_object = TraceKeyPath(global, key_path);
{
v8::Context::Scope main_context_scope(main_context);
context_bridge::ObjectCache object_cache;
v8::MaybeLocal<v8::Value> maybe_proxy = PassValueToOtherContext(
value->GetCreationContextChecked(), main_context, value, &object_cache,
support_dynamic_properties, 1, BridgeErrorTarget::kSource);
DCHECK(!maybe_proxy.IsEmpty());
auto proxy = maybe_proxy.ToLocalChecked();
target_object.Set(final_key, proxy);
}
}
bool OverrideGlobalPropertyFromIsolatedWorld(
const std::vector<std::string>& key_path,
v8::Local<v8::Object> getter,
v8::Local<v8::Value> setter,
gin_helper::Arguments* args) {
if (key_path.empty())
return false;
auto* render_frame = GetRenderFrame(getter);
CHECK(render_frame);
auto* frame = render_frame->GetWebFrame();
CHECK(frame);
v8::Local<v8::Context> main_context = frame->MainWorldScriptContext();
gin_helper::Dictionary global(main_context->GetIsolate(),
main_context->Global());
const std::string final_key = key_path[key_path.size() - 1];
v8::Local<v8::Object> target_object =
TraceKeyPath(global, key_path).GetHandle();
{
v8::Context::Scope main_context_scope(main_context);
context_bridge::ObjectCache object_cache;
v8::Local<v8::Value> getter_proxy;
v8::Local<v8::Value> setter_proxy;
if (!getter->IsNullOrUndefined()) {
v8::MaybeLocal<v8::Value> maybe_getter_proxy = PassValueToOtherContext(
getter->GetCreationContextChecked(), main_context, getter,
&object_cache, false, 1, BridgeErrorTarget::kSource);
DCHECK(!maybe_getter_proxy.IsEmpty());
getter_proxy = maybe_getter_proxy.ToLocalChecked();
}
if (!setter->IsNullOrUndefined() && setter->IsObject()) {
v8::MaybeLocal<v8::Value> maybe_setter_proxy = PassValueToOtherContext(
getter->GetCreationContextChecked(), main_context, setter,
&object_cache, false, 1, BridgeErrorTarget::kSource);
DCHECK(!maybe_setter_proxy.IsEmpty());
setter_proxy = maybe_setter_proxy.ToLocalChecked();
}
v8::PropertyDescriptor desc(getter_proxy, setter_proxy);
bool success = IsTrue(target_object->DefineProperty(
main_context, gin::StringToV8(args->isolate(), final_key), desc));
DCHECK(success);
return success;
}
}
bool IsCalledFromMainWorld(v8::Isolate* isolate) {
auto* render_frame = GetRenderFrame(isolate->GetCurrentContext()->Global());
CHECK(render_frame);
auto* frame = render_frame->GetWebFrame();
CHECK(frame);
v8::Local<v8::Context> main_context = frame->MainWorldScriptContext();
return isolate->GetCurrentContext() == main_context;
}
} // namespace api
} // namespace electron
namespace {
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.SetMethod("exposeAPIInWorld", &electron::api::ExposeAPIInWorld);
dict.SetMethod("_overrideGlobalValueFromIsolatedWorld",
&electron::api::OverrideGlobalValueFromIsolatedWorld);
dict.SetMethod("_overrideGlobalPropertyFromIsolatedWorld",
&electron::api::OverrideGlobalPropertyFromIsolatedWorld);
dict.SetMethod("_isCalledFromMainWorld",
&electron::api::IsCalledFromMainWorld);
#if DCHECK_IS_ON()
dict.Set("_isDebug", true);
#endif
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_renderer_context_bridge, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 39,891 |
[Bug]: NativeImage methods returned by capturePage fail with "Error: Illegal invocation"
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Ubuntu
### Operating System Version
Ubuntu 23.04
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
While calling `<webview-tag>.capturePage()` from renderer process, we should be able to run methods from the returned NativeImage (like `.getSize()`)
### Actual Behavior
While calling `<webview-tag>.capturePage()` from a renderer process, all of the NativeImage methods return the following error. In this example we call `.getSize()`:
```
Uncaught (in promise) Error: Illegal invocation: Function must be called on an object of type NativeImage
```
**Code snippet**
```js
const webviewElement = document.getElementById("webview")
webviewElement.capturePage()
.then((image) => console.log(image.getSize()))
```
**To reproduce**
**1.** Create a webview element in a page (BrowserView) and make set the id-attribute to `webview`
**2.** Execute the snippet above
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39891
|
https://github.com/electron/electron/pull/39978
|
5b105f911f7aa134ee44558fefaf171360d3d9d2
|
fd2861117e04a3c62bfab67a1b50cb9c3a55cd4d
| 2023-09-18T10:48:18Z |
c++
| 2023-10-18T14:21:42Z |
shell/renderer/api/electron_api_context_bridge.h
|
// Copyright (c) 2019 Slack Technologies, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_RENDERER_API_ELECTRON_API_CONTEXT_BRIDGE_H_
#define ELECTRON_SHELL_RENDERER_API_ELECTRON_API_CONTEXT_BRIDGE_H_
#include "shell/renderer/api/context_bridge/object_cache.h"
#include "v8/include/v8.h"
namespace gin_helper {
class Arguments;
}
namespace electron::api {
void ProxyFunctionWrapper(const v8::FunctionCallbackInfo<v8::Value>& info);
// Where the context bridge should create the exception it is about to throw
enum class BridgeErrorTarget {
// The source / calling context. This is default and correct 99% of the time,
// the caller / context asking for the conversion will receive the error and
// therefore the error should be made in that context
kSource,
// The destination / target context. This should only be used when the source
// won't catch the error that results from the value it is passing over the
// bridge. This can **only** occur when returning a value from a function as
// we convert the return value after the method has terminated and execution
// has been returned to the caller. In this scenario the error will the be
// catchable in the "destination" context and therefore we create the error
// there.
kDestination
};
v8::MaybeLocal<v8::Value> PassValueToOtherContext(
v8::Local<v8::Context> source_context,
v8::Local<v8::Context> destination_context,
v8::Local<v8::Value> value,
context_bridge::ObjectCache* object_cache,
bool support_dynamic_properties,
int recursion_depth,
BridgeErrorTarget error_target);
v8::MaybeLocal<v8::Object> CreateProxyForAPI(
const v8::Local<v8::Object>& api_object,
const v8::Local<v8::Context>& source_context,
const v8::Local<v8::Context>& destination_context,
context_bridge::ObjectCache* object_cache,
bool support_dynamic_properties,
int recursion_depth,
BridgeErrorTarget error_target);
} // namespace electron::api
#endif // ELECTRON_SHELL_RENDERER_API_ELECTRON_API_CONTEXT_BRIDGE_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 39,891 |
[Bug]: NativeImage methods returned by capturePage fail with "Error: Illegal invocation"
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Ubuntu
### Operating System Version
Ubuntu 23.04
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
While calling `<webview-tag>.capturePage()` from renderer process, we should be able to run methods from the returned NativeImage (like `.getSize()`)
### Actual Behavior
While calling `<webview-tag>.capturePage()` from a renderer process, all of the NativeImage methods return the following error. In this example we call `.getSize()`:
```
Uncaught (in promise) Error: Illegal invocation: Function must be called on an object of type NativeImage
```
**Code snippet**
```js
const webviewElement = document.getElementById("webview")
webviewElement.capturePage()
.then((image) => console.log(image.getSize()))
```
**To reproduce**
**1.** Create a webview element in a page (BrowserView) and make set the id-attribute to `webview`
**2.** Execute the snippet above
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39891
|
https://github.com/electron/electron/pull/39978
|
5b105f911f7aa134ee44558fefaf171360d3d9d2
|
fd2861117e04a3c62bfab67a1b50cb9c3a55cd4d
| 2023-09-18T10:48:18Z |
c++
| 2023-10-18T14:21:42Z |
shell/renderer/api/electron_api_web_frame.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/command_line.h"
#include "base/memory/memory_pressure_listener.h"
#include "base/strings/utf_string_conversions.h"
#include "components/spellcheck/renderer/spellcheck.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_frame_observer.h"
#include "content/public/renderer/render_frame_visitor.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/common/api/api.mojom.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/function_template_extensions.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/renderer/api/context_bridge/object_cache.h"
#include "shell/renderer/api/electron_api_context_bridge.h"
#include "shell/renderer/api/electron_api_spell_check_client.h"
#include "shell/renderer/renderer_client_base.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/common/web_cache/web_cache_resource_type_stats.h"
#include "third_party/blink/public/common/web_preferences/web_preferences.h"
#include "third_party/blink/public/platform/web_cache.h"
#include "third_party/blink/public/platform/web_isolated_world_info.h"
#include "third_party/blink/public/web/web_custom_element.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_element.h"
#include "third_party/blink/public/web/web_frame_widget.h"
#include "third_party/blink/public/web/web_input_method_controller.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_script_execution_callback.h"
#include "third_party/blink/public/web/web_script_source.h"
#include "third_party/blink/public/web/web_view.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h" // nogncheck
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h" // nogncheck
#include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h" // nogncheck
#include "ui/base/ime/ime_text_span.h"
#include "url/url_util.h"
namespace gin {
template <>
struct Converter<blink::WebCssOrigin> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
blink::WebCssOrigin* out) {
std::string css_origin;
if (!ConvertFromV8(isolate, val, &css_origin))
return false;
if (css_origin == "user") {
*out = blink::WebCssOrigin::kUser;
} else if (css_origin == "author") {
*out = blink::WebCssOrigin::kAuthor;
} else {
return false;
}
return true;
}
};
} // namespace gin
namespace electron {
content::RenderFrame* GetRenderFrame(v8::Local<v8::Object> value) {
v8::Local<v8::Context> context = value->GetCreationContextChecked();
if (context.IsEmpty())
return nullptr;
blink::WebLocalFrame* frame = blink::WebLocalFrame::FrameForContext(context);
if (!frame)
return nullptr;
return content::RenderFrame::FromWebFrame(frame);
}
namespace api {
namespace {
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
bool SpellCheckWord(content::RenderFrame* render_frame,
const std::string& word,
std::vector<std::u16string>* optional_suggestions) {
size_t start;
size_t length;
RendererClientBase* client = RendererClientBase::Get();
std::u16string w = base::UTF8ToUTF16(word);
int id = render_frame->GetRoutingID();
return client->GetSpellCheck()->SpellCheckWord(
w.c_str(), 0, word.size(), id, &start, &length, optional_suggestions);
}
#endif
class ScriptExecutionCallback {
public:
// for compatibility with the older version of this, error is after result
using CompletionCallback =
base::OnceCallback<void(const v8::Local<v8::Value>& result,
const v8::Local<v8::Value>& error)>;
explicit ScriptExecutionCallback(
gin_helper::Promise<v8::Local<v8::Value>> promise,
CompletionCallback callback)
: promise_(std::move(promise)), callback_(std::move(callback)) {}
~ScriptExecutionCallback() = default;
// disable copy
ScriptExecutionCallback(const ScriptExecutionCallback&) = delete;
ScriptExecutionCallback& operator=(const ScriptExecutionCallback&) = delete;
void CopyResultToCallingContextAndFinalize(
v8::Isolate* isolate,
const v8::Local<v8::Object>& result) {
v8::MaybeLocal<v8::Value> maybe_result;
bool success = true;
std::string error_message =
"An unknown exception occurred while getting the result of the script";
{
v8::TryCatch try_catch(isolate);
context_bridge::ObjectCache object_cache;
maybe_result = PassValueToOtherContext(
result->GetCreationContextChecked(), promise_.GetContext(), result,
&object_cache, false, 0, BridgeErrorTarget::kSource);
if (maybe_result.IsEmpty() || try_catch.HasCaught()) {
success = false;
}
if (try_catch.HasCaught()) {
auto message = try_catch.Message();
if (!message.IsEmpty()) {
gin::ConvertFromV8(isolate, message->Get(), &error_message);
}
}
}
if (!success) {
// Failed convert so we send undefined everywhere
if (callback_)
std::move(callback_).Run(
v8::Undefined(isolate),
v8::Exception::Error(
v8::String::NewFromUtf8(isolate, error_message.c_str())
.ToLocalChecked()));
promise_.RejectWithErrorMessage(error_message);
} else {
v8::Local<v8::Context> context = promise_.GetContext();
v8::Context::Scope context_scope(context);
v8::Local<v8::Value> cloned_value = maybe_result.ToLocalChecked();
if (callback_)
std::move(callback_).Run(cloned_value, v8::Undefined(isolate));
promise_.Resolve(cloned_value);
}
}
void Completed(const blink::WebVector<v8::Local<v8::Value>>& result) {
v8::Isolate* isolate = promise_.isolate();
if (!result.empty()) {
if (!result[0].IsEmpty()) {
v8::Local<v8::Value> value = result[0];
// Either the result was created in the same world as the caller
// or the result is not an object and therefore does not have a
// prototype chain to protect
bool should_clone_value =
!(value->IsObject() &&
promise_.GetContext() ==
value.As<v8::Object>()->GetCreationContextChecked()) &&
value->IsObject();
if (should_clone_value) {
CopyResultToCallingContextAndFinalize(isolate,
value.As<v8::Object>());
} else {
// Right now only single results per frame is supported.
if (callback_)
std::move(callback_).Run(value, v8::Undefined(isolate));
promise_.Resolve(value);
}
} else {
const char error_message[] =
"Script failed to execute, this normally means an error "
"was thrown. Check the renderer console for the error.";
if (!callback_.is_null()) {
v8::Local<v8::Context> context = promise_.GetContext();
v8::Context::Scope context_scope(context);
std::move(callback_).Run(
v8::Undefined(isolate),
v8::Exception::Error(
v8::String::NewFromUtf8(isolate, error_message)
.ToLocalChecked()));
}
promise_.RejectWithErrorMessage(error_message);
}
} else {
const char error_message[] =
"WebFrame was removed before script could run. This normally means "
"the underlying frame was destroyed";
if (!callback_.is_null()) {
v8::Local<v8::Context> context = promise_.GetContext();
v8::Context::Scope context_scope(context);
std::move(callback_).Run(
v8::Undefined(isolate),
v8::Exception::Error(v8::String::NewFromUtf8(isolate, error_message)
.ToLocalChecked()));
}
promise_.RejectWithErrorMessage(error_message);
}
delete this;
}
private:
gin_helper::Promise<v8::Local<v8::Value>> promise_;
CompletionCallback callback_;
};
class FrameSetSpellChecker : public content::RenderFrameVisitor {
public:
FrameSetSpellChecker(SpellCheckClient* spell_check_client,
content::RenderFrame* main_frame)
: spell_check_client_(spell_check_client), main_frame_(main_frame) {
content::RenderFrame::ForEach(this);
main_frame->GetWebFrame()->SetSpellCheckPanelHostClient(spell_check_client);
}
// disable copy
FrameSetSpellChecker(const FrameSetSpellChecker&) = delete;
FrameSetSpellChecker& operator=(const FrameSetSpellChecker&) = delete;
bool Visit(content::RenderFrame* render_frame) override {
if (render_frame->GetMainRenderFrame() == main_frame_ ||
(render_frame->IsMainFrame() && render_frame == main_frame_)) {
render_frame->GetWebFrame()->SetTextCheckClient(spell_check_client_);
}
return true;
}
private:
SpellCheckClient* spell_check_client_;
content::RenderFrame* main_frame_;
};
class SpellCheckerHolder final : public content::RenderFrameObserver {
public:
// Find existing holder for the |render_frame|.
static SpellCheckerHolder* FromRenderFrame(
content::RenderFrame* render_frame) {
for (auto* holder : instances_) {
if (holder->render_frame() == render_frame)
return holder;
}
return nullptr;
}
SpellCheckerHolder(content::RenderFrame* render_frame,
std::unique_ptr<SpellCheckClient> spell_check_client)
: content::RenderFrameObserver(render_frame),
spell_check_client_(std::move(spell_check_client)) {
DCHECK(!FromRenderFrame(render_frame));
instances_.insert(this);
}
~SpellCheckerHolder() final { instances_.erase(this); }
void UnsetAndDestroy() {
FrameSetSpellChecker set_spell_checker(nullptr, render_frame());
delete this;
}
// RenderFrameObserver implementation.
void OnDestruct() final {
// Since we delete this in WillReleaseScriptContext, this method is unlikely
// to be called, but override anyway since I'm not sure if there are some
// corner cases.
//
// Note that while there are two "delete this", it is totally fine as the
// observer unsubscribes automatically in destructor and the other one won't
// be called.
//
// Also note that we should not call UnsetAndDestroy here, as the render
// frame is going to be destroyed.
delete this;
}
void WillReleaseScriptContext(v8::Local<v8::Context> context,
int world_id) final {
// Unset spell checker when the script context is going to be released, as
// the spell check implementation lives there.
UnsetAndDestroy();
}
private:
static std::set<SpellCheckerHolder*> instances_;
std::unique_ptr<SpellCheckClient> spell_check_client_;
};
} // namespace
class WebFrameRenderer : public gin::Wrappable<WebFrameRenderer>,
public content::RenderFrameObserver {
public:
static gin::WrapperInfo kWrapperInfo;
static gin::Handle<WebFrameRenderer> Create(
v8::Isolate* isolate,
content::RenderFrame* render_frame) {
return gin::CreateHandle(isolate, new WebFrameRenderer(render_frame));
}
explicit WebFrameRenderer(content::RenderFrame* render_frame)
: content::RenderFrameObserver(render_frame) {
DCHECK(render_frame);
}
// gin::Wrappable:
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override {
return gin::Wrappable<WebFrameRenderer>::GetObjectTemplateBuilder(isolate)
.SetMethod("getWebFrameId", &WebFrameRenderer::GetWebFrameId)
.SetMethod("setName", &WebFrameRenderer::SetName)
.SetMethod("setZoomLevel", &WebFrameRenderer::SetZoomLevel)
.SetMethod("getZoomLevel", &WebFrameRenderer::GetZoomLevel)
.SetMethod("setZoomFactor", &WebFrameRenderer::SetZoomFactor)
.SetMethod("getZoomFactor", &WebFrameRenderer::GetZoomFactor)
.SetMethod("getWebPreference", &WebFrameRenderer::GetWebPreference)
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
.SetMethod("isWordMisspelled", &WebFrameRenderer::IsWordMisspelled)
.SetMethod("getWordSuggestions", &WebFrameRenderer::GetWordSuggestions)
#endif
.SetMethod("setVisualZoomLevelLimits",
&WebFrameRenderer::SetVisualZoomLevelLimits)
.SetMethod("allowGuestViewElementDefinition",
&RendererClientBase::AllowGuestViewElementDefinition)
.SetMethod("insertText", &WebFrameRenderer::InsertText)
.SetMethod("insertCSS", &WebFrameRenderer::InsertCSS)
.SetMethod("removeInsertedCSS", &WebFrameRenderer::RemoveInsertedCSS)
.SetMethod("_isEvalAllowed", &WebFrameRenderer::IsEvalAllowed)
.SetMethod("executeJavaScript", &WebFrameRenderer::ExecuteJavaScript)
.SetMethod("executeJavaScriptInIsolatedWorld",
&WebFrameRenderer::ExecuteJavaScriptInIsolatedWorld)
.SetMethod("setIsolatedWorldInfo",
&WebFrameRenderer::SetIsolatedWorldInfo)
.SetMethod("getResourceUsage", &WebFrameRenderer::GetResourceUsage)
.SetMethod("clearCache", &WebFrameRenderer::ClearCache)
.SetMethod("setSpellCheckProvider",
&WebFrameRenderer::SetSpellCheckProvider)
// Frame navigators
.SetMethod("findFrameByRoutingId",
&WebFrameRenderer::FindFrameByRoutingId)
.SetMethod("getFrameForSelector",
&WebFrameRenderer::GetFrameForSelector)
.SetMethod("findFrameByName", &WebFrameRenderer::FindFrameByName)
.SetProperty("opener", &WebFrameRenderer::GetOpener)
.SetProperty("parent", &WebFrameRenderer::GetFrameParent)
.SetProperty("top", &WebFrameRenderer::GetTop)
.SetProperty("firstChild", &WebFrameRenderer::GetFirstChild)
.SetProperty("nextSibling", &WebFrameRenderer::GetNextSibling)
.SetProperty("routingId", &WebFrameRenderer::GetRoutingId);
}
const char* GetTypeName() override { return "WebFrameRenderer"; }
void OnDestruct() override {}
private:
bool MaybeGetRenderFrame(v8::Isolate* isolate,
const base::StringPiece method_name,
content::RenderFrame** render_frame_ptr) {
std::string error_msg;
if (!MaybeGetRenderFrame(&error_msg, method_name, render_frame_ptr)) {
gin_helper::ErrorThrower(isolate).ThrowError(error_msg);
return false;
}
return true;
}
bool MaybeGetRenderFrame(std::string* error_msg,
const base::StringPiece method_name,
content::RenderFrame** render_frame_ptr) {
auto* frame = render_frame();
if (!frame) {
*error_msg = base::ToString("Render frame was torn down before webFrame.",
method_name, " could be executed");
return false;
}
*render_frame_ptr = frame;
return true;
}
static v8::Local<v8::Value> CreateWebFrameRenderer(v8::Isolate* isolate,
blink::WebFrame* frame) {
if (frame && frame->IsWebLocalFrame()) {
auto* render_frame =
content::RenderFrame::FromWebFrame(frame->ToWebLocalFrame());
return WebFrameRenderer::Create(isolate, render_frame).ToV8();
} else {
return v8::Null(isolate);
}
}
void SetName(v8::Isolate* isolate, const std::string& name) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "setName", &render_frame))
return;
render_frame->GetWebFrame()->SetName(blink::WebString::FromUTF8(name));
}
void SetZoomLevel(v8::Isolate* isolate, double level) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "setZoomLevel", &render_frame))
return;
mojo::AssociatedRemote<mojom::ElectronWebContentsUtility>
web_contents_utility_remote;
render_frame->GetRemoteAssociatedInterfaces()->GetInterface(
&web_contents_utility_remote);
web_contents_utility_remote->SetTemporaryZoomLevel(level);
}
double GetZoomLevel(v8::Isolate* isolate) {
double result = 0.0;
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "getZoomLevel", &render_frame))
return result;
mojo::AssociatedRemote<mojom::ElectronWebContentsUtility>
web_contents_utility_remote;
render_frame->GetRemoteAssociatedInterfaces()->GetInterface(
&web_contents_utility_remote);
web_contents_utility_remote->DoGetZoomLevel(&result);
return result;
}
void SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) {
if (factor < std::numeric_limits<double>::epsilon()) {
thrower.ThrowError("'zoomFactor' must be a double greater than 0.0");
return;
}
SetZoomLevel(thrower.isolate(), blink::PageZoomFactorToZoomLevel(factor));
}
double GetZoomFactor(v8::Isolate* isolate) {
double zoom_level = GetZoomLevel(isolate);
return blink::PageZoomLevelToZoomFactor(zoom_level);
}
v8::Local<v8::Value> GetWebPreference(v8::Isolate* isolate,
std::string pref_name) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "getWebPreference", &render_frame))
return v8::Undefined(isolate);
const auto& prefs = render_frame->GetBlinkPreferences();
if (pref_name == "isWebView") {
// FIXME(zcbenz): For child windows opened with window.open('') from
// webview, the WebPreferences is inherited from webview and the value
// of |is_webview| is wrong.
// Please check ElectronRenderFrameObserver::DidInstallConditionalFeatures
// for the background.
auto* web_frame = render_frame->GetWebFrame();
if (web_frame->Opener())
return gin::ConvertToV8(isolate, false);
return gin::ConvertToV8(isolate, prefs.is_webview);
} else if (pref_name == options::kHiddenPage) {
// NOTE: hiddenPage is internal-only.
return gin::ConvertToV8(isolate, prefs.hidden_page);
} else if (pref_name == options::kNodeIntegration) {
return gin::ConvertToV8(isolate, prefs.node_integration);
} else if (pref_name == options::kWebviewTag) {
return gin::ConvertToV8(isolate, prefs.webview_tag);
}
return v8::Null(isolate);
}
void SetVisualZoomLevelLimits(v8::Isolate* isolate,
double min_level,
double max_level) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "setVisualZoomLevelLimits",
&render_frame))
return;
blink::WebFrame* web_frame = render_frame->GetWebFrame();
web_frame->View()->SetDefaultPageScaleLimits(min_level, max_level);
}
static int GetWebFrameId(v8::Local<v8::Object> content_window) {
// Get the WebLocalFrame before (possibly) executing any user-space JS while
// getting the |params|. We track the status of the RenderFrame via an
// observer in case it is deleted during user code execution.
content::RenderFrame* render_frame = GetRenderFrame(content_window);
if (!render_frame)
return -1;
blink::WebLocalFrame* frame = render_frame->GetWebFrame();
// Parent must exist.
blink::WebFrame* parent_frame = frame->Parent();
DCHECK(parent_frame);
DCHECK(parent_frame->IsWebLocalFrame());
return render_frame->GetRoutingID();
}
void SetSpellCheckProvider(gin_helper::ErrorThrower thrower,
v8::Isolate* isolate,
const std::string& language,
v8::Local<v8::Object> provider) {
auto context = isolate->GetCurrentContext();
if (!provider->Has(context, gin::StringToV8(isolate, "spellCheck"))
.ToChecked()) {
thrower.ThrowError("\"spellCheck\" has to be defined");
return;
}
// Remove the old client.
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "setSpellCheckProvider", &render_frame))
return;
auto* existing = SpellCheckerHolder::FromRenderFrame(render_frame);
if (existing)
existing->UnsetAndDestroy();
// Set spellchecker for all live frames in the same process or
// in the sandbox mode for all live sub frames to this WebFrame.
auto spell_check_client =
std::make_unique<SpellCheckClient>(language, isolate, provider);
FrameSetSpellChecker spell_checker(spell_check_client.get(), render_frame);
// Attach the spell checker to RenderFrame.
new SpellCheckerHolder(render_frame, std::move(spell_check_client));
}
void InsertText(v8::Isolate* isolate, const std::string& text) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "insertText", &render_frame))
return;
blink::WebFrame* web_frame = render_frame->GetWebFrame();
if (web_frame->IsWebLocalFrame()) {
web_frame->ToWebLocalFrame()
->FrameWidget()
->GetActiveWebInputMethodController()
->CommitText(blink::WebString::FromUTF8(text),
blink::WebVector<ui::ImeTextSpan>(), blink::WebRange(),
0);
}
}
std::u16string InsertCSS(v8::Isolate* isolate,
const std::string& css,
gin::Arguments* args) {
blink::WebCssOrigin css_origin = blink::WebCssOrigin::kAuthor;
gin_helper::Dictionary options;
if (args->GetNext(&options))
options.Get("cssOrigin", &css_origin);
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "insertCSS", &render_frame))
return std::u16string();
blink::WebFrame* web_frame = render_frame->GetWebFrame();
if (web_frame->IsWebLocalFrame()) {
return web_frame->ToWebLocalFrame()
->GetDocument()
.InsertStyleSheet(blink::WebString::FromUTF8(css), nullptr,
css_origin)
.Utf16();
}
return std::u16string();
}
void RemoveInsertedCSS(v8::Isolate* isolate, const std::u16string& key) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "removeInsertedCSS", &render_frame))
return;
blink::WebFrame* web_frame = render_frame->GetWebFrame();
if (web_frame->IsWebLocalFrame()) {
web_frame->ToWebLocalFrame()->GetDocument().RemoveInsertedStyleSheet(
blink::WebString::FromUTF16(key));
}
}
bool IsEvalAllowed(v8::Isolate* isolate) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "isEvalAllowed", &render_frame))
return true;
auto* context = blink::ExecutionContext::From(
render_frame->GetWebFrame()->MainWorldScriptContext());
return !context->GetContentSecurityPolicy()->ShouldCheckEval();
}
v8::Local<v8::Promise> ExecuteJavaScript(gin::Arguments* gin_args,
const std::u16string& code) {
gin_helper::Arguments* args = static_cast<gin_helper::Arguments*>(gin_args);
v8::Isolate* isolate = args->isolate();
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
content::RenderFrame* render_frame;
std::string error_msg;
if (!MaybeGetRenderFrame(&error_msg, "executeJavaScript", &render_frame)) {
promise.RejectWithErrorMessage(error_msg);
return handle;
}
const blink::WebScriptSource source{blink::WebString::FromUTF16(code)};
bool has_user_gesture = false;
args->GetNext(&has_user_gesture);
ScriptExecutionCallback::CompletionCallback completion_callback;
args->GetNext(&completion_callback);
auto* self = new ScriptExecutionCallback(std::move(promise),
std::move(completion_callback));
render_frame->GetWebFrame()->RequestExecuteScript(
blink::DOMWrapperWorld::kMainWorldId, base::make_span(&source, 1u),
has_user_gesture ? blink::mojom::UserActivationOption::kActivate
: blink::mojom::UserActivationOption::kDoNotActivate,
blink::mojom::EvaluationTiming::kSynchronous,
blink::mojom::LoadEventBlockingOption::kDoNotBlock,
base::NullCallback(),
base::BindOnce(&ScriptExecutionCallback::Completed,
base::Unretained(self)),
blink::BackForwardCacheAware::kAllow,
blink::mojom::WantResultOption::kWantResult,
blink::mojom::PromiseResultOption::kDoNotWait);
return handle;
}
v8::Local<v8::Promise> ExecuteJavaScriptInIsolatedWorld(
gin::Arguments* gin_args,
int world_id,
const std::vector<gin_helper::Dictionary>& scripts) {
gin_helper::Arguments* args = static_cast<gin_helper::Arguments*>(gin_args);
v8::Isolate* isolate = args->isolate();
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
content::RenderFrame* render_frame;
std::string error_msg;
if (!MaybeGetRenderFrame(&error_msg, "executeJavaScriptInIsolatedWorld",
&render_frame)) {
promise.RejectWithErrorMessage(error_msg);
return handle;
}
bool has_user_gesture = false;
args->GetNext(&has_user_gesture);
blink::mojom::EvaluationTiming script_execution_type =
blink::mojom::EvaluationTiming::kSynchronous;
blink::mojom::LoadEventBlockingOption load_blocking_option =
blink::mojom::LoadEventBlockingOption::kDoNotBlock;
std::string execution_type;
args->GetNext(&execution_type);
if (execution_type == "asynchronous") {
script_execution_type = blink::mojom::EvaluationTiming::kAsynchronous;
} else if (execution_type == "asynchronousBlockingOnload") {
script_execution_type = blink::mojom::EvaluationTiming::kAsynchronous;
load_blocking_option = blink::mojom::LoadEventBlockingOption::kBlock;
}
ScriptExecutionCallback::CompletionCallback completion_callback;
args->GetNext(&completion_callback);
std::vector<blink::WebScriptSource> sources;
sources.reserve(scripts.size());
for (const auto& script : scripts) {
std::u16string code;
std::u16string url;
script.Get("url", &url);
if (!script.Get("code", &code)) {
const char error_message[] = "Invalid 'code'";
if (!completion_callback.is_null()) {
std::move(completion_callback)
.Run(v8::Undefined(isolate),
v8::Exception::Error(
v8::String::NewFromUtf8(isolate, error_message)
.ToLocalChecked()));
}
promise.RejectWithErrorMessage(error_message);
return handle;
}
sources.emplace_back(blink::WebString::FromUTF16(code),
blink::WebURL(GURL(url)));
}
// Deletes itself.
auto* self = new ScriptExecutionCallback(std::move(promise),
std::move(completion_callback));
render_frame->GetWebFrame()->RequestExecuteScript(
world_id, base::make_span(sources),
has_user_gesture ? blink::mojom::UserActivationOption::kActivate
: blink::mojom::UserActivationOption::kDoNotActivate,
script_execution_type, load_blocking_option, base::NullCallback(),
base::BindOnce(&ScriptExecutionCallback::Completed,
base::Unretained(self)),
blink::BackForwardCacheAware::kPossiblyDisallow,
blink::mojom::WantResultOption::kWantResult,
blink::mojom::PromiseResultOption::kDoNotWait);
return handle;
}
void SetIsolatedWorldInfo(v8::Isolate* isolate,
int world_id,
const gin_helper::Dictionary& options) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "setIsolatedWorldInfo", &render_frame))
return;
std::string origin_url, security_policy, name;
options.Get("securityOrigin", &origin_url);
options.Get("csp", &security_policy);
options.Get("name", &name);
if (!security_policy.empty() && origin_url.empty()) {
gin_helper::ErrorThrower(isolate).ThrowError(
"If csp is specified, securityOrigin should also be specified");
return;
}
blink::WebIsolatedWorldInfo info;
info.security_origin = blink::WebSecurityOrigin::CreateFromString(
blink::WebString::FromUTF8(origin_url));
info.content_security_policy = blink::WebString::FromUTF8(security_policy);
info.human_readable_name = blink::WebString::FromUTF8(name);
blink::SetIsolatedWorldInfo(world_id, info);
}
blink::WebCacheResourceTypeStats GetResourceUsage(v8::Isolate* isolate) {
blink::WebCacheResourceTypeStats stats;
blink::WebCache::GetResourceTypeStats(&stats);
return stats;
}
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
bool IsWordMisspelled(v8::Isolate* isolate, const std::string& word) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "isWordMisspelled", &render_frame))
return false;
return !SpellCheckWord(render_frame, word, nullptr);
}
std::vector<std::u16string> GetWordSuggestions(v8::Isolate* isolate,
const std::string& word) {
content::RenderFrame* render_frame;
std::vector<std::u16string> suggestions;
if (!MaybeGetRenderFrame(isolate, "getWordSuggestions", &render_frame))
return suggestions;
SpellCheckWord(render_frame, word, &suggestions);
return suggestions;
}
#endif
void ClearCache(v8::Isolate* isolate) {
isolate->IdleNotificationDeadline(0.5);
blink::WebCache::Clear();
base::MemoryPressureListener::NotifyMemoryPressure(
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
}
v8::Local<v8::Value> FindFrameByRoutingId(v8::Isolate* isolate,
int routing_id) {
content::RenderFrame* render_frame =
content::RenderFrame::FromRoutingID(routing_id);
if (render_frame)
return WebFrameRenderer::Create(isolate, render_frame).ToV8();
else
return v8::Null(isolate);
}
v8::Local<v8::Value> GetOpener(v8::Isolate* isolate) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "opener", &render_frame))
return v8::Null(isolate);
blink::WebFrame* frame = render_frame->GetWebFrame()->Opener();
return CreateWebFrameRenderer(isolate, frame);
}
// Don't name it as GetParent, Windows has API with same name.
v8::Local<v8::Value> GetFrameParent(v8::Isolate* isolate) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "parent", &render_frame))
return v8::Null(isolate);
blink::WebFrame* frame = render_frame->GetWebFrame()->Parent();
return CreateWebFrameRenderer(isolate, frame);
}
v8::Local<v8::Value> GetTop(v8::Isolate* isolate) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "top", &render_frame))
return v8::Null(isolate);
blink::WebFrame* frame = render_frame->GetWebFrame()->Top();
return CreateWebFrameRenderer(isolate, frame);
}
v8::Local<v8::Value> GetFirstChild(v8::Isolate* isolate) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "firstChild", &render_frame))
return v8::Null(isolate);
blink::WebFrame* frame = render_frame->GetWebFrame()->FirstChild();
return CreateWebFrameRenderer(isolate, frame);
}
v8::Local<v8::Value> GetNextSibling(v8::Isolate* isolate) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "nextSibling", &render_frame))
return v8::Null(isolate);
blink::WebFrame* frame = render_frame->GetWebFrame()->NextSibling();
return CreateWebFrameRenderer(isolate, frame);
}
v8::Local<v8::Value> GetFrameForSelector(v8::Isolate* isolate,
const std::string& selector) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "getFrameForSelector", &render_frame))
return v8::Null(isolate);
blink::WebElement element =
render_frame->GetWebFrame()->GetDocument().QuerySelector(
blink::WebString::FromUTF8(selector));
if (element.IsNull()) // not found
return v8::Null(isolate);
blink::WebFrame* frame = blink::WebFrame::FromFrameOwnerElement(element);
return CreateWebFrameRenderer(isolate, frame);
}
v8::Local<v8::Value> FindFrameByName(v8::Isolate* isolate,
const std::string& name) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "findFrameByName", &render_frame))
return v8::Null(isolate);
blink::WebFrame* frame = render_frame->GetWebFrame()->FindFrameByName(
blink::WebString::FromUTF8(name));
return CreateWebFrameRenderer(isolate, frame);
}
int GetRoutingId(v8::Isolate* isolate) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "routingId", &render_frame))
return 0;
return render_frame->GetRoutingID();
}
};
gin::WrapperInfo WebFrameRenderer::kWrapperInfo = {gin::kEmbedderNativeGin};
// static
std::set<SpellCheckerHolder*> SpellCheckerHolder::instances_;
} // namespace api
} // namespace electron
namespace {
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
using namespace electron::api; // NOLINT(build/namespaces)
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("mainFrame", WebFrameRenderer::Create(
isolate, electron::GetRenderFrame(exports)));
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_renderer_web_frame, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 39,891 |
[Bug]: NativeImage methods returned by capturePage fail with "Error: Illegal invocation"
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Ubuntu
### Operating System Version
Ubuntu 23.04
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
While calling `<webview-tag>.capturePage()` from renderer process, we should be able to run methods from the returned NativeImage (like `.getSize()`)
### Actual Behavior
While calling `<webview-tag>.capturePage()` from a renderer process, all of the NativeImage methods return the following error. In this example we call `.getSize()`:
```
Uncaught (in promise) Error: Illegal invocation: Function must be called on an object of type NativeImage
```
**Code snippet**
```js
const webviewElement = document.getElementById("webview")
webviewElement.capturePage()
.then((image) => console.log(image.getSize()))
```
**To reproduce**
**1.** Create a webview element in a page (BrowserView) and make set the id-attribute to `webview`
**2.** Execute the snippet above
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39891
|
https://github.com/electron/electron/pull/39978
|
5b105f911f7aa134ee44558fefaf171360d3d9d2
|
fd2861117e04a3c62bfab67a1b50cb9c3a55cd4d
| 2023-09-18T10:48:18Z |
c++
| 2023-10-18T14:21:42Z |
shell/renderer/renderer_client_base.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/renderer_client_base.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/command_line.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "components/network_hints/renderer/web_prescient_networking_impl.h"
#include "content/common/buildflags.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_switches.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_thread.h"
#include "electron/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "shell/browser/api/electron_api_protocol.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/color_util.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/node_includes.h"
#include "shell/common/node_util.h"
#include "shell/common/options_switches.h"
#include "shell/common/world_ids.h"
#include "shell/renderer/api/context_bridge/object_cache.h"
#include "shell/renderer/api/electron_api_context_bridge.h"
#include "shell/renderer/browser_exposed_renderer_interfaces.h"
#include "shell/renderer/content_settings_observer.h"
#include "shell/renderer/electron_api_service_impl.h"
#include "shell/renderer/electron_autofill_agent.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "third_party/blink/public/common/web_preferences/web_preferences.h"
#include "third_party/blink/public/web/blink.h"
#include "third_party/blink/public/web/web_custom_element.h" // NOLINT(build/include_alpha)
#include "third_party/blink/public/web/web_frame_widget.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_plugin_params.h"
#include "third_party/blink/public/web/web_script_source.h"
#include "third_party/blink/public/web/web_security_policy.h"
#include "third_party/blink/public/web/web_view.h"
#include "third_party/blink/renderer/platform/media/multi_buffer_data_source.h" // nogncheck
#include "third_party/blink/renderer/platform/weborigin/scheme_registry.h" // nogncheck
#include "third_party/widevine/cdm/buildflags.h"
#if BUILDFLAG(IS_MAC)
#include "base/strings/sys_string_conversions.h"
#endif
#if BUILDFLAG(IS_WIN)
#include <shlobj.h>
#endif
#if BUILDFLAG(ENABLE_WIDEVINE)
#include "chrome/renderer/media/chrome_key_systems.h" // nogncheck
#endif
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
#include "components/spellcheck/renderer/spellcheck.h"
#include "components/spellcheck/renderer/spellcheck_provider.h"
#endif
#if BUILDFLAG(ENABLE_PDF_VIEWER)
#include "chrome/common/pdf_util.h"
#include "components/pdf/common/internal_plugin_helpers.h"
#include "components/pdf/renderer/pdf_internal_plugin_delegate.h"
#include "shell/common/electron_constants.h"
#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
#if BUILDFLAG(ENABLE_PLUGINS)
#include "shell/common/plugin_info.h"
#include "shell/renderer/pepper_helper.h"
#endif // BUILDFLAG(ENABLE_PLUGINS)
#if BUILDFLAG(ENABLE_PRINTING)
#include "components/printing/renderer/print_render_frame_helper.h"
#include "printing/metafile_agent.h" // nogncheck
#include "shell/renderer/printing/print_render_frame_helper_delegate.h"
#endif // BUILDFLAG(ENABLE_PRINTING)
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "base/strings/utf_string_conversions.h"
#include "content/public/common/webplugininfo.h"
#include "extensions/common/constants.h"
#include "extensions/common/extensions_client.h"
#include "extensions/renderer/dispatcher.h"
#include "extensions/renderer/extension_frame_helper.h"
#include "extensions/renderer/extension_web_view_helper.h"
#include "extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container_manager.h"
#include "shell/common/extensions/electron_extensions_client.h"
#include "shell/renderer/extensions/electron_extensions_renderer_client.h"
#endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
namespace electron {
content::RenderFrame* GetRenderFrame(v8::Local<v8::Object> value);
namespace {
void SetIsWebView(v8::Isolate* isolate, v8::Local<v8::Object> object) {
gin_helper::Dictionary dict(isolate, object);
dict.SetHidden("isWebView", true);
}
std::vector<std::string> ParseSchemesCLISwitch(base::CommandLine* command_line,
const char* switch_name) {
std::string custom_schemes = command_line->GetSwitchValueASCII(switch_name);
return base::SplitString(custom_schemes, ",", base::TRIM_WHITESPACE,
base::SPLIT_WANT_NONEMPTY);
}
#if BUILDFLAG(ENABLE_PDF_VIEWER)
class ChromePdfInternalPluginDelegate final
: public pdf::PdfInternalPluginDelegate {
public:
ChromePdfInternalPluginDelegate() = default;
ChromePdfInternalPluginDelegate(const ChromePdfInternalPluginDelegate&) =
delete;
ChromePdfInternalPluginDelegate& operator=(
const ChromePdfInternalPluginDelegate&) = delete;
~ChromePdfInternalPluginDelegate() override = default;
// `pdf::PdfInternalPluginDelegate`:
bool IsAllowedOrigin(const url::Origin& origin) const override {
return origin.scheme() == extensions::kExtensionScheme &&
origin.host() == extension_misc::kPdfExtensionId;
}
};
#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
// static
RendererClientBase* g_renderer_client_base = nullptr;
bool IsDevTools(content::RenderFrame* render_frame) {
return render_frame->GetWebFrame()->GetDocument().Url().ProtocolIs(
"devtools");
}
bool IsDevToolsExtension(content::RenderFrame* render_frame) {
return render_frame->GetWebFrame()->GetDocument().Url().ProtocolIs(
"chrome-extension");
}
} // namespace
RendererClientBase::RendererClientBase() {
auto* command_line = base::CommandLine::ForCurrentProcess();
// Parse --service-worker-schemes=scheme1,scheme2
std::vector<std::string> service_worker_schemes_list =
ParseSchemesCLISwitch(command_line, switches::kServiceWorkerSchemes);
for (const std::string& scheme : service_worker_schemes_list)
electron::api::AddServiceWorkerScheme(scheme);
// Parse --standard-schemes=scheme1,scheme2
std::vector<std::string> standard_schemes_list =
ParseSchemesCLISwitch(command_line, switches::kStandardSchemes);
for (const std::string& scheme : standard_schemes_list)
url::AddStandardScheme(scheme.c_str(), url::SCHEME_WITH_HOST);
// Parse --cors-schemes=scheme1,scheme2
std::vector<std::string> cors_schemes_list =
ParseSchemesCLISwitch(command_line, switches::kCORSSchemes);
for (const std::string& scheme : cors_schemes_list)
url::AddCorsEnabledScheme(scheme.c_str());
// Parse --streaming-schemes=scheme1,scheme2
std::vector<std::string> streaming_schemes_list =
ParseSchemesCLISwitch(command_line, switches::kStreamingSchemes);
for (const std::string& scheme : streaming_schemes_list)
blink::AddStreamingScheme(scheme.c_str());
// Parse --secure-schemes=scheme1,scheme2
std::vector<std::string> secure_schemes_list =
ParseSchemesCLISwitch(command_line, switches::kSecureSchemes);
for (const std::string& scheme : secure_schemes_list)
url::AddSecureScheme(scheme.data());
// We rely on the unique process host id which is notified to the
// renderer process via command line switch from the content layer,
// if this switch is removed from the content layer for some reason,
// we should define our own.
DCHECK(command_line->HasSwitch(::switches::kRendererClientId));
renderer_client_id_ =
command_line->GetSwitchValueASCII(::switches::kRendererClientId);
g_renderer_client_base = this;
}
RendererClientBase::~RendererClientBase() {
g_renderer_client_base = nullptr;
}
// static
RendererClientBase* RendererClientBase::Get() {
DCHECK(g_renderer_client_base);
return g_renderer_client_base;
}
void RendererClientBase::BindProcess(v8::Isolate* isolate,
gin_helper::Dictionary* process,
content::RenderFrame* render_frame) {
auto context_id = base::StringPrintf(
"%s-%" PRId64, renderer_client_id_.c_str(), ++next_context_id_);
process->SetReadOnly("isMainFrame", render_frame->IsMainFrame());
process->SetReadOnly("contextIsolated",
render_frame->GetBlinkPreferences().context_isolation);
process->SetReadOnly("contextId", context_id);
}
bool RendererClientBase::ShouldLoadPreload(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) const {
auto prefs = render_frame->GetBlinkPreferences();
bool is_main_frame = render_frame->IsMainFrame();
bool is_devtools =
IsDevTools(render_frame) || IsDevToolsExtension(render_frame);
bool allow_node_in_sub_frames = prefs.node_integration_in_sub_frames;
return (is_main_frame || is_devtools || allow_node_in_sub_frames) &&
!IsWebViewFrame(context, render_frame);
}
void RendererClientBase::RenderThreadStarted() {
auto* command_line = base::CommandLine::ForCurrentProcess();
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
auto* thread = content::RenderThread::Get();
extensions_client_.reset(CreateExtensionsClient());
extensions::ExtensionsClient::Set(extensions_client_.get());
extensions_renderer_client_ =
std::make_unique<ElectronExtensionsRendererClient>();
extensions::ExtensionsRendererClient::Set(extensions_renderer_client_.get());
thread->AddObserver(extensions_renderer_client_->GetDispatcher());
WTF::String extension_scheme(extensions::kExtensionScheme);
// Extension resources are HTTP-like and safe to expose to the fetch API. The
// rules for the fetch API are consistent with XHR.
blink::SchemeRegistry::RegisterURLSchemeAsSupportingFetchAPI(
extension_scheme);
// Extension resources, when loaded as the top-level document, should bypass
// Blink's strict first-party origin checks.
blink::SchemeRegistry::RegisterURLSchemeAsFirstPartyWhenTopLevel(
extension_scheme);
blink::SchemeRegistry::RegisterURLSchemeAsBypassingContentSecurityPolicy(
extension_scheme);
#endif
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
spellcheck_ = std::make_unique<SpellCheck>(this);
#endif
blink::WebCustomElement::AddEmbedderCustomElementName("webview");
blink::WebCustomElement::AddEmbedderCustomElementName("browserplugin");
std::vector<std::string> fetch_enabled_schemes =
ParseSchemesCLISwitch(command_line, switches::kFetchSchemes);
for (const std::string& scheme : fetch_enabled_schemes) {
blink::WebSecurityPolicy::RegisterURLSchemeAsSupportingFetchAPI(
blink::WebString::FromASCII(scheme));
}
std::vector<std::string> service_worker_schemes =
ParseSchemesCLISwitch(command_line, switches::kServiceWorkerSchemes);
for (const std::string& scheme : service_worker_schemes)
blink::WebSecurityPolicy::RegisterURLSchemeAsAllowingServiceWorkers(
blink::WebString::FromASCII(scheme));
std::vector<std::string> csp_bypassing_schemes =
ParseSchemesCLISwitch(command_line, switches::kBypassCSPSchemes);
for (const std::string& scheme : csp_bypassing_schemes)
blink::SchemeRegistry::RegisterURLSchemeAsBypassingContentSecurityPolicy(
WTF::String::FromUTF8(scheme.data(), scheme.length()));
// Allow file scheme to handle service worker by default.
// FIXME(zcbenz): Can this be moved elsewhere?
blink::WebSecurityPolicy::RegisterURLSchemeAsAllowingServiceWorkers("file");
blink::SchemeRegistry::RegisterURLSchemeAsSupportingFetchAPI("file");
#if BUILDFLAG(IS_WIN)
// Set ApplicationUserModelID in renderer process.
std::wstring app_id =
command_line->GetSwitchValueNative(switches::kAppUserModelId);
if (!app_id.empty()) {
SetCurrentProcessExplicitAppUserModelID(app_id.c_str());
}
#endif
}
void RendererClientBase::ExposeInterfacesToBrowser(mojo::BinderMap* binders) {
// NOTE: Do not add binders directly within this method. Instead, modify the
// definition of |ExposeElectronRendererInterfacesToBrowser()| to ensure
// security review coverage.
ExposeElectronRendererInterfacesToBrowser(this, binders);
}
void RendererClientBase::RenderFrameCreated(
content::RenderFrame* render_frame) {
#if defined(TOOLKIT_VIEWS)
new AutofillAgent(render_frame,
render_frame->GetAssociatedInterfaceRegistry());
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
new PepperHelper(render_frame);
#endif
new ContentSettingsObserver(render_frame);
#if BUILDFLAG(ENABLE_PRINTING)
new printing::PrintRenderFrameHelper(
render_frame,
std::make_unique<electron::PrintRenderFrameHelperDelegate>());
#endif
// Note: ElectronApiServiceImpl has to be created now to capture the
// DidCreateDocumentElement event.
new ElectronApiServiceImpl(render_frame, this);
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
auto* dispatcher = extensions_renderer_client_->GetDispatcher();
// ExtensionFrameHelper destroys itself when the RenderFrame is destroyed.
new extensions::ExtensionFrameHelper(render_frame, dispatcher);
dispatcher->OnRenderFrameCreated(render_frame);
render_frame->GetAssociatedInterfaceRegistry()
->AddInterface<extensions::mojom::MimeHandlerViewContainerManager>(
base::BindRepeating(
&extensions::MimeHandlerViewContainerManager::BindReceiver,
render_frame->GetRoutingID()));
#endif
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
if (render_frame->GetBlinkPreferences().enable_spellcheck)
new SpellCheckProvider(render_frame, spellcheck_.get(), this);
#endif
}
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
void RendererClientBase::GetInterface(
const std::string& interface_name,
mojo::ScopedMessagePipeHandle interface_pipe) {
// TODO(crbug.com/977637): Get rid of the use of this implementation of
// |service_manager::LocalInterfaceProvider|. This was done only to avoid
// churning spellcheck code while eliminating the "chrome" and
// "chrome_renderer" services. Spellcheck is (and should remain) the only
// consumer of this implementation.
content::RenderThread::Get()->BindHostReceiver(
mojo::GenericPendingReceiver(interface_name, std::move(interface_pipe)));
}
#endif
void RendererClientBase::DidClearWindowObject(
content::RenderFrame* render_frame) {
// Make sure every page will get a script context created.
render_frame->GetWebFrame()->ExecuteScript(blink::WebScriptSource("void 0"));
}
bool RendererClientBase::OverrideCreatePlugin(
content::RenderFrame* render_frame,
const blink::WebPluginParams& params,
blink::WebPlugin** plugin) {
#if BUILDFLAG(ENABLE_PDF_VIEWER)
if (params.mime_type.Utf8() == pdf::kInternalPluginMimeType) {
*plugin = pdf::CreateInternalPlugin(
std::move(params), render_frame,
std::make_unique<ChromePdfInternalPluginDelegate>());
return true;
}
#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
if (params.mime_type.Utf8() == content::kBrowserPluginMimeType ||
render_frame->GetBlinkPreferences().enable_plugins)
return false;
*plugin = nullptr;
return true;
}
void RendererClientBase::GetSupportedKeySystems(
media::GetSupportedKeySystemsCB cb) {
#if BUILDFLAG(ENABLE_WIDEVINE)
GetChromeKeySystems(std::move(cb));
#else
std::move(cb).Run({});
#endif
}
void RendererClientBase::DidSetUserAgent(const std::string& user_agent) {
#if BUILDFLAG(ENABLE_PRINTING)
printing::SetAgent(user_agent);
#endif
}
bool RendererClientBase::IsPluginHandledExternally(
content::RenderFrame* render_frame,
const blink::WebElement& plugin_element,
const GURL& original_url,
const std::string& mime_type) {
#if BUILDFLAG(ENABLE_PDF_VIEWER)
DCHECK(plugin_element.HasHTMLTagName("object") ||
plugin_element.HasHTMLTagName("embed"));
if (mime_type == pdf::kInternalPluginMimeType) {
if (IsPdfInternalPluginAllowedOrigin(
render_frame->GetWebFrame()->GetSecurityOrigin())) {
return true;
}
content::WebPluginInfo info;
info.type = content::WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS;
info.name = base::ASCIIToUTF16(kPDFInternalPluginName);
info.path = base::FilePath(kPdfPluginPath);
info.background_color = content::WebPluginInfo::kDefaultBackgroundColor;
info.mime_types.emplace_back(pdf::kInternalPluginMimeType, "pdf",
"Portable Document Format");
return extensions::MimeHandlerViewContainerManager::Get(
content::RenderFrame::FromWebFrame(
plugin_element.GetDocument().GetFrame()),
true /* create_if_does_not_exist */)
->CreateFrameContainer(plugin_element, original_url, mime_type, info);
}
return extensions::MimeHandlerViewContainerManager::Get(
content::RenderFrame::FromWebFrame(
plugin_element.GetDocument().GetFrame()),
true /* create_if_does_not_exist */)
->CreateFrameContainer(plugin_element, original_url, mime_type,
GetPDFPluginInfo());
#else
return false;
#endif
}
v8::Local<v8::Object> RendererClientBase::GetScriptableObject(
const blink::WebElement& plugin_element,
v8::Isolate* isolate) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// If there is a MimeHandlerView that can provide the scriptable object then
// MaybeCreateMimeHandlerView must have been called before and a container
// manager should exist.
auto* container_manager = extensions::MimeHandlerViewContainerManager::Get(
content::RenderFrame::FromWebFrame(
plugin_element.GetDocument().GetFrame()),
false /* create_if_does_not_exist */);
if (container_manager)
return container_manager->GetScriptableObject(plugin_element, isolate);
#endif
return v8::Local<v8::Object>();
}
std::unique_ptr<blink::WebPrescientNetworking>
RendererClientBase::CreatePrescientNetworking(
content::RenderFrame* render_frame) {
return std::make_unique<network_hints::WebPrescientNetworkingImpl>(
render_frame);
}
void RendererClientBase::RunScriptsAtDocumentStart(
content::RenderFrame* render_frame) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_.get()->RunScriptsAtDocumentStart(render_frame);
#endif
}
void RendererClientBase::RunScriptsAtDocumentIdle(
content::RenderFrame* render_frame) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_.get()->RunScriptsAtDocumentIdle(render_frame);
#endif
}
void RendererClientBase::RunScriptsAtDocumentEnd(
content::RenderFrame* render_frame) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_.get()->RunScriptsAtDocumentEnd(render_frame);
#endif
}
bool RendererClientBase::AllowScriptExtensionForServiceWorker(
const url::Origin& script_origin) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
return script_origin.scheme() == extensions::kExtensionScheme;
#else
return false;
#endif
}
void RendererClientBase::DidInitializeServiceWorkerContextOnWorkerThread(
blink::WebServiceWorkerContextProxy* context_proxy,
const GURL& service_worker_scope,
const GURL& script_url) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_->GetDispatcher()
->DidInitializeServiceWorkerContextOnWorkerThread(
context_proxy, service_worker_scope, script_url);
#endif
}
void RendererClientBase::WillEvaluateServiceWorkerOnWorkerThread(
blink::WebServiceWorkerContextProxy* context_proxy,
v8::Local<v8::Context> v8_context,
int64_t service_worker_version_id,
const GURL& service_worker_scope,
const GURL& script_url) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_->GetDispatcher()
->WillEvaluateServiceWorkerOnWorkerThread(
context_proxy, v8_context, service_worker_version_id,
service_worker_scope, script_url);
#endif
}
void RendererClientBase::DidStartServiceWorkerContextOnWorkerThread(
int64_t service_worker_version_id,
const GURL& service_worker_scope,
const GURL& script_url) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_->GetDispatcher()
->DidStartServiceWorkerContextOnWorkerThread(
service_worker_version_id, service_worker_scope, script_url);
#endif
}
void RendererClientBase::WillDestroyServiceWorkerContextOnWorkerThread(
v8::Local<v8::Context> context,
int64_t service_worker_version_id,
const GURL& service_worker_scope,
const GURL& script_url) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_->GetDispatcher()
->WillDestroyServiceWorkerContextOnWorkerThread(
context, service_worker_version_id, service_worker_scope, script_url);
#endif
}
void RendererClientBase::WebViewCreated(blink::WebView* web_view,
bool was_created_by_renderer,
const url::Origin* outermost_origin) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
new extensions::ExtensionWebViewHelper(web_view, outermost_origin);
#endif
}
v8::Local<v8::Context> RendererClientBase::GetContext(
blink::WebLocalFrame* frame,
v8::Isolate* isolate) const {
auto* render_frame = content::RenderFrame::FromWebFrame(frame);
DCHECK(render_frame);
if (render_frame && render_frame->GetBlinkPreferences().context_isolation)
return frame->GetScriptContextFromWorldId(isolate,
WorldIDs::ISOLATED_WORLD_ID);
else
return frame->MainWorldScriptContext();
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ExtensionsClient* RendererClientBase::CreateExtensionsClient() {
return new ElectronExtensionsClient;
}
#endif
bool RendererClientBase::IsWebViewFrame(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) const {
auto* isolate = context->GetIsolate();
if (render_frame->IsMainFrame())
return false;
gin::Dictionary window_dict(
isolate, GetContext(render_frame->GetWebFrame(), isolate)->Global());
v8::Local<v8::Object> frame_element;
if (!window_dict.Get("frameElement", &frame_element))
return false;
gin_helper::Dictionary frame_element_dict(isolate, frame_element);
bool is_webview = false;
return frame_element_dict.GetHidden("isWebView", &is_webview) && is_webview;
}
void RendererClientBase::SetupMainWorldOverrides(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) {
auto prefs = render_frame->GetBlinkPreferences();
// We only need to run the isolated bundle if webview is enabled
if (!prefs.webview_tag)
return;
// Setup window overrides in the main world context
// Wrap the bundle into a function that receives the isolatedApi as
// an argument.
auto* isolate = context->GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context);
auto isolated_api = gin_helper::Dictionary::CreateEmpty(isolate);
isolated_api.SetMethod("allowGuestViewElementDefinition",
&AllowGuestViewElementDefinition);
isolated_api.SetMethod("setIsWebView", &SetIsWebView);
auto source_context = GetContext(render_frame->GetWebFrame(), isolate);
gin_helper::Dictionary global(isolate, source_context->Global());
v8::Local<v8::Value> guest_view_internal;
if (global.GetHidden("guestViewInternal", &guest_view_internal)) {
api::context_bridge::ObjectCache object_cache;
auto result = api::PassValueToOtherContext(
source_context, context, guest_view_internal, &object_cache, false, 0,
api::BridgeErrorTarget::kSource);
if (!result.IsEmpty()) {
isolated_api.Set("guestViewInternal", result.ToLocalChecked());
}
}
std::vector<v8::Local<v8::String>> isolated_bundle_params = {
node::FIXED_ONE_BYTE_STRING(isolate, "isolatedApi")};
std::vector<v8::Local<v8::Value>> isolated_bundle_args = {
isolated_api.GetHandle()};
util::CompileAndCall(context, "electron/js2c/isolated_bundle",
&isolated_bundle_params, &isolated_bundle_args, nullptr);
}
// static
void RendererClientBase::AllowGuestViewElementDefinition(
v8::Isolate* isolate,
v8::Local<v8::Object> context,
v8::Local<v8::Function> register_cb) {
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context->GetCreationContextChecked());
blink::WebCustomElement::EmbedderNamesAllowedScope embedder_names_scope;
content::RenderFrame* render_frame = GetRenderFrame(context);
if (!render_frame)
return;
render_frame->GetWebFrame()->RequestExecuteV8Function(
context->GetCreationContextChecked(), register_cb, v8::Null(isolate), 0,
nullptr, base::NullCallback());
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 39,891 |
[Bug]: NativeImage methods returned by capturePage fail with "Error: Illegal invocation"
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Ubuntu
### Operating System Version
Ubuntu 23.04
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
While calling `<webview-tag>.capturePage()` from renderer process, we should be able to run methods from the returned NativeImage (like `.getSize()`)
### Actual Behavior
While calling `<webview-tag>.capturePage()` from a renderer process, all of the NativeImage methods return the following error. In this example we call `.getSize()`:
```
Uncaught (in promise) Error: Illegal invocation: Function must be called on an object of type NativeImage
```
**Code snippet**
```js
const webviewElement = document.getElementById("webview")
webviewElement.capturePage()
.then((image) => console.log(image.getSize()))
```
**To reproduce**
**1.** Create a webview element in a page (BrowserView) and make set the id-attribute to `webview`
**2.** Execute the snippet above
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39891
|
https://github.com/electron/electron/pull/39978
|
5b105f911f7aa134ee44558fefaf171360d3d9d2
|
fd2861117e04a3c62bfab67a1b50cb9c3a55cd4d
| 2023-09-18T10:48:18Z |
c++
| 2023-10-18T14:21:42Z |
spec/webview-spec.ts
|
import * as path from 'node:path';
import * as url from 'node:url';
import { BrowserWindow, session, ipcMain, app, WebContents } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import { emittedUntil } from './lib/events-helpers';
import { ifit, ifdescribe, defer, itremote, useRemoteContext, listen } from './lib/spec-helpers';
import { expect } from 'chai';
import * as http from 'node:http';
import * as auth from 'basic-auth';
import { once } from 'node:events';
import { setTimeout } from 'node:timers/promises';
declare let WebView: any;
const features = process._linkedBinding('electron_common_features');
async function loadWebView (w: WebContents, attributes: Record<string, string>, opts?: {openDevTools?: boolean}): Promise<void> {
const { openDevTools } = {
openDevTools: false,
...opts
};
await w.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView()
webview.id = 'webview'
for (const [k, v] of Object.entries(${JSON.stringify(attributes)})) {
webview.setAttribute(k, v)
}
document.body.appendChild(webview)
webview.addEventListener('dom-ready', () => {
if (${openDevTools}) {
webview.openDevTools()
}
})
webview.addEventListener('did-finish-load', () => {
resolve()
})
})
`);
}
async function loadWebViewAndWaitForEvent (w: WebContents, attributes: Record<string, string>, eventName: string): Promise<any> {
return await w.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.id = 'webview'
for (const [k, v] of Object.entries(${JSON.stringify(attributes)})) {
webview.setAttribute(k, v)
}
webview.addEventListener(${JSON.stringify(eventName)}, (e) => resolve({...e}), {once: true})
document.body.appendChild(webview)
})`);
};
async function loadWebViewAndWaitForMessage (w: WebContents, attributes: Record<string, string>): Promise<string> {
const { message } = await loadWebViewAndWaitForEvent(w, attributes, 'console-message');
return message;
};
describe('<webview> tag', function () {
const fixtures = path.join(__dirname, 'fixtures');
const blankPageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'blank.html')).toString();
function hideChildWindows (e: any, wc: WebContents) {
wc.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
show: false
}
}));
}
before(() => {
app.on('web-contents-created', hideChildWindows);
});
after(() => {
app.off('web-contents-created', hideChildWindows);
});
describe('behavior', () => {
afterEach(closeAllWindows);
it('works without script tag in page', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html'));
await once(ipcMain, 'pong');
});
it('works with sandbox', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
sandbox: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html'));
await once(ipcMain, 'pong');
});
it('works with contextIsolation', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html'));
await once(ipcMain, 'pong');
});
it('works with contextIsolation + sandbox', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true,
sandbox: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html'));
await once(ipcMain, 'pong');
});
it('works with Trusted Types', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-trusted-types.html'));
await once(ipcMain, 'pong');
});
it('is disabled by default', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
preload: path.join(fixtures, 'module', 'preload-webview.js'),
nodeIntegration: true
}
});
const webview = once(ipcMain, 'webview');
w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html'));
const [, type] = await webview;
expect(type).to.equal('undefined', 'WebView still exists');
});
});
// FIXME(deepak1556): Ch69 follow up.
xdescribe('document.visibilityState/hidden', () => {
afterEach(() => {
ipcMain.removeAllListeners('pong');
});
afterEach(closeAllWindows);
it('updates when the window is shown after the ready-to-show event', async () => {
const w = new BrowserWindow({ show: false });
const readyToShowSignal = once(w, 'ready-to-show');
const pongSignal1 = once(ipcMain, 'pong');
w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html'));
await pongSignal1;
const pongSignal2 = once(ipcMain, 'pong');
await readyToShowSignal;
w.show();
const [, visibilityState, hidden] = await pongSignal2;
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false();
});
it('inherits the parent window visibility state and receives visibilitychange events', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html'));
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true();
// We have to start waiting for the event
// before we ask the webContents to resize.
const getResponse = once(ipcMain, 'pong');
w.webContents.emit('-window-visibility-change', 'visible');
return getResponse.then(([, visibilityState, hidden]) => {
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false();
});
});
});
describe('did-attach-webview event', () => {
afterEach(closeAllWindows);
it('is emitted when a webview has been attached', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: 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('did-attach event', () => {
afterEach(closeAllWindows);
it('is emitted when a webview has been attached', async () => {
const w = new BrowserWindow({
webPreferences: {
webviewTag: true
}
});
await w.loadURL('about:blank');
const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', 'about:blank')
webview.addEventListener('did-attach', (e) => {
resolve('ok')
})
document.body.appendChild(webview)
})`);
expect(message).to.equal('ok');
});
});
describe('did-change-theme-color event', () => {
afterEach(closeAllWindows);
it('emits when theme color changes', async () => {
const w = new BrowserWindow({
webPreferences: {
webviewTag: true
}
});
await w.loadURL('about:blank');
const src = url.format({
pathname: `${fixtures.replaceAll('\\', '/')}/pages/theme-color.html`,
protocol: 'file',
slashes: true
});
const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', '${src}')
webview.addEventListener('did-change-theme-color', (e) => {
resolve('ok')
})
document.body.appendChild(webview)
})`);
expect(message).to.equal('ok');
});
});
describe('devtools', () => {
afterEach(closeAllWindows);
// FIXME: This test is flaky on WOA, so skip it there.
ifit(process.platform !== 'win32' || process.arch !== 'arm64')('loads devtools extensions registered on the parent window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
w.webContents.session.removeExtension('foo');
const extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo');
await w.webContents.session.loadExtension(extensionPath, {
allowFileAccess: true
});
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'webview-devtools.html'));
loadWebView(w.webContents, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(__dirname, 'fixtures', 'blank.html')}`
}, { openDevTools: true });
let childWebContentsId = 0;
app.once('web-contents-created', (e, webContents) => {
childWebContentsId = webContents.id;
webContents.on('devtools-opened', function () {
const showPanelIntervalId = setInterval(function () {
if (!webContents.isDestroyed() && webContents.devToolsWebContents) {
webContents.devToolsWebContents.executeJavaScript('(' + function () {
const { UI } = (window as any);
const tabs = UI.inspectorView.tabbedPane.tabs;
const lastPanelId: any = tabs[tabs.length - 1].id;
UI.inspectorView.showPanel(lastPanelId);
}.toString() + ')()');
} else {
clearInterval(showPanelIntervalId);
}
}, 100);
});
});
const [, { runtimeId, tabId }] = await once(ipcMain, 'answer');
expect(runtimeId).to.match(/^[a-z]{32}$/);
expect(tabId).to.equal(childWebContentsId);
await w.webContents.executeJavaScript('webview.closeDevTools()');
});
});
describe('zoom behavior', () => {
const zoomScheme = standardScheme;
const webviewSession = session.fromPartition('webview-temp');
afterEach(closeAllWindows);
before(() => {
const protocol = webviewSession.protocol;
protocol.registerStringProtocol(zoomScheme, (request, callback) => {
callback('hello');
});
});
after(() => {
const protocol = webviewSession.protocol;
protocol.unregisterProtocol(zoomScheme);
});
it('inherits the zoomFactor of the parent window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
});
const zoomEventPromise = once(ipcMain, 'webview-parent-zoom-level');
w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-factor.html'));
const [, zoomFactor, zoomLevel] = await zoomEventPromise;
expect(zoomFactor).to.equal(1.2);
expect(zoomLevel).to.equal(1);
});
it('maintains zoom level on navigation', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
});
const promise = new Promise<void>((resolve) => {
ipcMain.on('webview-zoom-level', (event, zoomLevel, zoomFactor, newHost, final) => {
if (!newHost) {
expect(zoomFactor).to.equal(1.44);
expect(zoomLevel).to.equal(2.0);
} else {
expect(zoomFactor).to.equal(1.2);
expect(zoomLevel).to.equal(1);
}
if (final) {
resolve();
}
});
});
w.loadFile(path.join(fixtures, 'pages', 'webview-custom-zoom-level.html'));
await promise;
});
it('maintains zoom level when navigating within same page', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
});
const promise = new Promise<void>((resolve) => {
ipcMain.on('webview-zoom-in-page', (event, zoomLevel, zoomFactor, final) => {
expect(zoomFactor).to.equal(1.44);
expect(zoomLevel).to.equal(2.0);
if (final) {
resolve();
}
});
});
w.loadFile(path.join(fixtures, 'pages', 'webview-in-page-navigate.html'));
await promise;
});
it('inherits zoom level for the origin when available', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-origin-zoom-level.html'));
const [, zoomLevel] = await once(ipcMain, 'webview-origin-zoom-level');
expect(zoomLevel).to.equal(2.0);
});
it('does not crash when navigating with zoom level inherited from parent', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
session: webviewSession,
contextIsolation: false
}
});
const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
const readyPromise = once(ipcMain, 'dom-ready');
w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-inherited.html'));
const [, webview] = await attachPromise;
await readyPromise;
expect(webview.getZoomFactor()).to.equal(1.2);
await w.loadURL(`${zoomScheme}://host1`);
});
it('does not crash when changing zoom level after webview is destroyed', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
session: webviewSession,
contextIsolation: false
}
});
const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
await w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-inherited.html'));
await attachPromise;
await w.webContents.executeJavaScript('view.remove()');
w.webContents.setZoomLevel(0.5);
});
});
describe('requestFullscreen from webview', () => {
afterEach(closeAllWindows);
async function loadWebViewWindow (): Promise<[BrowserWindow, WebContents]> {
const w = new BrowserWindow({
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
const loadPromise = once(w.webContents, 'did-finish-load');
const readyPromise = once(ipcMain, 'webview-ready');
w.loadFile(path.join(__dirname, 'fixtures', 'webview', 'fullscreen', 'main.html'));
const [, webview] = await attachPromise;
await Promise.all([readyPromise, loadPromise]);
return [w, webview];
};
afterEach(async () => {
// The leaving animation is un-observable but can interfere with future tests
// Specifically this is async on macOS but can be on other platforms too
await setTimeout(1000);
closeAllWindows();
});
ifit(process.platform !== 'darwin')('should make parent frame element fullscreen too (non-macOS)', async () => {
const [w, webview] = await loadWebViewWindow();
expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.false();
const parentFullscreen = once(ipcMain, 'fullscreenchange');
await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await parentFullscreen;
expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.true();
const close = once(w, 'closed');
w.close();
await close;
});
ifit(process.platform === 'darwin')('should make parent frame element fullscreen too (macOS)', async () => {
const [w, webview] = await loadWebViewWindow();
expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.false();
const parentFullscreen = once(ipcMain, 'fullscreenchange');
const enterHTMLFS = once(w.webContents, 'enter-html-full-screen');
const leaveHTMLFS = once(w.webContents, 'leave-html-full-screen');
await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.true();
await webview.executeJavaScript('document.exitFullscreen()');
await Promise.all([enterHTMLFS, leaveHTMLFS, parentFullscreen]);
const close = once(w, 'closed');
w.close();
await close;
});
// FIXME(zcbenz): Fullscreen events do not work on Linux.
ifit(process.platform !== 'linux')('exiting fullscreen should unfullscreen window', async () => {
const [w, webview] = await loadWebViewWindow();
const enterFullScreen = once(w, 'enter-full-screen');
await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
const leaveFullScreen = once(w, 'leave-full-screen');
await webview.executeJavaScript('document.exitFullscreen()', true);
await leaveFullScreen;
await setTimeout();
expect(w.isFullScreen()).to.be.false();
const close = once(w, 'closed');
w.close();
await close;
});
// Sending ESC via sendInputEvent only works on Windows.
ifit(process.platform === 'win32')('pressing ESC should unfullscreen window', async () => {
const [w, webview] = await loadWebViewWindow();
const enterFullScreen = once(w, 'enter-full-screen');
await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
const leaveFullScreen = once(w, 'leave-full-screen');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
await leaveFullScreen;
await setTimeout();
expect(w.isFullScreen()).to.be.false();
const close = once(w, 'closed');
w.close();
await close;
});
it('pressing ESC should emit the leave-html-full-screen event', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
const didAttachWebview = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'));
const [, webContents] = await didAttachWebview;
const enterFSWindow = once(w, 'enter-html-full-screen');
const enterFSWebview = once(webContents, 'enter-html-full-screen');
await webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFSWindow;
await enterFSWebview;
const leaveFSWindow = once(w, 'leave-html-full-screen');
const leaveFSWebview = once(webContents, 'leave-html-full-screen');
webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
await leaveFSWebview;
await leaveFSWindow;
const close = once(w, 'closed');
w.close();
await close;
});
it('should support user gesture', async () => {
const [w, webview] = await loadWebViewWindow();
const waitForEnterHtmlFullScreen = once(webview, 'enter-html-full-screen');
const jsScript = "document.querySelector('video').webkitRequestFullscreen()";
webview.executeJavaScript(jsScript, true);
await waitForEnterHtmlFullScreen;
const close = once(w, 'closed');
w.close();
await close;
});
});
describe('child windows', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
it('opens window of about:blank with cross-scripting enabled', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-blank.html')}`
});
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('Hello');
});
it('opens window of same domain with cross-scripting enabled', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-file.html')}`
});
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('Hello');
});
it('returns null from window.open when allowpopups is not set', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-no-allowpopups.html')}`
});
const [, { windowOpenReturnedNull }] = await once(ipcMain, 'answer');
expect(windowOpenReturnedNull).to.be.true();
});
it('blocks accessing cross-origin frames', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-cross-origin.html')}`
});
const [, content] = await once(ipcMain, 'answer');
const expectedContent =
/Failed to read a named property 'toString' from 'Location': Blocked a frame with origin "(.*?)" from accessing a cross-origin frame./;
expect(content).to.match(expectedContent);
});
it('emits a browser-window-created event', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/window-open.html`
});
await once(app, 'browser-window-created');
});
it('emits a web-contents-created event', async () => {
const webContentsCreated = emittedUntil(app, 'web-contents-created',
(event: Electron.Event, contents: Electron.WebContents) => contents.getType() === 'window');
loadWebView(w.webContents, {
allowpopups: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/window-open.html`
});
await webContentsCreated;
});
it('does not crash when creating window with noopener', async () => {
loadWebView(w.webContents, {
allowpopups: 'on',
src: `file://${path.join(fixtures, 'api', 'native-window-open-noopener.html')}`
});
await once(app, 'browser-window-created');
});
});
describe('webpreferences attribute', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true } });
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
it('can enable context isolation', async () => {
loadWebView(w.webContents, {
allowpopups: 'yes',
preload: `file://${fixtures}/api/isolated-preload.js`,
src: `file://${fixtures}/api/isolated.html`,
webpreferences: 'contextIsolation=yes'
});
const [, data] = await once(ipcMain, 'isolated-world');
expect(data).to.deep.equal({
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'
}
});
});
});
describe('permission request handlers', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
const partition = 'permissionTest';
function setUpRequestHandler (webContentsId: number, requestedPermission: string) {
return new Promise<void>((resolve, reject) => {
session.fromPartition(partition).setPermissionRequestHandler(function (webContents, permission, callback) {
if (webContents.id === webContentsId) {
// requestMIDIAccess with sysex requests both midi and midiSysex so
// grant the first midi one and then reject the midiSysex one
if (requestedPermission === 'midiSysex' && permission === 'midi') {
return callback(true);
}
try {
expect(permission).to.equal(requestedPermission);
} catch (e) {
return reject(e);
}
callback(false);
resolve();
}
});
});
}
afterEach(() => {
session.fromPartition(partition).setPermissionRequestHandler(null);
});
// This is disabled because CI machines don't have cameras or microphones,
// so Chrome responds with "NotFoundError" instead of
// "PermissionDeniedError". It should be re-enabled if we find a way to mock
// the presence of a microphone & camera.
xit('emits when using navigator.getUserMedia api', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/media.html`,
partition,
nodeintegration: 'on'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
setUpRequestHandler(webViewContents.id, 'media');
const [, errorName] = await errorFromRenderer;
expect(errorName).to.equal('PermissionDeniedError');
});
it('emits when using navigator.geolocation api', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/geolocation.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
setUpRequestHandler(webViewContents.id, 'geolocation');
const [, error] = await errorFromRenderer;
expect(error).to.equal('User denied Geolocation');
});
it('emits when using navigator.requestMIDIAccess without sysex api', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/midi.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
setUpRequestHandler(webViewContents.id, 'midi');
const [, error] = await errorFromRenderer;
expect(error).to.equal('SecurityError');
});
it('emits when using navigator.requestMIDIAccess with sysex api', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/midi-sysex.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
setUpRequestHandler(webViewContents.id, 'midiSysex');
const [, error] = await errorFromRenderer;
expect(error).to.equal('SecurityError');
});
it('emits when accessing external protocol', async () => {
loadWebView(w.webContents, {
src: 'magnet:test',
partition
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
await setUpRequestHandler(webViewContents.id, 'openExternal');
});
it('emits when using Notification.requestPermission', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/notification.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
await setUpRequestHandler(webViewContents.id, 'notifications');
const [, error] = await errorFromRenderer;
expect(error).to.equal('denied');
});
});
describe('DOM events', () => {
afterEach(closeAllWindows);
it('receives extra properties on DOM events when contextIsolation is enabled', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true
}
});
await w.loadURL('about:blank');
const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', 'data:text/html,<script>console.log("hi")</script>')
webview.addEventListener('console-message', (e) => {
resolve(e.message)
})
document.body.appendChild(webview)
})`);
expect(message).to.equal('hi');
});
it('emits focus event when contextIsolation is enabled', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true
}
});
await w.loadURL('about:blank');
await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', 'about:blank')
webview.addEventListener('dom-ready', () => {
webview.focus()
})
webview.addEventListener('focus', () => {
resolve();
})
document.body.appendChild(webview)
})`);
});
});
describe('attributes', () => {
let w: WebContents;
before(async () => {
const window = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
await window.loadURL(`file://${fixtures}/pages/blank.html`);
w = window.webContents;
});
afterEach(async () => {
await w.executeJavaScript(`{
for (const el of document.querySelectorAll('webview')) el.remove();
}`);
});
after(closeAllWindows);
describe('src attribute', () => {
it('specifies the page to load', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/a.html`
});
expect(message).to.equal('a');
});
it('navigates to new page when changed', async () => {
await loadWebView(w, {
src: `file://${fixtures}/pages/a.html`
});
const { message } = await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('console-message', e => resolve({message: e.message}))
webview.src = ${JSON.stringify(`file://${fixtures}/pages/b.html`)}
})`);
expect(message).to.equal('b');
});
it('resolves relative URLs', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
src: './e.html'
});
expect(message).to.equal('Window script is loaded before preload script');
});
it('ignores empty values', async () => {
loadWebView(w, {});
for (const emptyValue of ['""', 'null', 'undefined']) {
const src = await w.executeJavaScript(`webview.src = ${emptyValue}, webview.src`);
expect(src).to.equal('');
}
});
it('does not wait until loadURL is resolved', async () => {
await loadWebView(w, { src: 'about:blank' });
const delay = await w.executeJavaScript(`new Promise(resolve => {
const before = Date.now();
webview.src = 'file://${fixtures}/pages/blank.html';
const now = Date.now();
resolve(now - before);
})`);
// Setting src is essentially sending a sync IPC message, which should
// not exceed more than a few ms.
//
// This is for testing #18638.
expect(delay).to.be.below(100);
});
});
describe('nodeintegration attribute', () => {
it('inserts no node symbols when not set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/c.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'undefined',
module: 'undefined',
process: 'undefined',
global: 'undefined'
});
});
it('inserts node symbols when set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/d.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('loads node symbols after POST navigation when set', async function () {
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/post.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('disables node integration on child windows when it is disabled on the webview', async () => {
const src = url.format({
pathname: `${fixtures}/pages/webview-opener-no-node-integration.html`,
protocol: 'file',
query: {
p: `${fixtures}/pages/window-opener-node.html`
},
slashes: true
});
const message = await loadWebViewAndWaitForMessage(w, {
allowpopups: 'on',
webpreferences: 'contextIsolation=no',
src
});
expect(JSON.parse(message).isProcessGlobalUndefined).to.be.true();
});
ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native modules when navigation happens', async function () {
await loadWebView(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/native-module.html`
});
const message = await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('console-message', e => resolve(e.message))
webview.reload();
})`);
expect(message).to.equal('function');
});
});
describe('preload attribute', () => {
useRemoteContext({ webPreferences: { webviewTag: true } });
it('loads the script before other scripts in window', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload.js`,
src: `file://${fixtures}/pages/e.html`
});
expect(message).to.be.a('string');
expect(message).to.be.not.equal('Window script is loaded before preload script');
});
it('preload script can still use "process" and "Buffer" when nodeintegration is off', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload-node-off.js`,
src: `file://${fixtures}/api/blank.html`
});
const types = JSON.parse(message);
expect(types).to.include({
process: 'object',
Buffer: 'function'
});
});
it('runs in the correct scope when sandboxed', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload-context.js`,
src: `file://${fixtures}/api/blank.html`,
webpreferences: 'sandbox=yes'
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function', // arguments passed to it should be available
electron: 'undefined', // objects from the scope it is called from should not be available
window: 'object', // the window object should be available
localVar: 'undefined' // but local variables should not be exposed to the window
});
});
it('preload script can require modules that still use "process" and "Buffer" when nodeintegration is off', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload-node-off-wrapper.js`,
webpreferences: 'sandbox=no',
src: `file://${fixtures}/api/blank.html`
});
const types = JSON.parse(message);
expect(types).to.include({
process: 'object',
Buffer: 'function'
});
});
it('receives ipc message in preload script', async () => {
await loadWebView(w, {
preload: `${fixtures}/module/preload-ipc.js`,
src: `file://${fixtures}/pages/e.html`
});
const message = 'boom!';
const { channel, args } = await w.executeJavaScript(`new Promise(resolve => {
webview.send('ping', ${JSON.stringify(message)})
webview.addEventListener('ipc-message', ({channel, args}) => resolve({channel, args}))
})`);
expect(channel).to.equal('pong');
expect(args).to.deep.equal([message]);
});
itremote('<webview>.sendToFrame()', async (fixtures: string) => {
const w = new WebView();
w.setAttribute('nodeintegration', 'on');
w.setAttribute('webpreferences', 'contextIsolation=no');
w.setAttribute('preload', `file://${fixtures}/module/preload-ipc.js`);
w.setAttribute('src', `file://${fixtures}/pages/ipc-message.html`);
document.body.appendChild(w);
const { frameId } = await new Promise<any>(resolve => w.addEventListener('ipc-message', resolve, { once: true }));
const message = 'boom!';
w.sendToFrame(frameId, 'ping', message);
const { channel, args } = await new Promise<any>(resolve => w.addEventListener('ipc-message', resolve, { once: true }));
expect(channel).to.equal('pong');
expect(args).to.deep.equal([message]);
}, [fixtures]);
it('works without script tag in page', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload.js`,
webpreferences: 'sandbox=no',
src: `file://${fixtures}/pages/base-page.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object',
Buffer: 'function'
});
});
it('resolves relative URLs', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: '../module/preload.js',
webpreferences: 'sandbox=no',
src: `file://${fixtures}/pages/e.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object',
Buffer: 'function'
});
});
itremote('ignores empty values', async () => {
const webview = new WebView();
for (const emptyValue of ['', null, undefined]) {
webview.preload = emptyValue;
expect(webview.preload).to.equal('');
}
});
});
describe('httpreferrer attribute', () => {
it('sets the referrer url', async () => {
const referrer = 'http://github.com/';
const received = await new Promise<string | undefined>((resolve, reject) => {
const server = http.createServer((req, res) => {
try {
resolve(req.headers.referer);
} catch (e) {
reject(e);
} finally {
res.end();
server.close();
}
});
listen(server).then(({ url }) => {
loadWebView(w, {
httpreferrer: referrer,
src: url
});
});
});
expect(received).to.equal(referrer);
});
});
describe('useragent attribute', () => {
it('sets the user agent', async () => {
const referrer = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko';
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/useragent.html`,
useragent: referrer
});
expect(message).to.equal(referrer);
});
});
describe('disablewebsecurity attribute', () => {
it('does not disable web security when not set', async () => {
await loadWebView(w, { src: 'about:blank' });
const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`);
expect(result).to.equal('failed');
});
it('disables web security when set', async () => {
await loadWebView(w, { src: 'about:blank', disablewebsecurity: '' });
const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`);
expect(result).to.equal('ok');
});
it('does not break node integration', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
disablewebsecurity: '',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/d.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('does not break preload script', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
disablewebsecurity: '',
preload: `${fixtures}/module/preload.js`,
webpreferences: 'sandbox=no',
src: `file://${fixtures}/pages/e.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object',
Buffer: 'function'
});
});
});
describe('partition attribute', () => {
it('inserts no node symbols when not set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
partition: 'test1',
src: `file://${fixtures}/pages/c.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'undefined',
module: 'undefined',
process: 'undefined',
global: 'undefined'
});
});
it('inserts node symbols when set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'on',
partition: 'test2',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/d.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('isolates storage for different id', async () => {
await w.executeJavaScript('localStorage.setItem(\'test\', \'one\')');
const message = await loadWebViewAndWaitForMessage(w, {
partition: 'test3',
src: `file://${fixtures}/pages/partition/one.html`
});
const parsedMessage = JSON.parse(message);
expect(parsedMessage).to.include({
numberOfEntries: 0,
testValue: null
});
});
it('uses current session storage when no id is provided', async () => {
await w.executeJavaScript('localStorage.setItem(\'test\', \'two\')');
const testValue = 'two';
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/partition/one.html`
});
const parsedMessage = JSON.parse(message);
expect(parsedMessage).to.include({
testValue
});
});
});
describe('allowpopups attribute', () => {
const generateSpecs = (description: string, webpreferences = '') => {
describe(description, () => {
it('can not open new window when not set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
webpreferences,
src: `file://${fixtures}/pages/window-open-hide.html`
});
expect(message).to.equal('null');
});
it('can open new window when set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
webpreferences,
allowpopups: 'on',
src: `file://${fixtures}/pages/window-open-hide.html`
});
expect(message).to.equal('window');
});
});
};
generateSpecs('without sandbox');
generateSpecs('with sandbox', 'sandbox=yes');
});
describe('webpreferences attribute', () => {
it('can enable nodeintegration', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/d.html`,
webpreferences: 'nodeIntegration,contextIsolation=no'
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('can disable web security and enable nodeintegration', async () => {
await loadWebView(w, { src: 'about:blank', webpreferences: 'webSecurity=no, nodeIntegration=yes, contextIsolation=no' });
const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`);
expect(result).to.equal('ok');
const type = await w.executeJavaScript('webview.executeJavaScript("typeof require")');
expect(type).to.equal('function');
});
});
});
describe('events', () => {
useRemoteContext({ webPreferences: { webviewTag: true } });
let w: WebContents;
before(async () => {
const window = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
await window.loadURL(`file://${fixtures}/pages/blank.html`);
w = window.webContents;
});
afterEach(async () => {
await w.executeJavaScript(`{
for (const el of document.querySelectorAll('webview')) el.remove();
}`);
});
after(closeAllWindows);
describe('ipc-message event', () => {
it('emits when guest sends an ipc message to browser', async () => {
const { frameId, channel, args } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/ipc-message.html`,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
}, 'ipc-message');
expect(frameId).to.be.an('array').that.has.lengthOf(2);
expect(channel).to.equal('channel');
expect(args).to.deep.equal(['arg1', 'arg2']);
});
});
describe('page-title-updated event', () => {
it('emits when title is set', async () => {
const { title, explicitSet } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/a.html`
}, 'page-title-updated');
expect(title).to.equal('test');
expect(explicitSet).to.be.true();
});
});
describe('page-favicon-updated event', () => {
it('emits when favicon urls are received', async () => {
const { favicons } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/a.html`
}, 'page-favicon-updated');
expect(favicons).to.be.an('array').of.length(2);
if (process.platform === 'win32') {
expect(favicons[0]).to.match(/^file:\/\/\/[A-Z]:\/favicon.png$/i);
} else {
expect(favicons[0]).to.equal('file:///favicon.png');
}
});
});
describe('did-redirect-navigation event', () => {
it('is emitted on redirects', async () => {
const server = http.createServer((req, res) => {
if (req.url === '/302') {
res.setHeader('Location', '/200');
res.statusCode = 302;
res.end();
} else {
res.end();
}
});
const { url } = await listen(server);
defer(() => { server.close(); });
const event = await loadWebViewAndWaitForEvent(w, {
src: `${url}/302`
}, 'did-redirect-navigation');
expect(event.url).to.equal(`${url}/200`);
expect(event.isInPlace).to.be.false();
expect(event.isMainFrame).to.be.true();
expect(event.frameProcessId).to.be.a('number');
expect(event.frameRoutingId).to.be.a('number');
});
});
describe('will-navigate event', () => {
it('emits when a url that leads to outside of the page is loaded', async () => {
const { url } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/webview-will-navigate.html`
}, 'will-navigate');
expect(url).to.equal('http://host/');
});
});
describe('will-frame-navigate event', () => {
it('emits when a link that leads to outside of the page is loaded', async () => {
const { url, isMainFrame } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/webview-will-navigate.html`
}, 'will-frame-navigate');
expect(url).to.equal('http://host/');
expect(isMainFrame).to.be.true();
});
it('emits when a link within an iframe, which leads to outside of the page, is loaded', async () => {
await loadWebView(w, {
src: `file://${fixtures}/pages/webview-will-navigate-in-frame.html`,
nodeIntegration: ''
});
const { url, frameProcessId, frameRoutingId } = await w.executeJavaScript(`
new Promise((resolve, reject) => {
let hasFrameNavigatedOnce = false;
const webview = document.getElementById('webview');
webview.addEventListener('will-frame-navigate', ({url, isMainFrame, frameProcessId, frameRoutingId}) => {
if (isMainFrame) return;
if (hasFrameNavigatedOnce) resolve({
url,
isMainFrame,
frameProcessId,
frameRoutingId,
});
// First navigation is the initial iframe load within the <webview>
hasFrameNavigatedOnce = true;
});
webview.executeJavaScript('loadSubframe()');
});
`);
expect(url).to.equal('http://host/');
expect(frameProcessId).to.be.a('number');
expect(frameRoutingId).to.be.a('number');
});
});
describe('did-navigate event', () => {
it('emits when a url that leads to outside of the page is clicked', async () => {
const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-will-navigate.html')).toString();
const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate');
expect(event.url).to.equal(pageUrl);
});
});
describe('did-navigate-in-page event', () => {
it('emits when an anchor link is clicked', async () => {
const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-did-navigate-in-page.html')).toString();
const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate-in-page');
expect(event.url).to.equal(`${pageUrl}#test_content`);
});
it('emits when window.history.replaceState is called', async () => {
const { url } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/webview-did-navigate-in-page-with-history.html`
}, 'did-navigate-in-page');
expect(url).to.equal('http://host/');
});
it('emits when window.location.hash is changed', async () => {
const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-did-navigate-in-page-with-hash.html')).toString();
const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate-in-page');
expect(event.url).to.equal(`${pageUrl}#test`);
});
});
describe('close event', () => {
it('should fire when interior page calls window.close', async () => {
await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/close.html` }, 'close');
});
});
describe('devtools-opened event', () => {
it('should fire when webview.openDevTools() is called', async () => {
await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/base-page.html`
}, 'dom-ready');
await w.executeJavaScript(`new Promise((resolve) => {
webview.openDevTools()
webview.addEventListener('devtools-opened', () => resolve(), {once: true})
})`);
await w.executeJavaScript('webview.closeDevTools()');
});
});
describe('devtools-closed event', () => {
itremote('should fire when webview.closeDevTools() is called', async (fixtures: string) => {
const webview = new WebView();
webview.src = `file://${fixtures}/pages/base-page.html`;
document.body.appendChild(webview);
await new Promise(resolve => webview.addEventListener('dom-ready', resolve, { once: true }));
webview.openDevTools();
await new Promise(resolve => webview.addEventListener('devtools-opened', resolve, { once: true }));
webview.closeDevTools();
await new Promise(resolve => webview.addEventListener('devtools-closed', resolve, { once: true }));
}, [fixtures]);
});
describe('devtools-focused event', () => {
itremote('should fire when webview.openDevTools() is called', async (fixtures: string) => {
const webview = new WebView();
webview.src = `file://${fixtures}/pages/base-page.html`;
document.body.appendChild(webview);
const waitForDevToolsFocused = new Promise(resolve => webview.addEventListener('devtools-focused', resolve, { once: true }));
await new Promise(resolve => webview.addEventListener('dom-ready', resolve, { once: true }));
webview.openDevTools();
await waitForDevToolsFocused;
webview.closeDevTools();
}, [fixtures]);
});
describe('dom-ready event', () => {
it('emits when document is loaded', async () => {
const server = http.createServer(() => {});
const { port } = await listen(server);
await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/dom-ready.html?port=${port}`
}, 'dom-ready');
});
itremote('throws a custom error when an API method is called before the event is emitted', () => {
const expectedErrorMessage =
'The WebView must be attached to the DOM ' +
'and the dom-ready event emitted before this method can be called.';
const webview = new WebView();
expect(() => { webview.stop(); }).to.throw(expectedErrorMessage);
});
});
describe('context-menu event', () => {
it('emits when right-clicked in page', async () => {
await loadWebView(w, { src: 'about:blank' });
const { params, url } = await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('context-menu', (e) => resolve({...e, url: webview.getURL() }), {once: true})
// Simulate right-click to create context-menu event.
const opts = { x: 0, y: 0, button: 'right' };
webview.sendInputEvent({ ...opts, type: 'mouseDown' });
webview.sendInputEvent({ ...opts, type: 'mouseUp' });
})`);
expect(params.pageURL).to.equal(url);
expect(params.frame).to.be.undefined();
expect(params.x).to.be.a('number');
expect(params.y).to.be.a('number');
});
});
describe('found-in-page event', () => {
itremote('emits when a request is made', async (fixtures: string) => {
const webview = new WebView();
const didFinishLoad = new Promise(resolve => webview.addEventListener('did-finish-load', resolve, { once: true }));
webview.src = `file://${fixtures}/pages/content.html`;
document.body.appendChild(webview);
// TODO(deepak1556): With https://codereview.chromium.org/2836973002
// focus of the webContents is required when triggering the api.
// Remove this workaround after determining the cause for
// incorrect focus.
webview.focus();
await didFinishLoad;
const activeMatchOrdinal = [];
for (;;) {
const foundInPage = new Promise<any>(resolve => webview.addEventListener('found-in-page', resolve, { once: true }));
const requestId = webview.findInPage('virtual');
const event = await foundInPage;
expect(event.result.requestId).to.equal(requestId);
expect(event.result.matches).to.equal(3);
activeMatchOrdinal.push(event.result.activeMatchOrdinal);
if (event.result.activeMatchOrdinal === event.result.matches) {
break;
}
}
expect(activeMatchOrdinal).to.deep.equal([1, 2, 3]);
webview.stopFindInPage('clearSelection');
}, [fixtures]);
});
describe('will-attach-webview event', () => {
itremote('does not emit when src is not changed', async () => {
const webview = new WebView();
document.body.appendChild(webview);
await setTimeout();
const expectedErrorMessage = 'The WebView must be attached to the DOM and the dom-ready event emitted before this method can be called.';
expect(() => { webview.stop(); }).to.throw(expectedErrorMessage);
});
it('supports changing the web preferences', async () => {
w.once('will-attach-webview', (event, webPreferences, params) => {
params.src = `file://${path.join(fixtures, 'pages', 'c.html')}`;
webPreferences.nodeIntegration = false;
});
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'yes',
src: `file://${fixtures}/pages/a.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'undefined',
module: 'undefined',
process: 'undefined',
global: 'undefined'
});
});
it('handler modifying params.instanceId does not break <webview>', async () => {
w.once('will-attach-webview', (event, webPreferences, params) => {
params.instanceId = null as any;
});
await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/a.html`
});
});
it('supports preventing a webview from being created', async () => {
w.once('will-attach-webview', event => event.preventDefault());
await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/c.html`
}, 'destroyed');
});
it('supports removing the preload script', async () => {
w.once('will-attach-webview', (event, webPreferences, params) => {
params.src = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-stripped-preload.html')).toString();
delete webPreferences.preload;
});
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'yes',
preload: path.join(fixtures, 'module', 'preload-set-global.js'),
src: `file://${fixtures}/pages/a.html`
});
expect(message).to.equal('undefined');
});
});
describe('media-started-playing and media-paused events', () => {
it('emits when audio starts and stops playing', async function () {
if (!await w.executeJavaScript('document.createElement(\'audio\').canPlayType(\'audio/wav\')')) {
return this.skip();
}
await loadWebView(w, { src: blankPageUrl });
// With the new autoplay policy, audio elements must be unmuted
// see https://goo.gl/xX8pDD.
await w.executeJavaScript(`new Promise(resolve => {
webview.executeJavaScript(\`
const audio = document.createElement("audio")
audio.src = "../assets/tone.wav"
document.body.appendChild(audio);
audio.play()
\`, true)
webview.addEventListener('media-started-playing', () => resolve(), {once: true})
})`);
await w.executeJavaScript(`new Promise(resolve => {
webview.executeJavaScript(\`
document.querySelector("audio").pause()
\`, true)
webview.addEventListener('media-paused', () => resolve(), {once: true})
})`);
});
});
});
describe('methods', () => {
let w: WebContents;
before(async () => {
const window = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
await window.loadURL(`file://${fixtures}/pages/blank.html`);
w = window.webContents;
});
afterEach(async () => {
await w.executeJavaScript(`{
for (const el of document.querySelectorAll('webview')) el.remove();
}`);
});
after(closeAllWindows);
describe('<webview>.reload()', () => {
it('should emit beforeunload handler', async () => {
await loadWebView(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/beforeunload-false.html`
});
// Event handler has to be added before reload.
const channel = await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('ipc-message', e => resolve(e.channel))
webview.reload();
})`);
expect(channel).to.equal('onbeforeunload');
});
});
describe('<webview>.goForward()', () => {
useRemoteContext({ webPreferences: { webviewTag: true } });
itremote('should work after a replaced history entry', async (fixtures: string) => {
function waitForEvent (target: EventTarget, event: string) {
return new Promise<any>(resolve => target.addEventListener(event, resolve, { once: true }));
}
function waitForEvents (target: EventTarget, ...events: string[]) {
return Promise.all(events.map(event => waitForEvent(webview, event)));
}
const webview = new WebView();
webview.setAttribute('nodeintegration', 'on');
webview.setAttribute('webpreferences', 'contextIsolation=no');
webview.src = `file://${fixtures}/pages/history-replace.html`;
document.body.appendChild(webview);
{
const [e] = await waitForEvents(webview, 'ipc-message', 'did-stop-loading');
expect(e.channel).to.equal('history');
expect(e.args[0]).to.equal(1);
expect(webview.canGoBack()).to.be.false();
expect(webview.canGoForward()).to.be.false();
}
webview.src = `file://${fixtures}/pages/base-page.html`;
await new Promise<void>(resolve => webview.addEventListener('did-stop-loading', resolve, { once: true }));
expect(webview.canGoBack()).to.be.true();
expect(webview.canGoForward()).to.be.false();
webview.goBack();
{
const [e] = await waitForEvents(webview, 'ipc-message', 'did-stop-loading');
expect(e.channel).to.equal('history');
expect(e.args[0]).to.equal(2);
expect(webview.canGoBack()).to.be.false();
expect(webview.canGoForward()).to.be.true();
}
webview.goForward();
await new Promise<void>(resolve => webview.addEventListener('did-stop-loading', resolve, { once: true }));
expect(webview.canGoBack()).to.be.true();
expect(webview.canGoForward()).to.be.false();
}, [fixtures]);
});
describe('<webview>.clearHistory()', () => {
it('should clear the navigation history', async () => {
await loadWebView(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: blankPageUrl
});
// Navigation must be triggered by a user gesture to make canGoBack() return true
await w.executeJavaScript('webview.executeJavaScript(`history.pushState(null, "", "foo.html")`, true)');
expect(await w.executeJavaScript('webview.canGoBack()')).to.be.true();
await w.executeJavaScript('webview.clearHistory()');
expect(await w.executeJavaScript('webview.canGoBack()')).to.be.false();
});
});
describe('executeJavaScript', () => {
it('can return the result of the executed script', async () => {
await loadWebView(w, {
src: 'about:blank'
});
const jsScript = "'4'+2";
const expectedResult = '42';
const result = await w.executeJavaScript(`webview.executeJavaScript(${JSON.stringify(jsScript)})`);
expect(result).to.equal(expectedResult);
});
});
it('supports inserting CSS', async () => {
await loadWebView(w, { src: `file://${fixtures}/pages/base-page.html` });
await w.executeJavaScript('webview.insertCSS(\'body { background-repeat: round; }\')');
const result = await w.executeJavaScript('webview.executeJavaScript(\'window.getComputedStyle(document.body).getPropertyValue("background-repeat")\')');
expect(result).to.equal('round');
});
it('supports removing inserted CSS', async () => {
await loadWebView(w, { src: `file://${fixtures}/pages/base-page.html` });
const key = await w.executeJavaScript('webview.insertCSS(\'body { background-repeat: round; }\')');
await w.executeJavaScript(`webview.removeInsertedCSS(${JSON.stringify(key)})`);
const result = await w.executeJavaScript('webview.executeJavaScript(\'window.getComputedStyle(document.body).getPropertyValue("background-repeat")\')');
expect(result).to.equal('repeat');
});
describe('sendInputEvent', () => {
it('can send keyboard event', async () => {
await loadWebViewAndWaitForEvent(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/onkeyup.html`
}, 'dom-ready');
const waitForIpcMessage = w.executeJavaScript('new Promise(resolve => webview.addEventListener("ipc-message", e => resolve({...e})), {once: true})');
w.executeJavaScript(`webview.sendInputEvent({
type: 'keyup',
keyCode: 'c',
modifiers: ['shift']
})`);
const { channel, args } = await waitForIpcMessage;
expect(channel).to.equal('keyup');
expect(args).to.deep.equal(['C', 'KeyC', 67, true, false]);
});
it('can send mouse event', async () => {
await loadWebViewAndWaitForEvent(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/onmouseup.html`
}, 'dom-ready');
const waitForIpcMessage = w.executeJavaScript('new Promise(resolve => webview.addEventListener("ipc-message", e => resolve({...e})), {once: true})');
w.executeJavaScript(`webview.sendInputEvent({
type: 'mouseup',
modifiers: ['ctrl'],
x: 10,
y: 20
})`);
const { channel, args } = await waitForIpcMessage;
expect(channel).to.equal('mouseup');
expect(args).to.deep.equal([10, 20, false, true]);
});
});
describe('<webview>.getWebContentsId', () => {
it('can return the WebContents ID', async () => {
await loadWebView(w, { src: 'about:blank' });
expect(await w.executeJavaScript('webview.getWebContentsId()')).to.be.a('number');
});
});
ifdescribe(features.isPrintingEnabled())('<webview>.printToPDF()', () => {
it('rejects on incorrectly typed parameters', async () => {
const badTypes = {
landscape: [],
displayHeaderFooter: '123',
printBackground: 2,
scale: 'not-a-number',
pageSize: 'IAmAPageSize',
margins: 'terrible',
pageRanges: { oops: 'im-not-the-right-key' },
headerTemplate: [1, 2, 3],
footerTemplate: [4, 5, 6],
preferCSSPageSize: 'no'
};
// These will hard crash in Chromium unless we type-check
for (const [key, value] of Object.entries(badTypes)) {
const param = { [key]: value };
const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
await loadWebView(w, { src });
await expect(w.executeJavaScript(`webview.printToPDF(${JSON.stringify(param)})`)).to.eventually.be.rejected();
}
});
it('can print to PDF', async () => {
const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
await loadWebView(w, { src });
const data = await w.executeJavaScript('webview.printToPDF({})');
expect(data).to.be.an.instanceof(Uint8Array).that.is.not.empty();
});
});
describe('DOM events', () => {
for (const [description, sandbox] of [
['without sandbox', false] as const,
['with sandbox', true] as const
]) {
describe(description, () => {
it('emits focus event', async () => {
await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/a.html`,
webpreferences: `sandbox=${sandbox ? 'yes' : 'no'}`
}, 'dom-ready');
// If this test fails, check if webview.focus() still works.
await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('focus', () => resolve(), {once: true});
webview.focus();
})`);
});
});
}
});
// TODO(miniak): figure out why this is failing on windows
ifdescribe(process.platform !== 'win32')('<webview>.capturePage()', () => {
it('returns a Promise with a NativeImage', async () => {
const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
await loadWebViewAndWaitForEvent(w, { src }, 'did-stop-loading');
// Retry a few times due to flake.
for (let i = 0; i < 5; i++) {
try {
const image = await w.executeJavaScript('webview.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);
return;
} catch {
/* drop the error */
}
}
expect(false).to.be.true('could not successfully capture the page');
});
});
// FIXME(zcbenz): Disabled because of moving to OOPIF webview.
xdescribe('setDevToolsWebContents() API', () => {
/*
it('sets webContents of webview as devtools', async () => {
const webview2 = new WebView();
loadWebView(webview2);
// Setup an event handler for further usage.
const waitForDomReady = waitForEvent(webview2, 'dom-ready');
loadWebView(webview, { src: 'about:blank' });
await waitForEvent(webview, 'dom-ready');
webview.getWebContents().setDevToolsWebContents(webview2.getWebContents());
webview.getWebContents().openDevTools();
await waitForDomReady;
// Its WebContents should be a DevTools.
const devtools = webview2.getWebContents();
expect(devtools.getURL().startsWith('devtools://devtools')).to.be.true();
const name = await devtools.executeJavaScript('InspectorFrontendHost.constructor.name');
document.body.removeChild(webview2);
expect(name).to.be.equal('InspectorFrontendHostImpl');
});
*/
});
});
describe('basic auth', () => {
let w: WebContents;
before(async () => {
const window = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
await window.loadURL(`file://${fixtures}/pages/blank.html`);
w = window.webContents;
});
afterEach(async () => {
await w.executeJavaScript(`{
for (const el of document.querySelectorAll('webview')) el.remove();
}`);
});
after(closeAllWindows);
it('should authenticate with correct credentials', async () => {
const message = 'Authenticated';
const server = http.createServer((req, res) => {
const credentials = auth(req)!;
if (credentials.name === 'test' && credentials.pass === 'test') {
res.end(message);
} else {
res.end('failed');
}
});
defer(() => {
server.close();
});
const { port } = await listen(server);
const e = await loadWebViewAndWaitForEvent(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/basic-auth.html?port=${port}`
}, 'ipc-message');
expect(e.channel).to.equal(message);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 39,891 |
[Bug]: NativeImage methods returned by capturePage fail with "Error: Illegal invocation"
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Ubuntu
### Operating System Version
Ubuntu 23.04
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
While calling `<webview-tag>.capturePage()` from renderer process, we should be able to run methods from the returned NativeImage (like `.getSize()`)
### Actual Behavior
While calling `<webview-tag>.capturePage()` from a renderer process, all of the NativeImage methods return the following error. In this example we call `.getSize()`:
```
Uncaught (in promise) Error: Illegal invocation: Function must be called on an object of type NativeImage
```
**Code snippet**
```js
const webviewElement = document.getElementById("webview")
webviewElement.capturePage()
.then((image) => console.log(image.getSize()))
```
**To reproduce**
**1.** Create a webview element in a page (BrowserView) and make set the id-attribute to `webview`
**2.** Execute the snippet above
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39891
|
https://github.com/electron/electron/pull/39978
|
5b105f911f7aa134ee44558fefaf171360d3d9d2
|
fd2861117e04a3c62bfab67a1b50cb9c3a55cd4d
| 2023-09-18T10:48:18Z |
c++
| 2023-10-18T14:21:42Z |
shell/renderer/api/electron_api_context_bridge.cc
|
// Copyright (c) 2019 Slack Technologies, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/renderer/api/electron_api_context_bridge.h"
#include <memory>
#include <set>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "base/containers/contains.h"
#include "base/feature_list.h"
#include "base/no_destructor.h"
#include "base/strings/string_number_conversions.h"
#include "base/trace_event/trace_event.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_frame_observer.h"
#include "shell/common/api/object_life_monitor.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/node_includes.h"
#include "shell/common/world_ids.h"
#include "third_party/blink/public/web/web_blob.h"
#include "third_party/blink/public/web/web_element.h"
#include "third_party/blink/public/web/web_local_frame.h"
namespace features {
const base::Feature kContextBridgeMutability{"ContextBridgeMutability",
base::FEATURE_DISABLED_BY_DEFAULT};
}
namespace electron {
content::RenderFrame* GetRenderFrame(v8::Local<v8::Object> value);
namespace api {
namespace context_bridge {
const char kProxyFunctionPrivateKey[] = "electron_contextBridge_proxy_fn";
const char kSupportsDynamicPropertiesPrivateKey[] =
"electron_contextBridge_supportsDynamicProperties";
const char kOriginalFunctionPrivateKey[] = "electron_contextBridge_original_fn";
} // namespace context_bridge
namespace {
static int kMaxRecursion = 1000;
// Returns true if |maybe| is both a value, and that value is true.
inline bool IsTrue(v8::Maybe<bool> maybe) {
return maybe.IsJust() && maybe.FromJust();
}
// Sourced from "extensions/renderer/v8_schema_registry.cc"
// Recursively freezes every v8 object on |object|.
bool DeepFreeze(const v8::Local<v8::Object>& object,
const v8::Local<v8::Context>& context,
std::set<int> frozen = std::set<int>()) {
int hash = object->GetIdentityHash();
if (base::Contains(frozen, hash))
return true;
frozen.insert(hash);
v8::Local<v8::Array> property_names =
object->GetOwnPropertyNames(context).ToLocalChecked();
for (uint32_t i = 0; i < property_names->Length(); ++i) {
v8::Local<v8::Value> child =
object->Get(context, property_names->Get(context, i).ToLocalChecked())
.ToLocalChecked();
if (child->IsObject() && !child->IsTypedArray()) {
if (!DeepFreeze(child.As<v8::Object>(), context, frozen))
return false;
}
}
return IsTrue(
object->SetIntegrityLevel(context, v8::IntegrityLevel::kFrozen));
}
bool IsPlainObject(const v8::Local<v8::Value>& object) {
if (!object->IsObject())
return false;
return !(object->IsNullOrUndefined() || object->IsDate() ||
object->IsArgumentsObject() || object->IsBigIntObject() ||
object->IsBooleanObject() || object->IsNumberObject() ||
object->IsStringObject() || object->IsSymbolObject() ||
object->IsNativeError() || object->IsRegExp() ||
object->IsPromise() || object->IsMap() || object->IsSet() ||
object->IsMapIterator() || object->IsSetIterator() ||
object->IsWeakMap() || object->IsWeakSet() ||
object->IsArrayBuffer() || object->IsArrayBufferView() ||
object->IsArray() || object->IsDataView() ||
object->IsSharedArrayBuffer() || object->IsGeneratorObject() ||
object->IsWasmModuleObject() || object->IsWasmMemoryObject() ||
object->IsModuleNamespaceObject() || object->IsProxy());
}
bool IsPlainArray(const v8::Local<v8::Value>& arr) {
if (!arr->IsArray())
return false;
return !arr->IsTypedArray();
}
void SetPrivate(v8::Local<v8::Context> context,
v8::Local<v8::Object> target,
const std::string& key,
v8::Local<v8::Value> value) {
target
->SetPrivate(
context,
v8::Private::ForApi(context->GetIsolate(),
gin::StringToV8(context->GetIsolate(), key)),
value)
.Check();
}
v8::MaybeLocal<v8::Value> GetPrivate(v8::Local<v8::Context> context,
v8::Local<v8::Object> target,
const std::string& key) {
return target->GetPrivate(
context,
v8::Private::ForApi(context->GetIsolate(),
gin::StringToV8(context->GetIsolate(), key)));
}
} // namespace
v8::MaybeLocal<v8::Value> PassValueToOtherContext(
v8::Local<v8::Context> source_context,
v8::Local<v8::Context> destination_context,
v8::Local<v8::Value> value,
context_bridge::ObjectCache* object_cache,
bool support_dynamic_properties,
int recursion_depth,
BridgeErrorTarget error_target) {
TRACE_EVENT0("electron", "ContextBridge::PassValueToOtherContext");
if (recursion_depth >= kMaxRecursion) {
v8::Context::Scope error_scope(error_target == BridgeErrorTarget::kSource
? source_context
: destination_context);
source_context->GetIsolate()->ThrowException(v8::Exception::TypeError(
gin::StringToV8(source_context->GetIsolate(),
"Electron contextBridge recursion depth exceeded. "
"Nested objects "
"deeper than 1000 are not supported.")));
return v8::MaybeLocal<v8::Value>();
}
// Certain primitives always use the current contexts prototype and we can
// pass these through directly which is significantly more performant than
// copying them. This list of primitives is based on the classification of
// "primitive value" as defined in the ECMA262 spec
// https://tc39.es/ecma262/#sec-primitive-value
if (value->IsString() || value->IsNumber() || value->IsNullOrUndefined() ||
value->IsBoolean() || value->IsSymbol() || value->IsBigInt()) {
return v8::MaybeLocal<v8::Value>(value);
}
// Check Cache
auto cached_value = object_cache->GetCachedProxiedObject(value);
if (!cached_value.IsEmpty()) {
return cached_value;
}
// Proxy functions and monitor the lifetime in the new context to release
// the global handle at the right time.
if (value->IsFunction()) {
auto func = value.As<v8::Function>();
v8::MaybeLocal<v8::Value> maybe_original_fn = GetPrivate(
source_context, func, context_bridge::kOriginalFunctionPrivateKey);
{
v8::Context::Scope destination_scope(destination_context);
v8::Local<v8::Value> proxy_func;
// If this function has already been sent over the bridge,
// then it is being sent _back_ over the bridge and we can
// simply return the original method here for performance reasons
// For safety reasons we check if the destination context is the
// creation context of the original method. If it's not we proceed
// with the proxy logic
if (maybe_original_fn.ToLocal(&proxy_func) && proxy_func->IsFunction() &&
proxy_func.As<v8::Object>()->GetCreationContextChecked() ==
destination_context) {
return v8::MaybeLocal<v8::Value>(proxy_func);
}
v8::Local<v8::Object> state =
v8::Object::New(destination_context->GetIsolate());
SetPrivate(destination_context, state,
context_bridge::kProxyFunctionPrivateKey, func);
SetPrivate(destination_context, state,
context_bridge::kSupportsDynamicPropertiesPrivateKey,
gin::ConvertToV8(destination_context->GetIsolate(),
support_dynamic_properties));
if (!v8::Function::New(destination_context, ProxyFunctionWrapper, state)
.ToLocal(&proxy_func))
return v8::MaybeLocal<v8::Value>();
SetPrivate(destination_context, proxy_func.As<v8::Object>(),
context_bridge::kOriginalFunctionPrivateKey, func);
object_cache->CacheProxiedObject(value, proxy_func);
return v8::MaybeLocal<v8::Value>(proxy_func);
}
}
// Proxy promises as they have a safe and guaranteed memory lifecycle
if (value->IsPromise()) {
v8::Context::Scope destination_scope(destination_context);
auto source_promise = value.As<v8::Promise>();
// Make the promise a shared_ptr so that when the original promise is
// freed the proxy promise is correctly freed as well instead of being
// left dangling
auto proxied_promise =
std::make_shared<gin_helper::Promise<v8::Local<v8::Value>>>(
destination_context->GetIsolate());
v8::Local<v8::Promise> proxied_promise_handle =
proxied_promise->GetHandle();
v8::Global<v8::Context> global_then_source_context(
source_context->GetIsolate(), source_context);
v8::Global<v8::Context> global_then_destination_context(
destination_context->GetIsolate(), destination_context);
global_then_source_context.SetWeak();
global_then_destination_context.SetWeak();
auto then_cb = base::BindOnce(
[](std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>>
proxied_promise,
v8::Isolate* isolate, v8::Global<v8::Context> global_source_context,
v8::Global<v8::Context> global_destination_context,
v8::Local<v8::Value> result) {
if (global_source_context.IsEmpty() ||
global_destination_context.IsEmpty())
return;
context_bridge::ObjectCache object_cache;
v8::MaybeLocal<v8::Value> val;
{
v8::TryCatch try_catch(isolate);
val = PassValueToOtherContext(
global_source_context.Get(isolate),
global_destination_context.Get(isolate), result, &object_cache,
false, 0, BridgeErrorTarget::kDestination);
if (try_catch.HasCaught()) {
if (try_catch.Message().IsEmpty()) {
proxied_promise->RejectWithErrorMessage(
"An error was thrown while sending a promise result over "
"the context bridge but it was not actually an Error "
"object. This normally means that a promise was resolved "
"with a value that is not supported by the Context "
"Bridge.");
} else {
proxied_promise->Reject(
v8::Exception::Error(try_catch.Message()->Get()));
}
return;
}
}
DCHECK(!val.IsEmpty());
if (!val.IsEmpty())
proxied_promise->Resolve(val.ToLocalChecked());
},
proxied_promise, destination_context->GetIsolate(),
std::move(global_then_source_context),
std::move(global_then_destination_context));
v8::Global<v8::Context> global_catch_source_context(
source_context->GetIsolate(), source_context);
v8::Global<v8::Context> global_catch_destination_context(
destination_context->GetIsolate(), destination_context);
global_catch_source_context.SetWeak();
global_catch_destination_context.SetWeak();
auto catch_cb = base::BindOnce(
[](std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>>
proxied_promise,
v8::Isolate* isolate, v8::Global<v8::Context> global_source_context,
v8::Global<v8::Context> global_destination_context,
v8::Local<v8::Value> result) {
if (global_source_context.IsEmpty() ||
global_destination_context.IsEmpty())
return;
context_bridge::ObjectCache object_cache;
v8::MaybeLocal<v8::Value> val;
{
v8::TryCatch try_catch(isolate);
val = PassValueToOtherContext(
global_source_context.Get(isolate),
global_destination_context.Get(isolate), result, &object_cache,
false, 0, BridgeErrorTarget::kDestination);
if (try_catch.HasCaught()) {
if (try_catch.Message().IsEmpty()) {
proxied_promise->RejectWithErrorMessage(
"An error was thrown while sending a promise rejection "
"over the context bridge but it was not actually an Error "
"object. This normally means that a promise was rejected "
"with a value that is not supported by the Context "
"Bridge.");
} else {
proxied_promise->Reject(
v8::Exception::Error(try_catch.Message()->Get()));
}
return;
}
}
if (!val.IsEmpty())
proxied_promise->Reject(val.ToLocalChecked());
},
proxied_promise, destination_context->GetIsolate(),
std::move(global_catch_source_context),
std::move(global_catch_destination_context));
std::ignore = source_promise->Then(
source_context,
gin::ConvertToV8(destination_context->GetIsolate(), std::move(then_cb))
.As<v8::Function>(),
gin::ConvertToV8(destination_context->GetIsolate(), std::move(catch_cb))
.As<v8::Function>());
object_cache->CacheProxiedObject(value, proxied_promise_handle);
return v8::MaybeLocal<v8::Value>(proxied_promise_handle);
}
// Errors aren't serializable currently, we need to pull the message out and
// re-construct in the destination context
if (value->IsNativeError()) {
v8::Context::Scope destination_context_scope(destination_context);
// We should try to pull "message" straight off of the error as a
// v8::Message includes some pretext that can get duplicated each time it
// crosses the bridge we fallback to the v8::Message approach if we can't
// pull "message" for some reason
v8::MaybeLocal<v8::Value> maybe_message = value.As<v8::Object>()->Get(
source_context,
gin::ConvertToV8(source_context->GetIsolate(), "message"));
v8::Local<v8::Value> message;
if (maybe_message.ToLocal(&message) && message->IsString()) {
return v8::MaybeLocal<v8::Value>(
v8::Exception::Error(message.As<v8::String>()));
}
return v8::MaybeLocal<v8::Value>(v8::Exception::Error(
v8::Exception::CreateMessage(destination_context->GetIsolate(), value)
->Get()));
}
// Manually go through the array and pass each value individually into a new
// array so that functions deep inside arrays get proxied or arrays of
// promises are proxied correctly.
if (IsPlainArray(value)) {
v8::Context::Scope destination_context_scope(destination_context);
v8::Local<v8::Array> arr = value.As<v8::Array>();
size_t length = arr->Length();
v8::Local<v8::Array> cloned_arr =
v8::Array::New(destination_context->GetIsolate(), length);
for (size_t i = 0; i < length; i++) {
auto value_for_array = PassValueToOtherContext(
source_context, destination_context,
arr->Get(source_context, i).ToLocalChecked(), object_cache,
support_dynamic_properties, recursion_depth + 1, error_target);
if (value_for_array.IsEmpty())
return v8::MaybeLocal<v8::Value>();
if (!IsTrue(cloned_arr->Set(destination_context, static_cast<int>(i),
value_for_array.ToLocalChecked()))) {
return v8::MaybeLocal<v8::Value>();
}
}
object_cache->CacheProxiedObject(value, cloned_arr);
return v8::MaybeLocal<v8::Value>(cloned_arr);
}
// Custom logic to "clone" Element references
blink::WebElement elem =
blink::WebElement::FromV8Value(destination_context->GetIsolate(), value);
if (!elem.IsNull()) {
v8::Context::Scope destination_context_scope(destination_context);
return v8::MaybeLocal<v8::Value>(elem.ToV8Value(
destination_context->Global(), destination_context->GetIsolate()));
}
// Custom logic to "clone" Blob references
blink::WebBlob blob =
blink::WebBlob::FromV8Value(destination_context->GetIsolate(), value);
if (!blob.IsNull()) {
v8::Context::Scope destination_context_scope(destination_context);
return v8::MaybeLocal<v8::Value>(
blob.ToV8Value(destination_context->GetIsolate()));
}
// Proxy all objects
if (IsPlainObject(value)) {
auto object_value = value.As<v8::Object>();
auto passed_value = CreateProxyForAPI(
object_value, source_context, destination_context, object_cache,
support_dynamic_properties, recursion_depth + 1, error_target);
if (passed_value.IsEmpty())
return v8::MaybeLocal<v8::Value>();
return v8::MaybeLocal<v8::Value>(passed_value.ToLocalChecked());
}
// Serializable objects
blink::CloneableMessage ret;
{
v8::Local<v8::Context> error_context =
error_target == BridgeErrorTarget::kSource ? source_context
: destination_context;
v8::Context::Scope error_scope(error_context);
// V8 serializer will throw an error if required
if (!gin::ConvertFromV8(error_context->GetIsolate(), value, &ret)) {
return v8::MaybeLocal<v8::Value>();
}
}
{
v8::Context::Scope destination_context_scope(destination_context);
v8::Local<v8::Value> cloned_value =
gin::ConvertToV8(destination_context->GetIsolate(), ret);
object_cache->CacheProxiedObject(value, cloned_value);
return v8::MaybeLocal<v8::Value>(cloned_value);
}
}
void ProxyFunctionWrapper(const v8::FunctionCallbackInfo<v8::Value>& info) {
TRACE_EVENT0("electron", "ContextBridge::ProxyFunctionWrapper");
CHECK(info.Data()->IsObject());
v8::Local<v8::Object> data = info.Data().As<v8::Object>();
bool support_dynamic_properties = false;
gin::Arguments args(info);
// Context the proxy function was called from
v8::Local<v8::Context> calling_context = args.isolate()->GetCurrentContext();
// Pull the original function and its context off of the data private key
v8::MaybeLocal<v8::Value> sdp_value =
GetPrivate(calling_context, data,
context_bridge::kSupportsDynamicPropertiesPrivateKey);
v8::MaybeLocal<v8::Value> maybe_func = GetPrivate(
calling_context, data, context_bridge::kProxyFunctionPrivateKey);
v8::Local<v8::Value> func_value;
if (sdp_value.IsEmpty() || maybe_func.IsEmpty() ||
!gin::ConvertFromV8(args.isolate(), sdp_value.ToLocalChecked(),
&support_dynamic_properties) ||
!maybe_func.ToLocal(&func_value))
return;
v8::Local<v8::Function> func = func_value.As<v8::Function>();
v8::Local<v8::Context> func_owning_context =
func->GetCreationContextChecked();
{
v8::Context::Scope func_owning_context_scope(func_owning_context);
context_bridge::ObjectCache object_cache;
std::vector<v8::Local<v8::Value>> original_args;
std::vector<v8::Local<v8::Value>> proxied_args;
args.GetRemaining(&original_args);
for (auto value : original_args) {
auto arg = PassValueToOtherContext(
calling_context, func_owning_context, value, &object_cache,
support_dynamic_properties, 0, BridgeErrorTarget::kSource);
if (arg.IsEmpty())
return;
proxied_args.push_back(arg.ToLocalChecked());
}
v8::MaybeLocal<v8::Value> maybe_return_value;
bool did_error = false;
v8::Local<v8::Value> error_message;
{
v8::TryCatch try_catch(args.isolate());
maybe_return_value = func->Call(func_owning_context, func,
proxied_args.size(), proxied_args.data());
if (try_catch.HasCaught()) {
did_error = true;
v8::Local<v8::Value> exception = try_catch.Exception();
const char err_msg[] =
"An unknown exception occurred in the isolated context, an error "
"occurred but a valid exception was not thrown.";
if (!exception->IsNull() && exception->IsObject()) {
v8::MaybeLocal<v8::Value> maybe_message =
exception.As<v8::Object>()->Get(
func_owning_context,
gin::ConvertToV8(args.isolate(), "message"));
if (!maybe_message.ToLocal(&error_message) ||
!error_message->IsString()) {
error_message = gin::StringToV8(args.isolate(), err_msg);
}
} else {
error_message = gin::StringToV8(args.isolate(), err_msg);
}
}
}
if (did_error) {
v8::Context::Scope calling_context_scope(calling_context);
args.isolate()->ThrowException(
v8::Exception::Error(error_message.As<v8::String>()));
return;
}
if (maybe_return_value.IsEmpty())
return;
// In the case where we encounted an exception converting the return value
// of the function we need to ensure that the exception / thrown value is
// safely transferred from the function_owning_context (where it was thrown)
// into the calling_context (where it needs to be thrown) To do this we pull
// the message off the exception and later re-throw it in the right context.
// In some cases the caught thing is not an exception i.e. it's technically
// valid to `throw 123`. In these cases to avoid infinite
// PassValueToOtherContext recursion we bail early as being unable to send
// the value from one context to the other.
// TODO(MarshallOfSound): In this case and other cases where the error can't
// be sent _across_ worlds we should probably log it globally in some way to
// allow easier debugging. This is not trivial though so is left to a
// future change.
bool did_error_converting_result = false;
v8::MaybeLocal<v8::Value> ret;
v8::Local<v8::String> exception;
{
v8::TryCatch try_catch(args.isolate());
ret = PassValueToOtherContext(func_owning_context, calling_context,
maybe_return_value.ToLocalChecked(),
&object_cache, support_dynamic_properties,
0, BridgeErrorTarget::kDestination);
if (try_catch.HasCaught()) {
did_error_converting_result = true;
if (!try_catch.Message().IsEmpty()) {
exception = try_catch.Message()->Get();
}
}
}
if (did_error_converting_result) {
v8::Context::Scope calling_context_scope(calling_context);
if (exception.IsEmpty()) {
const char err_msg[] =
"An unknown exception occurred while sending a function return "
"value over the context bridge, an error "
"occurred but a valid exception was not thrown.";
args.isolate()->ThrowException(v8::Exception::Error(
gin::StringToV8(args.isolate(), err_msg).As<v8::String>()));
} else {
args.isolate()->ThrowException(v8::Exception::Error(exception));
}
return;
}
DCHECK(!ret.IsEmpty());
if (ret.IsEmpty())
return;
info.GetReturnValue().Set(ret.ToLocalChecked());
}
}
v8::MaybeLocal<v8::Object> CreateProxyForAPI(
const v8::Local<v8::Object>& api_object,
const v8::Local<v8::Context>& source_context,
const v8::Local<v8::Context>& destination_context,
context_bridge::ObjectCache* object_cache,
bool support_dynamic_properties,
int recursion_depth,
BridgeErrorTarget error_target) {
gin_helper::Dictionary api(source_context->GetIsolate(), api_object);
{
v8::Context::Scope destination_context_scope(destination_context);
auto proxy =
gin_helper::Dictionary::CreateEmpty(destination_context->GetIsolate());
object_cache->CacheProxiedObject(api.GetHandle(), proxy.GetHandle());
auto maybe_keys = api.GetHandle()->GetOwnPropertyNames(
source_context, static_cast<v8::PropertyFilter>(v8::ONLY_ENUMERABLE));
if (maybe_keys.IsEmpty())
return v8::MaybeLocal<v8::Object>(proxy.GetHandle());
auto keys = maybe_keys.ToLocalChecked();
uint32_t length = keys->Length();
for (uint32_t i = 0; i < length; i++) {
v8::Local<v8::Value> key =
keys->Get(destination_context, i).ToLocalChecked();
if (support_dynamic_properties) {
v8::Context::Scope source_context_scope(source_context);
auto maybe_desc = api.GetHandle()->GetOwnPropertyDescriptor(
source_context, key.As<v8::Name>());
v8::Local<v8::Value> desc_value;
if (!maybe_desc.ToLocal(&desc_value) || !desc_value->IsObject())
continue;
gin_helper::Dictionary desc(api.isolate(), desc_value.As<v8::Object>());
if (desc.Has("get") || desc.Has("set")) {
v8::Local<v8::Value> getter;
v8::Local<v8::Value> setter;
desc.Get("get", &getter);
desc.Get("set", &setter);
{
v8::Context::Scope inner_destination_context_scope(
destination_context);
v8::Local<v8::Value> getter_proxy;
v8::Local<v8::Value> setter_proxy;
if (!getter.IsEmpty()) {
if (!PassValueToOtherContext(source_context, destination_context,
getter, object_cache,
support_dynamic_properties, 1,
error_target)
.ToLocal(&getter_proxy))
continue;
}
if (!setter.IsEmpty()) {
if (!PassValueToOtherContext(source_context, destination_context,
setter, object_cache,
support_dynamic_properties, 1,
error_target)
.ToLocal(&setter_proxy))
continue;
}
v8::PropertyDescriptor prop_desc(getter_proxy, setter_proxy);
std::ignore = proxy.GetHandle()->DefineProperty(
destination_context, key.As<v8::Name>(), prop_desc);
}
continue;
}
}
v8::Local<v8::Value> value;
if (!api.Get(key, &value))
continue;
auto passed_value = PassValueToOtherContext(
source_context, destination_context, value, object_cache,
support_dynamic_properties, recursion_depth + 1, error_target);
if (passed_value.IsEmpty())
return v8::MaybeLocal<v8::Object>();
proxy.Set(key, passed_value.ToLocalChecked());
}
return proxy.GetHandle();
}
}
void ExposeAPIInWorld(v8::Isolate* isolate,
const int world_id,
const std::string& key,
v8::Local<v8::Value> api,
gin_helper::Arguments* args) {
TRACE_EVENT2("electron", "ContextBridge::ExposeAPIInWorld", "key", key,
"worldId", world_id);
auto* render_frame = GetRenderFrame(isolate->GetCurrentContext()->Global());
CHECK(render_frame);
auto* frame = render_frame->GetWebFrame();
CHECK(frame);
v8::Local<v8::Context> target_context =
world_id == WorldIDs::MAIN_WORLD_ID
? frame->MainWorldScriptContext()
: frame->GetScriptContextFromWorldId(isolate, world_id);
gin_helper::Dictionary global(target_context->GetIsolate(),
target_context->Global());
if (global.Has(key)) {
args->ThrowError(
"Cannot bind an API on top of an existing property on the window "
"object");
return;
}
v8::Local<v8::Context> electron_isolated_context =
frame->GetScriptContextFromWorldId(args->isolate(),
WorldIDs::ISOLATED_WORLD_ID);
{
context_bridge::ObjectCache object_cache;
v8::Context::Scope target_context_scope(target_context);
v8::MaybeLocal<v8::Value> maybe_proxy = PassValueToOtherContext(
electron_isolated_context, target_context, api, &object_cache, false, 0,
BridgeErrorTarget::kSource);
if (maybe_proxy.IsEmpty())
return;
auto proxy = maybe_proxy.ToLocalChecked();
if (base::FeatureList::IsEnabled(features::kContextBridgeMutability)) {
global.Set(key, proxy);
return;
}
if (proxy->IsObject() && !proxy->IsTypedArray() &&
!DeepFreeze(proxy.As<v8::Object>(), target_context))
return;
global.SetReadOnlyNonConfigurable(key, proxy);
}
}
gin_helper::Dictionary TraceKeyPath(const gin_helper::Dictionary& start,
const std::vector<std::string>& key_path) {
gin_helper::Dictionary current = start;
for (size_t i = 0; i < key_path.size() - 1; i++) {
CHECK(current.Get(key_path[i], ¤t));
}
return current;
}
void OverrideGlobalValueFromIsolatedWorld(
const std::vector<std::string>& key_path,
v8::Local<v8::Object> value,
bool support_dynamic_properties) {
if (key_path.empty())
return;
auto* render_frame = GetRenderFrame(value);
CHECK(render_frame);
auto* frame = render_frame->GetWebFrame();
CHECK(frame);
v8::Local<v8::Context> main_context = frame->MainWorldScriptContext();
gin_helper::Dictionary global(main_context->GetIsolate(),
main_context->Global());
const std::string final_key = key_path[key_path.size() - 1];
gin_helper::Dictionary target_object = TraceKeyPath(global, key_path);
{
v8::Context::Scope main_context_scope(main_context);
context_bridge::ObjectCache object_cache;
v8::MaybeLocal<v8::Value> maybe_proxy = PassValueToOtherContext(
value->GetCreationContextChecked(), main_context, value, &object_cache,
support_dynamic_properties, 1, BridgeErrorTarget::kSource);
DCHECK(!maybe_proxy.IsEmpty());
auto proxy = maybe_proxy.ToLocalChecked();
target_object.Set(final_key, proxy);
}
}
bool OverrideGlobalPropertyFromIsolatedWorld(
const std::vector<std::string>& key_path,
v8::Local<v8::Object> getter,
v8::Local<v8::Value> setter,
gin_helper::Arguments* args) {
if (key_path.empty())
return false;
auto* render_frame = GetRenderFrame(getter);
CHECK(render_frame);
auto* frame = render_frame->GetWebFrame();
CHECK(frame);
v8::Local<v8::Context> main_context = frame->MainWorldScriptContext();
gin_helper::Dictionary global(main_context->GetIsolate(),
main_context->Global());
const std::string final_key = key_path[key_path.size() - 1];
v8::Local<v8::Object> target_object =
TraceKeyPath(global, key_path).GetHandle();
{
v8::Context::Scope main_context_scope(main_context);
context_bridge::ObjectCache object_cache;
v8::Local<v8::Value> getter_proxy;
v8::Local<v8::Value> setter_proxy;
if (!getter->IsNullOrUndefined()) {
v8::MaybeLocal<v8::Value> maybe_getter_proxy = PassValueToOtherContext(
getter->GetCreationContextChecked(), main_context, getter,
&object_cache, false, 1, BridgeErrorTarget::kSource);
DCHECK(!maybe_getter_proxy.IsEmpty());
getter_proxy = maybe_getter_proxy.ToLocalChecked();
}
if (!setter->IsNullOrUndefined() && setter->IsObject()) {
v8::MaybeLocal<v8::Value> maybe_setter_proxy = PassValueToOtherContext(
getter->GetCreationContextChecked(), main_context, setter,
&object_cache, false, 1, BridgeErrorTarget::kSource);
DCHECK(!maybe_setter_proxy.IsEmpty());
setter_proxy = maybe_setter_proxy.ToLocalChecked();
}
v8::PropertyDescriptor desc(getter_proxy, setter_proxy);
bool success = IsTrue(target_object->DefineProperty(
main_context, gin::StringToV8(args->isolate(), final_key), desc));
DCHECK(success);
return success;
}
}
bool IsCalledFromMainWorld(v8::Isolate* isolate) {
auto* render_frame = GetRenderFrame(isolate->GetCurrentContext()->Global());
CHECK(render_frame);
auto* frame = render_frame->GetWebFrame();
CHECK(frame);
v8::Local<v8::Context> main_context = frame->MainWorldScriptContext();
return isolate->GetCurrentContext() == main_context;
}
} // namespace api
} // namespace electron
namespace {
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.SetMethod("exposeAPIInWorld", &electron::api::ExposeAPIInWorld);
dict.SetMethod("_overrideGlobalValueFromIsolatedWorld",
&electron::api::OverrideGlobalValueFromIsolatedWorld);
dict.SetMethod("_overrideGlobalPropertyFromIsolatedWorld",
&electron::api::OverrideGlobalPropertyFromIsolatedWorld);
dict.SetMethod("_isCalledFromMainWorld",
&electron::api::IsCalledFromMainWorld);
#if DCHECK_IS_ON()
dict.Set("_isDebug", true);
#endif
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_renderer_context_bridge, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 39,891 |
[Bug]: NativeImage methods returned by capturePage fail with "Error: Illegal invocation"
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Ubuntu
### Operating System Version
Ubuntu 23.04
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
While calling `<webview-tag>.capturePage()` from renderer process, we should be able to run methods from the returned NativeImage (like `.getSize()`)
### Actual Behavior
While calling `<webview-tag>.capturePage()` from a renderer process, all of the NativeImage methods return the following error. In this example we call `.getSize()`:
```
Uncaught (in promise) Error: Illegal invocation: Function must be called on an object of type NativeImage
```
**Code snippet**
```js
const webviewElement = document.getElementById("webview")
webviewElement.capturePage()
.then((image) => console.log(image.getSize()))
```
**To reproduce**
**1.** Create a webview element in a page (BrowserView) and make set the id-attribute to `webview`
**2.** Execute the snippet above
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39891
|
https://github.com/electron/electron/pull/39978
|
5b105f911f7aa134ee44558fefaf171360d3d9d2
|
fd2861117e04a3c62bfab67a1b50cb9c3a55cd4d
| 2023-09-18T10:48:18Z |
c++
| 2023-10-18T14:21:42Z |
shell/renderer/api/electron_api_context_bridge.h
|
// Copyright (c) 2019 Slack Technologies, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_RENDERER_API_ELECTRON_API_CONTEXT_BRIDGE_H_
#define ELECTRON_SHELL_RENDERER_API_ELECTRON_API_CONTEXT_BRIDGE_H_
#include "shell/renderer/api/context_bridge/object_cache.h"
#include "v8/include/v8.h"
namespace gin_helper {
class Arguments;
}
namespace electron::api {
void ProxyFunctionWrapper(const v8::FunctionCallbackInfo<v8::Value>& info);
// Where the context bridge should create the exception it is about to throw
enum class BridgeErrorTarget {
// The source / calling context. This is default and correct 99% of the time,
// the caller / context asking for the conversion will receive the error and
// therefore the error should be made in that context
kSource,
// The destination / target context. This should only be used when the source
// won't catch the error that results from the value it is passing over the
// bridge. This can **only** occur when returning a value from a function as
// we convert the return value after the method has terminated and execution
// has been returned to the caller. In this scenario the error will the be
// catchable in the "destination" context and therefore we create the error
// there.
kDestination
};
v8::MaybeLocal<v8::Value> PassValueToOtherContext(
v8::Local<v8::Context> source_context,
v8::Local<v8::Context> destination_context,
v8::Local<v8::Value> value,
context_bridge::ObjectCache* object_cache,
bool support_dynamic_properties,
int recursion_depth,
BridgeErrorTarget error_target);
v8::MaybeLocal<v8::Object> CreateProxyForAPI(
const v8::Local<v8::Object>& api_object,
const v8::Local<v8::Context>& source_context,
const v8::Local<v8::Context>& destination_context,
context_bridge::ObjectCache* object_cache,
bool support_dynamic_properties,
int recursion_depth,
BridgeErrorTarget error_target);
} // namespace electron::api
#endif // ELECTRON_SHELL_RENDERER_API_ELECTRON_API_CONTEXT_BRIDGE_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 39,891 |
[Bug]: NativeImage methods returned by capturePage fail with "Error: Illegal invocation"
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Ubuntu
### Operating System Version
Ubuntu 23.04
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
While calling `<webview-tag>.capturePage()` from renderer process, we should be able to run methods from the returned NativeImage (like `.getSize()`)
### Actual Behavior
While calling `<webview-tag>.capturePage()` from a renderer process, all of the NativeImage methods return the following error. In this example we call `.getSize()`:
```
Uncaught (in promise) Error: Illegal invocation: Function must be called on an object of type NativeImage
```
**Code snippet**
```js
const webviewElement = document.getElementById("webview")
webviewElement.capturePage()
.then((image) => console.log(image.getSize()))
```
**To reproduce**
**1.** Create a webview element in a page (BrowserView) and make set the id-attribute to `webview`
**2.** Execute the snippet above
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39891
|
https://github.com/electron/electron/pull/39978
|
5b105f911f7aa134ee44558fefaf171360d3d9d2
|
fd2861117e04a3c62bfab67a1b50cb9c3a55cd4d
| 2023-09-18T10:48:18Z |
c++
| 2023-10-18T14:21:42Z |
shell/renderer/api/electron_api_web_frame.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/command_line.h"
#include "base/memory/memory_pressure_listener.h"
#include "base/strings/utf_string_conversions.h"
#include "components/spellcheck/renderer/spellcheck.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_frame_observer.h"
#include "content/public/renderer/render_frame_visitor.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/common/api/api.mojom.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/function_template_extensions.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/renderer/api/context_bridge/object_cache.h"
#include "shell/renderer/api/electron_api_context_bridge.h"
#include "shell/renderer/api/electron_api_spell_check_client.h"
#include "shell/renderer/renderer_client_base.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/common/web_cache/web_cache_resource_type_stats.h"
#include "third_party/blink/public/common/web_preferences/web_preferences.h"
#include "third_party/blink/public/platform/web_cache.h"
#include "third_party/blink/public/platform/web_isolated_world_info.h"
#include "third_party/blink/public/web/web_custom_element.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_element.h"
#include "third_party/blink/public/web/web_frame_widget.h"
#include "third_party/blink/public/web/web_input_method_controller.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_script_execution_callback.h"
#include "third_party/blink/public/web/web_script_source.h"
#include "third_party/blink/public/web/web_view.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h" // nogncheck
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h" // nogncheck
#include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h" // nogncheck
#include "ui/base/ime/ime_text_span.h"
#include "url/url_util.h"
namespace gin {
template <>
struct Converter<blink::WebCssOrigin> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
blink::WebCssOrigin* out) {
std::string css_origin;
if (!ConvertFromV8(isolate, val, &css_origin))
return false;
if (css_origin == "user") {
*out = blink::WebCssOrigin::kUser;
} else if (css_origin == "author") {
*out = blink::WebCssOrigin::kAuthor;
} else {
return false;
}
return true;
}
};
} // namespace gin
namespace electron {
content::RenderFrame* GetRenderFrame(v8::Local<v8::Object> value) {
v8::Local<v8::Context> context = value->GetCreationContextChecked();
if (context.IsEmpty())
return nullptr;
blink::WebLocalFrame* frame = blink::WebLocalFrame::FrameForContext(context);
if (!frame)
return nullptr;
return content::RenderFrame::FromWebFrame(frame);
}
namespace api {
namespace {
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
bool SpellCheckWord(content::RenderFrame* render_frame,
const std::string& word,
std::vector<std::u16string>* optional_suggestions) {
size_t start;
size_t length;
RendererClientBase* client = RendererClientBase::Get();
std::u16string w = base::UTF8ToUTF16(word);
int id = render_frame->GetRoutingID();
return client->GetSpellCheck()->SpellCheckWord(
w.c_str(), 0, word.size(), id, &start, &length, optional_suggestions);
}
#endif
class ScriptExecutionCallback {
public:
// for compatibility with the older version of this, error is after result
using CompletionCallback =
base::OnceCallback<void(const v8::Local<v8::Value>& result,
const v8::Local<v8::Value>& error)>;
explicit ScriptExecutionCallback(
gin_helper::Promise<v8::Local<v8::Value>> promise,
CompletionCallback callback)
: promise_(std::move(promise)), callback_(std::move(callback)) {}
~ScriptExecutionCallback() = default;
// disable copy
ScriptExecutionCallback(const ScriptExecutionCallback&) = delete;
ScriptExecutionCallback& operator=(const ScriptExecutionCallback&) = delete;
void CopyResultToCallingContextAndFinalize(
v8::Isolate* isolate,
const v8::Local<v8::Object>& result) {
v8::MaybeLocal<v8::Value> maybe_result;
bool success = true;
std::string error_message =
"An unknown exception occurred while getting the result of the script";
{
v8::TryCatch try_catch(isolate);
context_bridge::ObjectCache object_cache;
maybe_result = PassValueToOtherContext(
result->GetCreationContextChecked(), promise_.GetContext(), result,
&object_cache, false, 0, BridgeErrorTarget::kSource);
if (maybe_result.IsEmpty() || try_catch.HasCaught()) {
success = false;
}
if (try_catch.HasCaught()) {
auto message = try_catch.Message();
if (!message.IsEmpty()) {
gin::ConvertFromV8(isolate, message->Get(), &error_message);
}
}
}
if (!success) {
// Failed convert so we send undefined everywhere
if (callback_)
std::move(callback_).Run(
v8::Undefined(isolate),
v8::Exception::Error(
v8::String::NewFromUtf8(isolate, error_message.c_str())
.ToLocalChecked()));
promise_.RejectWithErrorMessage(error_message);
} else {
v8::Local<v8::Context> context = promise_.GetContext();
v8::Context::Scope context_scope(context);
v8::Local<v8::Value> cloned_value = maybe_result.ToLocalChecked();
if (callback_)
std::move(callback_).Run(cloned_value, v8::Undefined(isolate));
promise_.Resolve(cloned_value);
}
}
void Completed(const blink::WebVector<v8::Local<v8::Value>>& result) {
v8::Isolate* isolate = promise_.isolate();
if (!result.empty()) {
if (!result[0].IsEmpty()) {
v8::Local<v8::Value> value = result[0];
// Either the result was created in the same world as the caller
// or the result is not an object and therefore does not have a
// prototype chain to protect
bool should_clone_value =
!(value->IsObject() &&
promise_.GetContext() ==
value.As<v8::Object>()->GetCreationContextChecked()) &&
value->IsObject();
if (should_clone_value) {
CopyResultToCallingContextAndFinalize(isolate,
value.As<v8::Object>());
} else {
// Right now only single results per frame is supported.
if (callback_)
std::move(callback_).Run(value, v8::Undefined(isolate));
promise_.Resolve(value);
}
} else {
const char error_message[] =
"Script failed to execute, this normally means an error "
"was thrown. Check the renderer console for the error.";
if (!callback_.is_null()) {
v8::Local<v8::Context> context = promise_.GetContext();
v8::Context::Scope context_scope(context);
std::move(callback_).Run(
v8::Undefined(isolate),
v8::Exception::Error(
v8::String::NewFromUtf8(isolate, error_message)
.ToLocalChecked()));
}
promise_.RejectWithErrorMessage(error_message);
}
} else {
const char error_message[] =
"WebFrame was removed before script could run. This normally means "
"the underlying frame was destroyed";
if (!callback_.is_null()) {
v8::Local<v8::Context> context = promise_.GetContext();
v8::Context::Scope context_scope(context);
std::move(callback_).Run(
v8::Undefined(isolate),
v8::Exception::Error(v8::String::NewFromUtf8(isolate, error_message)
.ToLocalChecked()));
}
promise_.RejectWithErrorMessage(error_message);
}
delete this;
}
private:
gin_helper::Promise<v8::Local<v8::Value>> promise_;
CompletionCallback callback_;
};
class FrameSetSpellChecker : public content::RenderFrameVisitor {
public:
FrameSetSpellChecker(SpellCheckClient* spell_check_client,
content::RenderFrame* main_frame)
: spell_check_client_(spell_check_client), main_frame_(main_frame) {
content::RenderFrame::ForEach(this);
main_frame->GetWebFrame()->SetSpellCheckPanelHostClient(spell_check_client);
}
// disable copy
FrameSetSpellChecker(const FrameSetSpellChecker&) = delete;
FrameSetSpellChecker& operator=(const FrameSetSpellChecker&) = delete;
bool Visit(content::RenderFrame* render_frame) override {
if (render_frame->GetMainRenderFrame() == main_frame_ ||
(render_frame->IsMainFrame() && render_frame == main_frame_)) {
render_frame->GetWebFrame()->SetTextCheckClient(spell_check_client_);
}
return true;
}
private:
SpellCheckClient* spell_check_client_;
content::RenderFrame* main_frame_;
};
class SpellCheckerHolder final : public content::RenderFrameObserver {
public:
// Find existing holder for the |render_frame|.
static SpellCheckerHolder* FromRenderFrame(
content::RenderFrame* render_frame) {
for (auto* holder : instances_) {
if (holder->render_frame() == render_frame)
return holder;
}
return nullptr;
}
SpellCheckerHolder(content::RenderFrame* render_frame,
std::unique_ptr<SpellCheckClient> spell_check_client)
: content::RenderFrameObserver(render_frame),
spell_check_client_(std::move(spell_check_client)) {
DCHECK(!FromRenderFrame(render_frame));
instances_.insert(this);
}
~SpellCheckerHolder() final { instances_.erase(this); }
void UnsetAndDestroy() {
FrameSetSpellChecker set_spell_checker(nullptr, render_frame());
delete this;
}
// RenderFrameObserver implementation.
void OnDestruct() final {
// Since we delete this in WillReleaseScriptContext, this method is unlikely
// to be called, but override anyway since I'm not sure if there are some
// corner cases.
//
// Note that while there are two "delete this", it is totally fine as the
// observer unsubscribes automatically in destructor and the other one won't
// be called.
//
// Also note that we should not call UnsetAndDestroy here, as the render
// frame is going to be destroyed.
delete this;
}
void WillReleaseScriptContext(v8::Local<v8::Context> context,
int world_id) final {
// Unset spell checker when the script context is going to be released, as
// the spell check implementation lives there.
UnsetAndDestroy();
}
private:
static std::set<SpellCheckerHolder*> instances_;
std::unique_ptr<SpellCheckClient> spell_check_client_;
};
} // namespace
class WebFrameRenderer : public gin::Wrappable<WebFrameRenderer>,
public content::RenderFrameObserver {
public:
static gin::WrapperInfo kWrapperInfo;
static gin::Handle<WebFrameRenderer> Create(
v8::Isolate* isolate,
content::RenderFrame* render_frame) {
return gin::CreateHandle(isolate, new WebFrameRenderer(render_frame));
}
explicit WebFrameRenderer(content::RenderFrame* render_frame)
: content::RenderFrameObserver(render_frame) {
DCHECK(render_frame);
}
// gin::Wrappable:
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override {
return gin::Wrappable<WebFrameRenderer>::GetObjectTemplateBuilder(isolate)
.SetMethod("getWebFrameId", &WebFrameRenderer::GetWebFrameId)
.SetMethod("setName", &WebFrameRenderer::SetName)
.SetMethod("setZoomLevel", &WebFrameRenderer::SetZoomLevel)
.SetMethod("getZoomLevel", &WebFrameRenderer::GetZoomLevel)
.SetMethod("setZoomFactor", &WebFrameRenderer::SetZoomFactor)
.SetMethod("getZoomFactor", &WebFrameRenderer::GetZoomFactor)
.SetMethod("getWebPreference", &WebFrameRenderer::GetWebPreference)
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
.SetMethod("isWordMisspelled", &WebFrameRenderer::IsWordMisspelled)
.SetMethod("getWordSuggestions", &WebFrameRenderer::GetWordSuggestions)
#endif
.SetMethod("setVisualZoomLevelLimits",
&WebFrameRenderer::SetVisualZoomLevelLimits)
.SetMethod("allowGuestViewElementDefinition",
&RendererClientBase::AllowGuestViewElementDefinition)
.SetMethod("insertText", &WebFrameRenderer::InsertText)
.SetMethod("insertCSS", &WebFrameRenderer::InsertCSS)
.SetMethod("removeInsertedCSS", &WebFrameRenderer::RemoveInsertedCSS)
.SetMethod("_isEvalAllowed", &WebFrameRenderer::IsEvalAllowed)
.SetMethod("executeJavaScript", &WebFrameRenderer::ExecuteJavaScript)
.SetMethod("executeJavaScriptInIsolatedWorld",
&WebFrameRenderer::ExecuteJavaScriptInIsolatedWorld)
.SetMethod("setIsolatedWorldInfo",
&WebFrameRenderer::SetIsolatedWorldInfo)
.SetMethod("getResourceUsage", &WebFrameRenderer::GetResourceUsage)
.SetMethod("clearCache", &WebFrameRenderer::ClearCache)
.SetMethod("setSpellCheckProvider",
&WebFrameRenderer::SetSpellCheckProvider)
// Frame navigators
.SetMethod("findFrameByRoutingId",
&WebFrameRenderer::FindFrameByRoutingId)
.SetMethod("getFrameForSelector",
&WebFrameRenderer::GetFrameForSelector)
.SetMethod("findFrameByName", &WebFrameRenderer::FindFrameByName)
.SetProperty("opener", &WebFrameRenderer::GetOpener)
.SetProperty("parent", &WebFrameRenderer::GetFrameParent)
.SetProperty("top", &WebFrameRenderer::GetTop)
.SetProperty("firstChild", &WebFrameRenderer::GetFirstChild)
.SetProperty("nextSibling", &WebFrameRenderer::GetNextSibling)
.SetProperty("routingId", &WebFrameRenderer::GetRoutingId);
}
const char* GetTypeName() override { return "WebFrameRenderer"; }
void OnDestruct() override {}
private:
bool MaybeGetRenderFrame(v8::Isolate* isolate,
const base::StringPiece method_name,
content::RenderFrame** render_frame_ptr) {
std::string error_msg;
if (!MaybeGetRenderFrame(&error_msg, method_name, render_frame_ptr)) {
gin_helper::ErrorThrower(isolate).ThrowError(error_msg);
return false;
}
return true;
}
bool MaybeGetRenderFrame(std::string* error_msg,
const base::StringPiece method_name,
content::RenderFrame** render_frame_ptr) {
auto* frame = render_frame();
if (!frame) {
*error_msg = base::ToString("Render frame was torn down before webFrame.",
method_name, " could be executed");
return false;
}
*render_frame_ptr = frame;
return true;
}
static v8::Local<v8::Value> CreateWebFrameRenderer(v8::Isolate* isolate,
blink::WebFrame* frame) {
if (frame && frame->IsWebLocalFrame()) {
auto* render_frame =
content::RenderFrame::FromWebFrame(frame->ToWebLocalFrame());
return WebFrameRenderer::Create(isolate, render_frame).ToV8();
} else {
return v8::Null(isolate);
}
}
void SetName(v8::Isolate* isolate, const std::string& name) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "setName", &render_frame))
return;
render_frame->GetWebFrame()->SetName(blink::WebString::FromUTF8(name));
}
void SetZoomLevel(v8::Isolate* isolate, double level) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "setZoomLevel", &render_frame))
return;
mojo::AssociatedRemote<mojom::ElectronWebContentsUtility>
web_contents_utility_remote;
render_frame->GetRemoteAssociatedInterfaces()->GetInterface(
&web_contents_utility_remote);
web_contents_utility_remote->SetTemporaryZoomLevel(level);
}
double GetZoomLevel(v8::Isolate* isolate) {
double result = 0.0;
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "getZoomLevel", &render_frame))
return result;
mojo::AssociatedRemote<mojom::ElectronWebContentsUtility>
web_contents_utility_remote;
render_frame->GetRemoteAssociatedInterfaces()->GetInterface(
&web_contents_utility_remote);
web_contents_utility_remote->DoGetZoomLevel(&result);
return result;
}
void SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) {
if (factor < std::numeric_limits<double>::epsilon()) {
thrower.ThrowError("'zoomFactor' must be a double greater than 0.0");
return;
}
SetZoomLevel(thrower.isolate(), blink::PageZoomFactorToZoomLevel(factor));
}
double GetZoomFactor(v8::Isolate* isolate) {
double zoom_level = GetZoomLevel(isolate);
return blink::PageZoomLevelToZoomFactor(zoom_level);
}
v8::Local<v8::Value> GetWebPreference(v8::Isolate* isolate,
std::string pref_name) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "getWebPreference", &render_frame))
return v8::Undefined(isolate);
const auto& prefs = render_frame->GetBlinkPreferences();
if (pref_name == "isWebView") {
// FIXME(zcbenz): For child windows opened with window.open('') from
// webview, the WebPreferences is inherited from webview and the value
// of |is_webview| is wrong.
// Please check ElectronRenderFrameObserver::DidInstallConditionalFeatures
// for the background.
auto* web_frame = render_frame->GetWebFrame();
if (web_frame->Opener())
return gin::ConvertToV8(isolate, false);
return gin::ConvertToV8(isolate, prefs.is_webview);
} else if (pref_name == options::kHiddenPage) {
// NOTE: hiddenPage is internal-only.
return gin::ConvertToV8(isolate, prefs.hidden_page);
} else if (pref_name == options::kNodeIntegration) {
return gin::ConvertToV8(isolate, prefs.node_integration);
} else if (pref_name == options::kWebviewTag) {
return gin::ConvertToV8(isolate, prefs.webview_tag);
}
return v8::Null(isolate);
}
void SetVisualZoomLevelLimits(v8::Isolate* isolate,
double min_level,
double max_level) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "setVisualZoomLevelLimits",
&render_frame))
return;
blink::WebFrame* web_frame = render_frame->GetWebFrame();
web_frame->View()->SetDefaultPageScaleLimits(min_level, max_level);
}
static int GetWebFrameId(v8::Local<v8::Object> content_window) {
// Get the WebLocalFrame before (possibly) executing any user-space JS while
// getting the |params|. We track the status of the RenderFrame via an
// observer in case it is deleted during user code execution.
content::RenderFrame* render_frame = GetRenderFrame(content_window);
if (!render_frame)
return -1;
blink::WebLocalFrame* frame = render_frame->GetWebFrame();
// Parent must exist.
blink::WebFrame* parent_frame = frame->Parent();
DCHECK(parent_frame);
DCHECK(parent_frame->IsWebLocalFrame());
return render_frame->GetRoutingID();
}
void SetSpellCheckProvider(gin_helper::ErrorThrower thrower,
v8::Isolate* isolate,
const std::string& language,
v8::Local<v8::Object> provider) {
auto context = isolate->GetCurrentContext();
if (!provider->Has(context, gin::StringToV8(isolate, "spellCheck"))
.ToChecked()) {
thrower.ThrowError("\"spellCheck\" has to be defined");
return;
}
// Remove the old client.
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "setSpellCheckProvider", &render_frame))
return;
auto* existing = SpellCheckerHolder::FromRenderFrame(render_frame);
if (existing)
existing->UnsetAndDestroy();
// Set spellchecker for all live frames in the same process or
// in the sandbox mode for all live sub frames to this WebFrame.
auto spell_check_client =
std::make_unique<SpellCheckClient>(language, isolate, provider);
FrameSetSpellChecker spell_checker(spell_check_client.get(), render_frame);
// Attach the spell checker to RenderFrame.
new SpellCheckerHolder(render_frame, std::move(spell_check_client));
}
void InsertText(v8::Isolate* isolate, const std::string& text) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "insertText", &render_frame))
return;
blink::WebFrame* web_frame = render_frame->GetWebFrame();
if (web_frame->IsWebLocalFrame()) {
web_frame->ToWebLocalFrame()
->FrameWidget()
->GetActiveWebInputMethodController()
->CommitText(blink::WebString::FromUTF8(text),
blink::WebVector<ui::ImeTextSpan>(), blink::WebRange(),
0);
}
}
std::u16string InsertCSS(v8::Isolate* isolate,
const std::string& css,
gin::Arguments* args) {
blink::WebCssOrigin css_origin = blink::WebCssOrigin::kAuthor;
gin_helper::Dictionary options;
if (args->GetNext(&options))
options.Get("cssOrigin", &css_origin);
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "insertCSS", &render_frame))
return std::u16string();
blink::WebFrame* web_frame = render_frame->GetWebFrame();
if (web_frame->IsWebLocalFrame()) {
return web_frame->ToWebLocalFrame()
->GetDocument()
.InsertStyleSheet(blink::WebString::FromUTF8(css), nullptr,
css_origin)
.Utf16();
}
return std::u16string();
}
void RemoveInsertedCSS(v8::Isolate* isolate, const std::u16string& key) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "removeInsertedCSS", &render_frame))
return;
blink::WebFrame* web_frame = render_frame->GetWebFrame();
if (web_frame->IsWebLocalFrame()) {
web_frame->ToWebLocalFrame()->GetDocument().RemoveInsertedStyleSheet(
blink::WebString::FromUTF16(key));
}
}
bool IsEvalAllowed(v8::Isolate* isolate) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "isEvalAllowed", &render_frame))
return true;
auto* context = blink::ExecutionContext::From(
render_frame->GetWebFrame()->MainWorldScriptContext());
return !context->GetContentSecurityPolicy()->ShouldCheckEval();
}
v8::Local<v8::Promise> ExecuteJavaScript(gin::Arguments* gin_args,
const std::u16string& code) {
gin_helper::Arguments* args = static_cast<gin_helper::Arguments*>(gin_args);
v8::Isolate* isolate = args->isolate();
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
content::RenderFrame* render_frame;
std::string error_msg;
if (!MaybeGetRenderFrame(&error_msg, "executeJavaScript", &render_frame)) {
promise.RejectWithErrorMessage(error_msg);
return handle;
}
const blink::WebScriptSource source{blink::WebString::FromUTF16(code)};
bool has_user_gesture = false;
args->GetNext(&has_user_gesture);
ScriptExecutionCallback::CompletionCallback completion_callback;
args->GetNext(&completion_callback);
auto* self = new ScriptExecutionCallback(std::move(promise),
std::move(completion_callback));
render_frame->GetWebFrame()->RequestExecuteScript(
blink::DOMWrapperWorld::kMainWorldId, base::make_span(&source, 1u),
has_user_gesture ? blink::mojom::UserActivationOption::kActivate
: blink::mojom::UserActivationOption::kDoNotActivate,
blink::mojom::EvaluationTiming::kSynchronous,
blink::mojom::LoadEventBlockingOption::kDoNotBlock,
base::NullCallback(),
base::BindOnce(&ScriptExecutionCallback::Completed,
base::Unretained(self)),
blink::BackForwardCacheAware::kAllow,
blink::mojom::WantResultOption::kWantResult,
blink::mojom::PromiseResultOption::kDoNotWait);
return handle;
}
v8::Local<v8::Promise> ExecuteJavaScriptInIsolatedWorld(
gin::Arguments* gin_args,
int world_id,
const std::vector<gin_helper::Dictionary>& scripts) {
gin_helper::Arguments* args = static_cast<gin_helper::Arguments*>(gin_args);
v8::Isolate* isolate = args->isolate();
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
content::RenderFrame* render_frame;
std::string error_msg;
if (!MaybeGetRenderFrame(&error_msg, "executeJavaScriptInIsolatedWorld",
&render_frame)) {
promise.RejectWithErrorMessage(error_msg);
return handle;
}
bool has_user_gesture = false;
args->GetNext(&has_user_gesture);
blink::mojom::EvaluationTiming script_execution_type =
blink::mojom::EvaluationTiming::kSynchronous;
blink::mojom::LoadEventBlockingOption load_blocking_option =
blink::mojom::LoadEventBlockingOption::kDoNotBlock;
std::string execution_type;
args->GetNext(&execution_type);
if (execution_type == "asynchronous") {
script_execution_type = blink::mojom::EvaluationTiming::kAsynchronous;
} else if (execution_type == "asynchronousBlockingOnload") {
script_execution_type = blink::mojom::EvaluationTiming::kAsynchronous;
load_blocking_option = blink::mojom::LoadEventBlockingOption::kBlock;
}
ScriptExecutionCallback::CompletionCallback completion_callback;
args->GetNext(&completion_callback);
std::vector<blink::WebScriptSource> sources;
sources.reserve(scripts.size());
for (const auto& script : scripts) {
std::u16string code;
std::u16string url;
script.Get("url", &url);
if (!script.Get("code", &code)) {
const char error_message[] = "Invalid 'code'";
if (!completion_callback.is_null()) {
std::move(completion_callback)
.Run(v8::Undefined(isolate),
v8::Exception::Error(
v8::String::NewFromUtf8(isolate, error_message)
.ToLocalChecked()));
}
promise.RejectWithErrorMessage(error_message);
return handle;
}
sources.emplace_back(blink::WebString::FromUTF16(code),
blink::WebURL(GURL(url)));
}
// Deletes itself.
auto* self = new ScriptExecutionCallback(std::move(promise),
std::move(completion_callback));
render_frame->GetWebFrame()->RequestExecuteScript(
world_id, base::make_span(sources),
has_user_gesture ? blink::mojom::UserActivationOption::kActivate
: blink::mojom::UserActivationOption::kDoNotActivate,
script_execution_type, load_blocking_option, base::NullCallback(),
base::BindOnce(&ScriptExecutionCallback::Completed,
base::Unretained(self)),
blink::BackForwardCacheAware::kPossiblyDisallow,
blink::mojom::WantResultOption::kWantResult,
blink::mojom::PromiseResultOption::kDoNotWait);
return handle;
}
void SetIsolatedWorldInfo(v8::Isolate* isolate,
int world_id,
const gin_helper::Dictionary& options) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "setIsolatedWorldInfo", &render_frame))
return;
std::string origin_url, security_policy, name;
options.Get("securityOrigin", &origin_url);
options.Get("csp", &security_policy);
options.Get("name", &name);
if (!security_policy.empty() && origin_url.empty()) {
gin_helper::ErrorThrower(isolate).ThrowError(
"If csp is specified, securityOrigin should also be specified");
return;
}
blink::WebIsolatedWorldInfo info;
info.security_origin = blink::WebSecurityOrigin::CreateFromString(
blink::WebString::FromUTF8(origin_url));
info.content_security_policy = blink::WebString::FromUTF8(security_policy);
info.human_readable_name = blink::WebString::FromUTF8(name);
blink::SetIsolatedWorldInfo(world_id, info);
}
blink::WebCacheResourceTypeStats GetResourceUsage(v8::Isolate* isolate) {
blink::WebCacheResourceTypeStats stats;
blink::WebCache::GetResourceTypeStats(&stats);
return stats;
}
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
bool IsWordMisspelled(v8::Isolate* isolate, const std::string& word) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "isWordMisspelled", &render_frame))
return false;
return !SpellCheckWord(render_frame, word, nullptr);
}
std::vector<std::u16string> GetWordSuggestions(v8::Isolate* isolate,
const std::string& word) {
content::RenderFrame* render_frame;
std::vector<std::u16string> suggestions;
if (!MaybeGetRenderFrame(isolate, "getWordSuggestions", &render_frame))
return suggestions;
SpellCheckWord(render_frame, word, &suggestions);
return suggestions;
}
#endif
void ClearCache(v8::Isolate* isolate) {
isolate->IdleNotificationDeadline(0.5);
blink::WebCache::Clear();
base::MemoryPressureListener::NotifyMemoryPressure(
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
}
v8::Local<v8::Value> FindFrameByRoutingId(v8::Isolate* isolate,
int routing_id) {
content::RenderFrame* render_frame =
content::RenderFrame::FromRoutingID(routing_id);
if (render_frame)
return WebFrameRenderer::Create(isolate, render_frame).ToV8();
else
return v8::Null(isolate);
}
v8::Local<v8::Value> GetOpener(v8::Isolate* isolate) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "opener", &render_frame))
return v8::Null(isolate);
blink::WebFrame* frame = render_frame->GetWebFrame()->Opener();
return CreateWebFrameRenderer(isolate, frame);
}
// Don't name it as GetParent, Windows has API with same name.
v8::Local<v8::Value> GetFrameParent(v8::Isolate* isolate) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "parent", &render_frame))
return v8::Null(isolate);
blink::WebFrame* frame = render_frame->GetWebFrame()->Parent();
return CreateWebFrameRenderer(isolate, frame);
}
v8::Local<v8::Value> GetTop(v8::Isolate* isolate) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "top", &render_frame))
return v8::Null(isolate);
blink::WebFrame* frame = render_frame->GetWebFrame()->Top();
return CreateWebFrameRenderer(isolate, frame);
}
v8::Local<v8::Value> GetFirstChild(v8::Isolate* isolate) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "firstChild", &render_frame))
return v8::Null(isolate);
blink::WebFrame* frame = render_frame->GetWebFrame()->FirstChild();
return CreateWebFrameRenderer(isolate, frame);
}
v8::Local<v8::Value> GetNextSibling(v8::Isolate* isolate) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "nextSibling", &render_frame))
return v8::Null(isolate);
blink::WebFrame* frame = render_frame->GetWebFrame()->NextSibling();
return CreateWebFrameRenderer(isolate, frame);
}
v8::Local<v8::Value> GetFrameForSelector(v8::Isolate* isolate,
const std::string& selector) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "getFrameForSelector", &render_frame))
return v8::Null(isolate);
blink::WebElement element =
render_frame->GetWebFrame()->GetDocument().QuerySelector(
blink::WebString::FromUTF8(selector));
if (element.IsNull()) // not found
return v8::Null(isolate);
blink::WebFrame* frame = blink::WebFrame::FromFrameOwnerElement(element);
return CreateWebFrameRenderer(isolate, frame);
}
v8::Local<v8::Value> FindFrameByName(v8::Isolate* isolate,
const std::string& name) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "findFrameByName", &render_frame))
return v8::Null(isolate);
blink::WebFrame* frame = render_frame->GetWebFrame()->FindFrameByName(
blink::WebString::FromUTF8(name));
return CreateWebFrameRenderer(isolate, frame);
}
int GetRoutingId(v8::Isolate* isolate) {
content::RenderFrame* render_frame;
if (!MaybeGetRenderFrame(isolate, "routingId", &render_frame))
return 0;
return render_frame->GetRoutingID();
}
};
gin::WrapperInfo WebFrameRenderer::kWrapperInfo = {gin::kEmbedderNativeGin};
// static
std::set<SpellCheckerHolder*> SpellCheckerHolder::instances_;
} // namespace api
} // namespace electron
namespace {
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
using namespace electron::api; // NOLINT(build/namespaces)
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("mainFrame", WebFrameRenderer::Create(
isolate, electron::GetRenderFrame(exports)));
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_renderer_web_frame, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 39,891 |
[Bug]: NativeImage methods returned by capturePage fail with "Error: Illegal invocation"
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Ubuntu
### Operating System Version
Ubuntu 23.04
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
While calling `<webview-tag>.capturePage()` from renderer process, we should be able to run methods from the returned NativeImage (like `.getSize()`)
### Actual Behavior
While calling `<webview-tag>.capturePage()` from a renderer process, all of the NativeImage methods return the following error. In this example we call `.getSize()`:
```
Uncaught (in promise) Error: Illegal invocation: Function must be called on an object of type NativeImage
```
**Code snippet**
```js
const webviewElement = document.getElementById("webview")
webviewElement.capturePage()
.then((image) => console.log(image.getSize()))
```
**To reproduce**
**1.** Create a webview element in a page (BrowserView) and make set the id-attribute to `webview`
**2.** Execute the snippet above
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39891
|
https://github.com/electron/electron/pull/39978
|
5b105f911f7aa134ee44558fefaf171360d3d9d2
|
fd2861117e04a3c62bfab67a1b50cb9c3a55cd4d
| 2023-09-18T10:48:18Z |
c++
| 2023-10-18T14:21:42Z |
shell/renderer/renderer_client_base.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/renderer_client_base.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/command_line.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "components/network_hints/renderer/web_prescient_networking_impl.h"
#include "content/common/buildflags.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_switches.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_thread.h"
#include "electron/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "shell/browser/api/electron_api_protocol.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/color_util.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/node_includes.h"
#include "shell/common/node_util.h"
#include "shell/common/options_switches.h"
#include "shell/common/world_ids.h"
#include "shell/renderer/api/context_bridge/object_cache.h"
#include "shell/renderer/api/electron_api_context_bridge.h"
#include "shell/renderer/browser_exposed_renderer_interfaces.h"
#include "shell/renderer/content_settings_observer.h"
#include "shell/renderer/electron_api_service_impl.h"
#include "shell/renderer/electron_autofill_agent.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "third_party/blink/public/common/web_preferences/web_preferences.h"
#include "third_party/blink/public/web/blink.h"
#include "third_party/blink/public/web/web_custom_element.h" // NOLINT(build/include_alpha)
#include "third_party/blink/public/web/web_frame_widget.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_plugin_params.h"
#include "third_party/blink/public/web/web_script_source.h"
#include "third_party/blink/public/web/web_security_policy.h"
#include "third_party/blink/public/web/web_view.h"
#include "third_party/blink/renderer/platform/media/multi_buffer_data_source.h" // nogncheck
#include "third_party/blink/renderer/platform/weborigin/scheme_registry.h" // nogncheck
#include "third_party/widevine/cdm/buildflags.h"
#if BUILDFLAG(IS_MAC)
#include "base/strings/sys_string_conversions.h"
#endif
#if BUILDFLAG(IS_WIN)
#include <shlobj.h>
#endif
#if BUILDFLAG(ENABLE_WIDEVINE)
#include "chrome/renderer/media/chrome_key_systems.h" // nogncheck
#endif
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
#include "components/spellcheck/renderer/spellcheck.h"
#include "components/spellcheck/renderer/spellcheck_provider.h"
#endif
#if BUILDFLAG(ENABLE_PDF_VIEWER)
#include "chrome/common/pdf_util.h"
#include "components/pdf/common/internal_plugin_helpers.h"
#include "components/pdf/renderer/pdf_internal_plugin_delegate.h"
#include "shell/common/electron_constants.h"
#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
#if BUILDFLAG(ENABLE_PLUGINS)
#include "shell/common/plugin_info.h"
#include "shell/renderer/pepper_helper.h"
#endif // BUILDFLAG(ENABLE_PLUGINS)
#if BUILDFLAG(ENABLE_PRINTING)
#include "components/printing/renderer/print_render_frame_helper.h"
#include "printing/metafile_agent.h" // nogncheck
#include "shell/renderer/printing/print_render_frame_helper_delegate.h"
#endif // BUILDFLAG(ENABLE_PRINTING)
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "base/strings/utf_string_conversions.h"
#include "content/public/common/webplugininfo.h"
#include "extensions/common/constants.h"
#include "extensions/common/extensions_client.h"
#include "extensions/renderer/dispatcher.h"
#include "extensions/renderer/extension_frame_helper.h"
#include "extensions/renderer/extension_web_view_helper.h"
#include "extensions/renderer/guest_view/mime_handler_view/mime_handler_view_container_manager.h"
#include "shell/common/extensions/electron_extensions_client.h"
#include "shell/renderer/extensions/electron_extensions_renderer_client.h"
#endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
namespace electron {
content::RenderFrame* GetRenderFrame(v8::Local<v8::Object> value);
namespace {
void SetIsWebView(v8::Isolate* isolate, v8::Local<v8::Object> object) {
gin_helper::Dictionary dict(isolate, object);
dict.SetHidden("isWebView", true);
}
std::vector<std::string> ParseSchemesCLISwitch(base::CommandLine* command_line,
const char* switch_name) {
std::string custom_schemes = command_line->GetSwitchValueASCII(switch_name);
return base::SplitString(custom_schemes, ",", base::TRIM_WHITESPACE,
base::SPLIT_WANT_NONEMPTY);
}
#if BUILDFLAG(ENABLE_PDF_VIEWER)
class ChromePdfInternalPluginDelegate final
: public pdf::PdfInternalPluginDelegate {
public:
ChromePdfInternalPluginDelegate() = default;
ChromePdfInternalPluginDelegate(const ChromePdfInternalPluginDelegate&) =
delete;
ChromePdfInternalPluginDelegate& operator=(
const ChromePdfInternalPluginDelegate&) = delete;
~ChromePdfInternalPluginDelegate() override = default;
// `pdf::PdfInternalPluginDelegate`:
bool IsAllowedOrigin(const url::Origin& origin) const override {
return origin.scheme() == extensions::kExtensionScheme &&
origin.host() == extension_misc::kPdfExtensionId;
}
};
#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
// static
RendererClientBase* g_renderer_client_base = nullptr;
bool IsDevTools(content::RenderFrame* render_frame) {
return render_frame->GetWebFrame()->GetDocument().Url().ProtocolIs(
"devtools");
}
bool IsDevToolsExtension(content::RenderFrame* render_frame) {
return render_frame->GetWebFrame()->GetDocument().Url().ProtocolIs(
"chrome-extension");
}
} // namespace
RendererClientBase::RendererClientBase() {
auto* command_line = base::CommandLine::ForCurrentProcess();
// Parse --service-worker-schemes=scheme1,scheme2
std::vector<std::string> service_worker_schemes_list =
ParseSchemesCLISwitch(command_line, switches::kServiceWorkerSchemes);
for (const std::string& scheme : service_worker_schemes_list)
electron::api::AddServiceWorkerScheme(scheme);
// Parse --standard-schemes=scheme1,scheme2
std::vector<std::string> standard_schemes_list =
ParseSchemesCLISwitch(command_line, switches::kStandardSchemes);
for (const std::string& scheme : standard_schemes_list)
url::AddStandardScheme(scheme.c_str(), url::SCHEME_WITH_HOST);
// Parse --cors-schemes=scheme1,scheme2
std::vector<std::string> cors_schemes_list =
ParseSchemesCLISwitch(command_line, switches::kCORSSchemes);
for (const std::string& scheme : cors_schemes_list)
url::AddCorsEnabledScheme(scheme.c_str());
// Parse --streaming-schemes=scheme1,scheme2
std::vector<std::string> streaming_schemes_list =
ParseSchemesCLISwitch(command_line, switches::kStreamingSchemes);
for (const std::string& scheme : streaming_schemes_list)
blink::AddStreamingScheme(scheme.c_str());
// Parse --secure-schemes=scheme1,scheme2
std::vector<std::string> secure_schemes_list =
ParseSchemesCLISwitch(command_line, switches::kSecureSchemes);
for (const std::string& scheme : secure_schemes_list)
url::AddSecureScheme(scheme.data());
// We rely on the unique process host id which is notified to the
// renderer process via command line switch from the content layer,
// if this switch is removed from the content layer for some reason,
// we should define our own.
DCHECK(command_line->HasSwitch(::switches::kRendererClientId));
renderer_client_id_ =
command_line->GetSwitchValueASCII(::switches::kRendererClientId);
g_renderer_client_base = this;
}
RendererClientBase::~RendererClientBase() {
g_renderer_client_base = nullptr;
}
// static
RendererClientBase* RendererClientBase::Get() {
DCHECK(g_renderer_client_base);
return g_renderer_client_base;
}
void RendererClientBase::BindProcess(v8::Isolate* isolate,
gin_helper::Dictionary* process,
content::RenderFrame* render_frame) {
auto context_id = base::StringPrintf(
"%s-%" PRId64, renderer_client_id_.c_str(), ++next_context_id_);
process->SetReadOnly("isMainFrame", render_frame->IsMainFrame());
process->SetReadOnly("contextIsolated",
render_frame->GetBlinkPreferences().context_isolation);
process->SetReadOnly("contextId", context_id);
}
bool RendererClientBase::ShouldLoadPreload(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) const {
auto prefs = render_frame->GetBlinkPreferences();
bool is_main_frame = render_frame->IsMainFrame();
bool is_devtools =
IsDevTools(render_frame) || IsDevToolsExtension(render_frame);
bool allow_node_in_sub_frames = prefs.node_integration_in_sub_frames;
return (is_main_frame || is_devtools || allow_node_in_sub_frames) &&
!IsWebViewFrame(context, render_frame);
}
void RendererClientBase::RenderThreadStarted() {
auto* command_line = base::CommandLine::ForCurrentProcess();
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
auto* thread = content::RenderThread::Get();
extensions_client_.reset(CreateExtensionsClient());
extensions::ExtensionsClient::Set(extensions_client_.get());
extensions_renderer_client_ =
std::make_unique<ElectronExtensionsRendererClient>();
extensions::ExtensionsRendererClient::Set(extensions_renderer_client_.get());
thread->AddObserver(extensions_renderer_client_->GetDispatcher());
WTF::String extension_scheme(extensions::kExtensionScheme);
// Extension resources are HTTP-like and safe to expose to the fetch API. The
// rules for the fetch API are consistent with XHR.
blink::SchemeRegistry::RegisterURLSchemeAsSupportingFetchAPI(
extension_scheme);
// Extension resources, when loaded as the top-level document, should bypass
// Blink's strict first-party origin checks.
blink::SchemeRegistry::RegisterURLSchemeAsFirstPartyWhenTopLevel(
extension_scheme);
blink::SchemeRegistry::RegisterURLSchemeAsBypassingContentSecurityPolicy(
extension_scheme);
#endif
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
spellcheck_ = std::make_unique<SpellCheck>(this);
#endif
blink::WebCustomElement::AddEmbedderCustomElementName("webview");
blink::WebCustomElement::AddEmbedderCustomElementName("browserplugin");
std::vector<std::string> fetch_enabled_schemes =
ParseSchemesCLISwitch(command_line, switches::kFetchSchemes);
for (const std::string& scheme : fetch_enabled_schemes) {
blink::WebSecurityPolicy::RegisterURLSchemeAsSupportingFetchAPI(
blink::WebString::FromASCII(scheme));
}
std::vector<std::string> service_worker_schemes =
ParseSchemesCLISwitch(command_line, switches::kServiceWorkerSchemes);
for (const std::string& scheme : service_worker_schemes)
blink::WebSecurityPolicy::RegisterURLSchemeAsAllowingServiceWorkers(
blink::WebString::FromASCII(scheme));
std::vector<std::string> csp_bypassing_schemes =
ParseSchemesCLISwitch(command_line, switches::kBypassCSPSchemes);
for (const std::string& scheme : csp_bypassing_schemes)
blink::SchemeRegistry::RegisterURLSchemeAsBypassingContentSecurityPolicy(
WTF::String::FromUTF8(scheme.data(), scheme.length()));
// Allow file scheme to handle service worker by default.
// FIXME(zcbenz): Can this be moved elsewhere?
blink::WebSecurityPolicy::RegisterURLSchemeAsAllowingServiceWorkers("file");
blink::SchemeRegistry::RegisterURLSchemeAsSupportingFetchAPI("file");
#if BUILDFLAG(IS_WIN)
// Set ApplicationUserModelID in renderer process.
std::wstring app_id =
command_line->GetSwitchValueNative(switches::kAppUserModelId);
if (!app_id.empty()) {
SetCurrentProcessExplicitAppUserModelID(app_id.c_str());
}
#endif
}
void RendererClientBase::ExposeInterfacesToBrowser(mojo::BinderMap* binders) {
// NOTE: Do not add binders directly within this method. Instead, modify the
// definition of |ExposeElectronRendererInterfacesToBrowser()| to ensure
// security review coverage.
ExposeElectronRendererInterfacesToBrowser(this, binders);
}
void RendererClientBase::RenderFrameCreated(
content::RenderFrame* render_frame) {
#if defined(TOOLKIT_VIEWS)
new AutofillAgent(render_frame,
render_frame->GetAssociatedInterfaceRegistry());
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
new PepperHelper(render_frame);
#endif
new ContentSettingsObserver(render_frame);
#if BUILDFLAG(ENABLE_PRINTING)
new printing::PrintRenderFrameHelper(
render_frame,
std::make_unique<electron::PrintRenderFrameHelperDelegate>());
#endif
// Note: ElectronApiServiceImpl has to be created now to capture the
// DidCreateDocumentElement event.
new ElectronApiServiceImpl(render_frame, this);
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
auto* dispatcher = extensions_renderer_client_->GetDispatcher();
// ExtensionFrameHelper destroys itself when the RenderFrame is destroyed.
new extensions::ExtensionFrameHelper(render_frame, dispatcher);
dispatcher->OnRenderFrameCreated(render_frame);
render_frame->GetAssociatedInterfaceRegistry()
->AddInterface<extensions::mojom::MimeHandlerViewContainerManager>(
base::BindRepeating(
&extensions::MimeHandlerViewContainerManager::BindReceiver,
render_frame->GetRoutingID()));
#endif
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
if (render_frame->GetBlinkPreferences().enable_spellcheck)
new SpellCheckProvider(render_frame, spellcheck_.get(), this);
#endif
}
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
void RendererClientBase::GetInterface(
const std::string& interface_name,
mojo::ScopedMessagePipeHandle interface_pipe) {
// TODO(crbug.com/977637): Get rid of the use of this implementation of
// |service_manager::LocalInterfaceProvider|. This was done only to avoid
// churning spellcheck code while eliminating the "chrome" and
// "chrome_renderer" services. Spellcheck is (and should remain) the only
// consumer of this implementation.
content::RenderThread::Get()->BindHostReceiver(
mojo::GenericPendingReceiver(interface_name, std::move(interface_pipe)));
}
#endif
void RendererClientBase::DidClearWindowObject(
content::RenderFrame* render_frame) {
// Make sure every page will get a script context created.
render_frame->GetWebFrame()->ExecuteScript(blink::WebScriptSource("void 0"));
}
bool RendererClientBase::OverrideCreatePlugin(
content::RenderFrame* render_frame,
const blink::WebPluginParams& params,
blink::WebPlugin** plugin) {
#if BUILDFLAG(ENABLE_PDF_VIEWER)
if (params.mime_type.Utf8() == pdf::kInternalPluginMimeType) {
*plugin = pdf::CreateInternalPlugin(
std::move(params), render_frame,
std::make_unique<ChromePdfInternalPluginDelegate>());
return true;
}
#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
if (params.mime_type.Utf8() == content::kBrowserPluginMimeType ||
render_frame->GetBlinkPreferences().enable_plugins)
return false;
*plugin = nullptr;
return true;
}
void RendererClientBase::GetSupportedKeySystems(
media::GetSupportedKeySystemsCB cb) {
#if BUILDFLAG(ENABLE_WIDEVINE)
GetChromeKeySystems(std::move(cb));
#else
std::move(cb).Run({});
#endif
}
void RendererClientBase::DidSetUserAgent(const std::string& user_agent) {
#if BUILDFLAG(ENABLE_PRINTING)
printing::SetAgent(user_agent);
#endif
}
bool RendererClientBase::IsPluginHandledExternally(
content::RenderFrame* render_frame,
const blink::WebElement& plugin_element,
const GURL& original_url,
const std::string& mime_type) {
#if BUILDFLAG(ENABLE_PDF_VIEWER)
DCHECK(plugin_element.HasHTMLTagName("object") ||
plugin_element.HasHTMLTagName("embed"));
if (mime_type == pdf::kInternalPluginMimeType) {
if (IsPdfInternalPluginAllowedOrigin(
render_frame->GetWebFrame()->GetSecurityOrigin())) {
return true;
}
content::WebPluginInfo info;
info.type = content::WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS;
info.name = base::ASCIIToUTF16(kPDFInternalPluginName);
info.path = base::FilePath(kPdfPluginPath);
info.background_color = content::WebPluginInfo::kDefaultBackgroundColor;
info.mime_types.emplace_back(pdf::kInternalPluginMimeType, "pdf",
"Portable Document Format");
return extensions::MimeHandlerViewContainerManager::Get(
content::RenderFrame::FromWebFrame(
plugin_element.GetDocument().GetFrame()),
true /* create_if_does_not_exist */)
->CreateFrameContainer(plugin_element, original_url, mime_type, info);
}
return extensions::MimeHandlerViewContainerManager::Get(
content::RenderFrame::FromWebFrame(
plugin_element.GetDocument().GetFrame()),
true /* create_if_does_not_exist */)
->CreateFrameContainer(plugin_element, original_url, mime_type,
GetPDFPluginInfo());
#else
return false;
#endif
}
v8::Local<v8::Object> RendererClientBase::GetScriptableObject(
const blink::WebElement& plugin_element,
v8::Isolate* isolate) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// If there is a MimeHandlerView that can provide the scriptable object then
// MaybeCreateMimeHandlerView must have been called before and a container
// manager should exist.
auto* container_manager = extensions::MimeHandlerViewContainerManager::Get(
content::RenderFrame::FromWebFrame(
plugin_element.GetDocument().GetFrame()),
false /* create_if_does_not_exist */);
if (container_manager)
return container_manager->GetScriptableObject(plugin_element, isolate);
#endif
return v8::Local<v8::Object>();
}
std::unique_ptr<blink::WebPrescientNetworking>
RendererClientBase::CreatePrescientNetworking(
content::RenderFrame* render_frame) {
return std::make_unique<network_hints::WebPrescientNetworkingImpl>(
render_frame);
}
void RendererClientBase::RunScriptsAtDocumentStart(
content::RenderFrame* render_frame) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_.get()->RunScriptsAtDocumentStart(render_frame);
#endif
}
void RendererClientBase::RunScriptsAtDocumentIdle(
content::RenderFrame* render_frame) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_.get()->RunScriptsAtDocumentIdle(render_frame);
#endif
}
void RendererClientBase::RunScriptsAtDocumentEnd(
content::RenderFrame* render_frame) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_.get()->RunScriptsAtDocumentEnd(render_frame);
#endif
}
bool RendererClientBase::AllowScriptExtensionForServiceWorker(
const url::Origin& script_origin) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
return script_origin.scheme() == extensions::kExtensionScheme;
#else
return false;
#endif
}
void RendererClientBase::DidInitializeServiceWorkerContextOnWorkerThread(
blink::WebServiceWorkerContextProxy* context_proxy,
const GURL& service_worker_scope,
const GURL& script_url) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_->GetDispatcher()
->DidInitializeServiceWorkerContextOnWorkerThread(
context_proxy, service_worker_scope, script_url);
#endif
}
void RendererClientBase::WillEvaluateServiceWorkerOnWorkerThread(
blink::WebServiceWorkerContextProxy* context_proxy,
v8::Local<v8::Context> v8_context,
int64_t service_worker_version_id,
const GURL& service_worker_scope,
const GURL& script_url) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_->GetDispatcher()
->WillEvaluateServiceWorkerOnWorkerThread(
context_proxy, v8_context, service_worker_version_id,
service_worker_scope, script_url);
#endif
}
void RendererClientBase::DidStartServiceWorkerContextOnWorkerThread(
int64_t service_worker_version_id,
const GURL& service_worker_scope,
const GURL& script_url) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_->GetDispatcher()
->DidStartServiceWorkerContextOnWorkerThread(
service_worker_version_id, service_worker_scope, script_url);
#endif
}
void RendererClientBase::WillDestroyServiceWorkerContextOnWorkerThread(
v8::Local<v8::Context> context,
int64_t service_worker_version_id,
const GURL& service_worker_scope,
const GURL& script_url) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_renderer_client_->GetDispatcher()
->WillDestroyServiceWorkerContextOnWorkerThread(
context, service_worker_version_id, service_worker_scope, script_url);
#endif
}
void RendererClientBase::WebViewCreated(blink::WebView* web_view,
bool was_created_by_renderer,
const url::Origin* outermost_origin) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
new extensions::ExtensionWebViewHelper(web_view, outermost_origin);
#endif
}
v8::Local<v8::Context> RendererClientBase::GetContext(
blink::WebLocalFrame* frame,
v8::Isolate* isolate) const {
auto* render_frame = content::RenderFrame::FromWebFrame(frame);
DCHECK(render_frame);
if (render_frame && render_frame->GetBlinkPreferences().context_isolation)
return frame->GetScriptContextFromWorldId(isolate,
WorldIDs::ISOLATED_WORLD_ID);
else
return frame->MainWorldScriptContext();
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ExtensionsClient* RendererClientBase::CreateExtensionsClient() {
return new ElectronExtensionsClient;
}
#endif
bool RendererClientBase::IsWebViewFrame(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) const {
auto* isolate = context->GetIsolate();
if (render_frame->IsMainFrame())
return false;
gin::Dictionary window_dict(
isolate, GetContext(render_frame->GetWebFrame(), isolate)->Global());
v8::Local<v8::Object> frame_element;
if (!window_dict.Get("frameElement", &frame_element))
return false;
gin_helper::Dictionary frame_element_dict(isolate, frame_element);
bool is_webview = false;
return frame_element_dict.GetHidden("isWebView", &is_webview) && is_webview;
}
void RendererClientBase::SetupMainWorldOverrides(
v8::Handle<v8::Context> context,
content::RenderFrame* render_frame) {
auto prefs = render_frame->GetBlinkPreferences();
// We only need to run the isolated bundle if webview is enabled
if (!prefs.webview_tag)
return;
// Setup window overrides in the main world context
// Wrap the bundle into a function that receives the isolatedApi as
// an argument.
auto* isolate = context->GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context);
auto isolated_api = gin_helper::Dictionary::CreateEmpty(isolate);
isolated_api.SetMethod("allowGuestViewElementDefinition",
&AllowGuestViewElementDefinition);
isolated_api.SetMethod("setIsWebView", &SetIsWebView);
auto source_context = GetContext(render_frame->GetWebFrame(), isolate);
gin_helper::Dictionary global(isolate, source_context->Global());
v8::Local<v8::Value> guest_view_internal;
if (global.GetHidden("guestViewInternal", &guest_view_internal)) {
api::context_bridge::ObjectCache object_cache;
auto result = api::PassValueToOtherContext(
source_context, context, guest_view_internal, &object_cache, false, 0,
api::BridgeErrorTarget::kSource);
if (!result.IsEmpty()) {
isolated_api.Set("guestViewInternal", result.ToLocalChecked());
}
}
std::vector<v8::Local<v8::String>> isolated_bundle_params = {
node::FIXED_ONE_BYTE_STRING(isolate, "isolatedApi")};
std::vector<v8::Local<v8::Value>> isolated_bundle_args = {
isolated_api.GetHandle()};
util::CompileAndCall(context, "electron/js2c/isolated_bundle",
&isolated_bundle_params, &isolated_bundle_args, nullptr);
}
// static
void RendererClientBase::AllowGuestViewElementDefinition(
v8::Isolate* isolate,
v8::Local<v8::Object> context,
v8::Local<v8::Function> register_cb) {
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context->GetCreationContextChecked());
blink::WebCustomElement::EmbedderNamesAllowedScope embedder_names_scope;
content::RenderFrame* render_frame = GetRenderFrame(context);
if (!render_frame)
return;
render_frame->GetWebFrame()->RequestExecuteV8Function(
context->GetCreationContextChecked(), register_cb, v8::Null(isolate), 0,
nullptr, base::NullCallback());
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 39,891 |
[Bug]: NativeImage methods returned by capturePage fail with "Error: Illegal invocation"
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0
### What operating system are you using?
Ubuntu
### Operating System Version
Ubuntu 23.04
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
While calling `<webview-tag>.capturePage()` from renderer process, we should be able to run methods from the returned NativeImage (like `.getSize()`)
### Actual Behavior
While calling `<webview-tag>.capturePage()` from a renderer process, all of the NativeImage methods return the following error. In this example we call `.getSize()`:
```
Uncaught (in promise) Error: Illegal invocation: Function must be called on an object of type NativeImage
```
**Code snippet**
```js
const webviewElement = document.getElementById("webview")
webviewElement.capturePage()
.then((image) => console.log(image.getSize()))
```
**To reproduce**
**1.** Create a webview element in a page (BrowserView) and make set the id-attribute to `webview`
**2.** Execute the snippet above
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39891
|
https://github.com/electron/electron/pull/39978
|
5b105f911f7aa134ee44558fefaf171360d3d9d2
|
fd2861117e04a3c62bfab67a1b50cb9c3a55cd4d
| 2023-09-18T10:48:18Z |
c++
| 2023-10-18T14:21:42Z |
spec/webview-spec.ts
|
import * as path from 'node:path';
import * as url from 'node:url';
import { BrowserWindow, session, ipcMain, app, WebContents } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import { emittedUntil } from './lib/events-helpers';
import { ifit, ifdescribe, defer, itremote, useRemoteContext, listen } from './lib/spec-helpers';
import { expect } from 'chai';
import * as http from 'node:http';
import * as auth from 'basic-auth';
import { once } from 'node:events';
import { setTimeout } from 'node:timers/promises';
declare let WebView: any;
const features = process._linkedBinding('electron_common_features');
async function loadWebView (w: WebContents, attributes: Record<string, string>, opts?: {openDevTools?: boolean}): Promise<void> {
const { openDevTools } = {
openDevTools: false,
...opts
};
await w.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView()
webview.id = 'webview'
for (const [k, v] of Object.entries(${JSON.stringify(attributes)})) {
webview.setAttribute(k, v)
}
document.body.appendChild(webview)
webview.addEventListener('dom-ready', () => {
if (${openDevTools}) {
webview.openDevTools()
}
})
webview.addEventListener('did-finish-load', () => {
resolve()
})
})
`);
}
async function loadWebViewAndWaitForEvent (w: WebContents, attributes: Record<string, string>, eventName: string): Promise<any> {
return await w.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.id = 'webview'
for (const [k, v] of Object.entries(${JSON.stringify(attributes)})) {
webview.setAttribute(k, v)
}
webview.addEventListener(${JSON.stringify(eventName)}, (e) => resolve({...e}), {once: true})
document.body.appendChild(webview)
})`);
};
async function loadWebViewAndWaitForMessage (w: WebContents, attributes: Record<string, string>): Promise<string> {
const { message } = await loadWebViewAndWaitForEvent(w, attributes, 'console-message');
return message;
};
describe('<webview> tag', function () {
const fixtures = path.join(__dirname, 'fixtures');
const blankPageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'blank.html')).toString();
function hideChildWindows (e: any, wc: WebContents) {
wc.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
show: false
}
}));
}
before(() => {
app.on('web-contents-created', hideChildWindows);
});
after(() => {
app.off('web-contents-created', hideChildWindows);
});
describe('behavior', () => {
afterEach(closeAllWindows);
it('works without script tag in page', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html'));
await once(ipcMain, 'pong');
});
it('works with sandbox', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
sandbox: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html'));
await once(ipcMain, 'pong');
});
it('works with contextIsolation', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html'));
await once(ipcMain, 'pong');
});
it('works with contextIsolation + sandbox', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true,
sandbox: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html'));
await once(ipcMain, 'pong');
});
it('works with Trusted Types', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-trusted-types.html'));
await once(ipcMain, 'pong');
});
it('is disabled by default', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
preload: path.join(fixtures, 'module', 'preload-webview.js'),
nodeIntegration: true
}
});
const webview = once(ipcMain, 'webview');
w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html'));
const [, type] = await webview;
expect(type).to.equal('undefined', 'WebView still exists');
});
});
// FIXME(deepak1556): Ch69 follow up.
xdescribe('document.visibilityState/hidden', () => {
afterEach(() => {
ipcMain.removeAllListeners('pong');
});
afterEach(closeAllWindows);
it('updates when the window is shown after the ready-to-show event', async () => {
const w = new BrowserWindow({ show: false });
const readyToShowSignal = once(w, 'ready-to-show');
const pongSignal1 = once(ipcMain, 'pong');
w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html'));
await pongSignal1;
const pongSignal2 = once(ipcMain, 'pong');
await readyToShowSignal;
w.show();
const [, visibilityState, hidden] = await pongSignal2;
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false();
});
it('inherits the parent window visibility state and receives visibilitychange events', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html'));
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true();
// We have to start waiting for the event
// before we ask the webContents to resize.
const getResponse = once(ipcMain, 'pong');
w.webContents.emit('-window-visibility-change', 'visible');
return getResponse.then(([, visibilityState, hidden]) => {
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false();
});
});
});
describe('did-attach-webview event', () => {
afterEach(closeAllWindows);
it('is emitted when a webview has been attached', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: 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('did-attach event', () => {
afterEach(closeAllWindows);
it('is emitted when a webview has been attached', async () => {
const w = new BrowserWindow({
webPreferences: {
webviewTag: true
}
});
await w.loadURL('about:blank');
const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', 'about:blank')
webview.addEventListener('did-attach', (e) => {
resolve('ok')
})
document.body.appendChild(webview)
})`);
expect(message).to.equal('ok');
});
});
describe('did-change-theme-color event', () => {
afterEach(closeAllWindows);
it('emits when theme color changes', async () => {
const w = new BrowserWindow({
webPreferences: {
webviewTag: true
}
});
await w.loadURL('about:blank');
const src = url.format({
pathname: `${fixtures.replaceAll('\\', '/')}/pages/theme-color.html`,
protocol: 'file',
slashes: true
});
const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', '${src}')
webview.addEventListener('did-change-theme-color', (e) => {
resolve('ok')
})
document.body.appendChild(webview)
})`);
expect(message).to.equal('ok');
});
});
describe('devtools', () => {
afterEach(closeAllWindows);
// FIXME: This test is flaky on WOA, so skip it there.
ifit(process.platform !== 'win32' || process.arch !== 'arm64')('loads devtools extensions registered on the parent window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
w.webContents.session.removeExtension('foo');
const extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo');
await w.webContents.session.loadExtension(extensionPath, {
allowFileAccess: true
});
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'webview-devtools.html'));
loadWebView(w.webContents, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(__dirname, 'fixtures', 'blank.html')}`
}, { openDevTools: true });
let childWebContentsId = 0;
app.once('web-contents-created', (e, webContents) => {
childWebContentsId = webContents.id;
webContents.on('devtools-opened', function () {
const showPanelIntervalId = setInterval(function () {
if (!webContents.isDestroyed() && webContents.devToolsWebContents) {
webContents.devToolsWebContents.executeJavaScript('(' + function () {
const { UI } = (window as any);
const tabs = UI.inspectorView.tabbedPane.tabs;
const lastPanelId: any = tabs[tabs.length - 1].id;
UI.inspectorView.showPanel(lastPanelId);
}.toString() + ')()');
} else {
clearInterval(showPanelIntervalId);
}
}, 100);
});
});
const [, { runtimeId, tabId }] = await once(ipcMain, 'answer');
expect(runtimeId).to.match(/^[a-z]{32}$/);
expect(tabId).to.equal(childWebContentsId);
await w.webContents.executeJavaScript('webview.closeDevTools()');
});
});
describe('zoom behavior', () => {
const zoomScheme = standardScheme;
const webviewSession = session.fromPartition('webview-temp');
afterEach(closeAllWindows);
before(() => {
const protocol = webviewSession.protocol;
protocol.registerStringProtocol(zoomScheme, (request, callback) => {
callback('hello');
});
});
after(() => {
const protocol = webviewSession.protocol;
protocol.unregisterProtocol(zoomScheme);
});
it('inherits the zoomFactor of the parent window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
});
const zoomEventPromise = once(ipcMain, 'webview-parent-zoom-level');
w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-factor.html'));
const [, zoomFactor, zoomLevel] = await zoomEventPromise;
expect(zoomFactor).to.equal(1.2);
expect(zoomLevel).to.equal(1);
});
it('maintains zoom level on navigation', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
});
const promise = new Promise<void>((resolve) => {
ipcMain.on('webview-zoom-level', (event, zoomLevel, zoomFactor, newHost, final) => {
if (!newHost) {
expect(zoomFactor).to.equal(1.44);
expect(zoomLevel).to.equal(2.0);
} else {
expect(zoomFactor).to.equal(1.2);
expect(zoomLevel).to.equal(1);
}
if (final) {
resolve();
}
});
});
w.loadFile(path.join(fixtures, 'pages', 'webview-custom-zoom-level.html'));
await promise;
});
it('maintains zoom level when navigating within same page', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
});
const promise = new Promise<void>((resolve) => {
ipcMain.on('webview-zoom-in-page', (event, zoomLevel, zoomFactor, final) => {
expect(zoomFactor).to.equal(1.44);
expect(zoomLevel).to.equal(2.0);
if (final) {
resolve();
}
});
});
w.loadFile(path.join(fixtures, 'pages', 'webview-in-page-navigate.html'));
await promise;
});
it('inherits zoom level for the origin when available', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-origin-zoom-level.html'));
const [, zoomLevel] = await once(ipcMain, 'webview-origin-zoom-level');
expect(zoomLevel).to.equal(2.0);
});
it('does not crash when navigating with zoom level inherited from parent', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
session: webviewSession,
contextIsolation: false
}
});
const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
const readyPromise = once(ipcMain, 'dom-ready');
w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-inherited.html'));
const [, webview] = await attachPromise;
await readyPromise;
expect(webview.getZoomFactor()).to.equal(1.2);
await w.loadURL(`${zoomScheme}://host1`);
});
it('does not crash when changing zoom level after webview is destroyed', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
session: webviewSession,
contextIsolation: false
}
});
const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
await w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-inherited.html'));
await attachPromise;
await w.webContents.executeJavaScript('view.remove()');
w.webContents.setZoomLevel(0.5);
});
});
describe('requestFullscreen from webview', () => {
afterEach(closeAllWindows);
async function loadWebViewWindow (): Promise<[BrowserWindow, WebContents]> {
const w = new BrowserWindow({
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
const loadPromise = once(w.webContents, 'did-finish-load');
const readyPromise = once(ipcMain, 'webview-ready');
w.loadFile(path.join(__dirname, 'fixtures', 'webview', 'fullscreen', 'main.html'));
const [, webview] = await attachPromise;
await Promise.all([readyPromise, loadPromise]);
return [w, webview];
};
afterEach(async () => {
// The leaving animation is un-observable but can interfere with future tests
// Specifically this is async on macOS but can be on other platforms too
await setTimeout(1000);
closeAllWindows();
});
ifit(process.platform !== 'darwin')('should make parent frame element fullscreen too (non-macOS)', async () => {
const [w, webview] = await loadWebViewWindow();
expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.false();
const parentFullscreen = once(ipcMain, 'fullscreenchange');
await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await parentFullscreen;
expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.true();
const close = once(w, 'closed');
w.close();
await close;
});
ifit(process.platform === 'darwin')('should make parent frame element fullscreen too (macOS)', async () => {
const [w, webview] = await loadWebViewWindow();
expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.false();
const parentFullscreen = once(ipcMain, 'fullscreenchange');
const enterHTMLFS = once(w.webContents, 'enter-html-full-screen');
const leaveHTMLFS = once(w.webContents, 'leave-html-full-screen');
await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.true();
await webview.executeJavaScript('document.exitFullscreen()');
await Promise.all([enterHTMLFS, leaveHTMLFS, parentFullscreen]);
const close = once(w, 'closed');
w.close();
await close;
});
// FIXME(zcbenz): Fullscreen events do not work on Linux.
ifit(process.platform !== 'linux')('exiting fullscreen should unfullscreen window', async () => {
const [w, webview] = await loadWebViewWindow();
const enterFullScreen = once(w, 'enter-full-screen');
await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
const leaveFullScreen = once(w, 'leave-full-screen');
await webview.executeJavaScript('document.exitFullscreen()', true);
await leaveFullScreen;
await setTimeout();
expect(w.isFullScreen()).to.be.false();
const close = once(w, 'closed');
w.close();
await close;
});
// Sending ESC via sendInputEvent only works on Windows.
ifit(process.platform === 'win32')('pressing ESC should unfullscreen window', async () => {
const [w, webview] = await loadWebViewWindow();
const enterFullScreen = once(w, 'enter-full-screen');
await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
const leaveFullScreen = once(w, 'leave-full-screen');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
await leaveFullScreen;
await setTimeout();
expect(w.isFullScreen()).to.be.false();
const close = once(w, 'closed');
w.close();
await close;
});
it('pressing ESC should emit the leave-html-full-screen event', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
const didAttachWebview = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'));
const [, webContents] = await didAttachWebview;
const enterFSWindow = once(w, 'enter-html-full-screen');
const enterFSWebview = once(webContents, 'enter-html-full-screen');
await webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFSWindow;
await enterFSWebview;
const leaveFSWindow = once(w, 'leave-html-full-screen');
const leaveFSWebview = once(webContents, 'leave-html-full-screen');
webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
await leaveFSWebview;
await leaveFSWindow;
const close = once(w, 'closed');
w.close();
await close;
});
it('should support user gesture', async () => {
const [w, webview] = await loadWebViewWindow();
const waitForEnterHtmlFullScreen = once(webview, 'enter-html-full-screen');
const jsScript = "document.querySelector('video').webkitRequestFullscreen()";
webview.executeJavaScript(jsScript, true);
await waitForEnterHtmlFullScreen;
const close = once(w, 'closed');
w.close();
await close;
});
});
describe('child windows', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
it('opens window of about:blank with cross-scripting enabled', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-blank.html')}`
});
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('Hello');
});
it('opens window of same domain with cross-scripting enabled', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-file.html')}`
});
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('Hello');
});
it('returns null from window.open when allowpopups is not set', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-no-allowpopups.html')}`
});
const [, { windowOpenReturnedNull }] = await once(ipcMain, 'answer');
expect(windowOpenReturnedNull).to.be.true();
});
it('blocks accessing cross-origin frames', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-cross-origin.html')}`
});
const [, content] = await once(ipcMain, 'answer');
const expectedContent =
/Failed to read a named property 'toString' from 'Location': Blocked a frame with origin "(.*?)" from accessing a cross-origin frame./;
expect(content).to.match(expectedContent);
});
it('emits a browser-window-created event', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/window-open.html`
});
await once(app, 'browser-window-created');
});
it('emits a web-contents-created event', async () => {
const webContentsCreated = emittedUntil(app, 'web-contents-created',
(event: Electron.Event, contents: Electron.WebContents) => contents.getType() === 'window');
loadWebView(w.webContents, {
allowpopups: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/window-open.html`
});
await webContentsCreated;
});
it('does not crash when creating window with noopener', async () => {
loadWebView(w.webContents, {
allowpopups: 'on',
src: `file://${path.join(fixtures, 'api', 'native-window-open-noopener.html')}`
});
await once(app, 'browser-window-created');
});
});
describe('webpreferences attribute', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true } });
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
it('can enable context isolation', async () => {
loadWebView(w.webContents, {
allowpopups: 'yes',
preload: `file://${fixtures}/api/isolated-preload.js`,
src: `file://${fixtures}/api/isolated.html`,
webpreferences: 'contextIsolation=yes'
});
const [, data] = await once(ipcMain, 'isolated-world');
expect(data).to.deep.equal({
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'
}
});
});
});
describe('permission request handlers', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
const partition = 'permissionTest';
function setUpRequestHandler (webContentsId: number, requestedPermission: string) {
return new Promise<void>((resolve, reject) => {
session.fromPartition(partition).setPermissionRequestHandler(function (webContents, permission, callback) {
if (webContents.id === webContentsId) {
// requestMIDIAccess with sysex requests both midi and midiSysex so
// grant the first midi one and then reject the midiSysex one
if (requestedPermission === 'midiSysex' && permission === 'midi') {
return callback(true);
}
try {
expect(permission).to.equal(requestedPermission);
} catch (e) {
return reject(e);
}
callback(false);
resolve();
}
});
});
}
afterEach(() => {
session.fromPartition(partition).setPermissionRequestHandler(null);
});
// This is disabled because CI machines don't have cameras or microphones,
// so Chrome responds with "NotFoundError" instead of
// "PermissionDeniedError". It should be re-enabled if we find a way to mock
// the presence of a microphone & camera.
xit('emits when using navigator.getUserMedia api', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/media.html`,
partition,
nodeintegration: 'on'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
setUpRequestHandler(webViewContents.id, 'media');
const [, errorName] = await errorFromRenderer;
expect(errorName).to.equal('PermissionDeniedError');
});
it('emits when using navigator.geolocation api', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/geolocation.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
setUpRequestHandler(webViewContents.id, 'geolocation');
const [, error] = await errorFromRenderer;
expect(error).to.equal('User denied Geolocation');
});
it('emits when using navigator.requestMIDIAccess without sysex api', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/midi.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
setUpRequestHandler(webViewContents.id, 'midi');
const [, error] = await errorFromRenderer;
expect(error).to.equal('SecurityError');
});
it('emits when using navigator.requestMIDIAccess with sysex api', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/midi-sysex.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
setUpRequestHandler(webViewContents.id, 'midiSysex');
const [, error] = await errorFromRenderer;
expect(error).to.equal('SecurityError');
});
it('emits when accessing external protocol', async () => {
loadWebView(w.webContents, {
src: 'magnet:test',
partition
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
await setUpRequestHandler(webViewContents.id, 'openExternal');
});
it('emits when using Notification.requestPermission', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/notification.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
await setUpRequestHandler(webViewContents.id, 'notifications');
const [, error] = await errorFromRenderer;
expect(error).to.equal('denied');
});
});
describe('DOM events', () => {
afterEach(closeAllWindows);
it('receives extra properties on DOM events when contextIsolation is enabled', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true
}
});
await w.loadURL('about:blank');
const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', 'data:text/html,<script>console.log("hi")</script>')
webview.addEventListener('console-message', (e) => {
resolve(e.message)
})
document.body.appendChild(webview)
})`);
expect(message).to.equal('hi');
});
it('emits focus event when contextIsolation is enabled', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true
}
});
await w.loadURL('about:blank');
await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', 'about:blank')
webview.addEventListener('dom-ready', () => {
webview.focus()
})
webview.addEventListener('focus', () => {
resolve();
})
document.body.appendChild(webview)
})`);
});
});
describe('attributes', () => {
let w: WebContents;
before(async () => {
const window = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
await window.loadURL(`file://${fixtures}/pages/blank.html`);
w = window.webContents;
});
afterEach(async () => {
await w.executeJavaScript(`{
for (const el of document.querySelectorAll('webview')) el.remove();
}`);
});
after(closeAllWindows);
describe('src attribute', () => {
it('specifies the page to load', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/a.html`
});
expect(message).to.equal('a');
});
it('navigates to new page when changed', async () => {
await loadWebView(w, {
src: `file://${fixtures}/pages/a.html`
});
const { message } = await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('console-message', e => resolve({message: e.message}))
webview.src = ${JSON.stringify(`file://${fixtures}/pages/b.html`)}
})`);
expect(message).to.equal('b');
});
it('resolves relative URLs', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
src: './e.html'
});
expect(message).to.equal('Window script is loaded before preload script');
});
it('ignores empty values', async () => {
loadWebView(w, {});
for (const emptyValue of ['""', 'null', 'undefined']) {
const src = await w.executeJavaScript(`webview.src = ${emptyValue}, webview.src`);
expect(src).to.equal('');
}
});
it('does not wait until loadURL is resolved', async () => {
await loadWebView(w, { src: 'about:blank' });
const delay = await w.executeJavaScript(`new Promise(resolve => {
const before = Date.now();
webview.src = 'file://${fixtures}/pages/blank.html';
const now = Date.now();
resolve(now - before);
})`);
// Setting src is essentially sending a sync IPC message, which should
// not exceed more than a few ms.
//
// This is for testing #18638.
expect(delay).to.be.below(100);
});
});
describe('nodeintegration attribute', () => {
it('inserts no node symbols when not set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/c.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'undefined',
module: 'undefined',
process: 'undefined',
global: 'undefined'
});
});
it('inserts node symbols when set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/d.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('loads node symbols after POST navigation when set', async function () {
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/post.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('disables node integration on child windows when it is disabled on the webview', async () => {
const src = url.format({
pathname: `${fixtures}/pages/webview-opener-no-node-integration.html`,
protocol: 'file',
query: {
p: `${fixtures}/pages/window-opener-node.html`
},
slashes: true
});
const message = await loadWebViewAndWaitForMessage(w, {
allowpopups: 'on',
webpreferences: 'contextIsolation=no',
src
});
expect(JSON.parse(message).isProcessGlobalUndefined).to.be.true();
});
ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native modules when navigation happens', async function () {
await loadWebView(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/native-module.html`
});
const message = await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('console-message', e => resolve(e.message))
webview.reload();
})`);
expect(message).to.equal('function');
});
});
describe('preload attribute', () => {
useRemoteContext({ webPreferences: { webviewTag: true } });
it('loads the script before other scripts in window', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload.js`,
src: `file://${fixtures}/pages/e.html`
});
expect(message).to.be.a('string');
expect(message).to.be.not.equal('Window script is loaded before preload script');
});
it('preload script can still use "process" and "Buffer" when nodeintegration is off', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload-node-off.js`,
src: `file://${fixtures}/api/blank.html`
});
const types = JSON.parse(message);
expect(types).to.include({
process: 'object',
Buffer: 'function'
});
});
it('runs in the correct scope when sandboxed', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload-context.js`,
src: `file://${fixtures}/api/blank.html`,
webpreferences: 'sandbox=yes'
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function', // arguments passed to it should be available
electron: 'undefined', // objects from the scope it is called from should not be available
window: 'object', // the window object should be available
localVar: 'undefined' // but local variables should not be exposed to the window
});
});
it('preload script can require modules that still use "process" and "Buffer" when nodeintegration is off', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload-node-off-wrapper.js`,
webpreferences: 'sandbox=no',
src: `file://${fixtures}/api/blank.html`
});
const types = JSON.parse(message);
expect(types).to.include({
process: 'object',
Buffer: 'function'
});
});
it('receives ipc message in preload script', async () => {
await loadWebView(w, {
preload: `${fixtures}/module/preload-ipc.js`,
src: `file://${fixtures}/pages/e.html`
});
const message = 'boom!';
const { channel, args } = await w.executeJavaScript(`new Promise(resolve => {
webview.send('ping', ${JSON.stringify(message)})
webview.addEventListener('ipc-message', ({channel, args}) => resolve({channel, args}))
})`);
expect(channel).to.equal('pong');
expect(args).to.deep.equal([message]);
});
itremote('<webview>.sendToFrame()', async (fixtures: string) => {
const w = new WebView();
w.setAttribute('nodeintegration', 'on');
w.setAttribute('webpreferences', 'contextIsolation=no');
w.setAttribute('preload', `file://${fixtures}/module/preload-ipc.js`);
w.setAttribute('src', `file://${fixtures}/pages/ipc-message.html`);
document.body.appendChild(w);
const { frameId } = await new Promise<any>(resolve => w.addEventListener('ipc-message', resolve, { once: true }));
const message = 'boom!';
w.sendToFrame(frameId, 'ping', message);
const { channel, args } = await new Promise<any>(resolve => w.addEventListener('ipc-message', resolve, { once: true }));
expect(channel).to.equal('pong');
expect(args).to.deep.equal([message]);
}, [fixtures]);
it('works without script tag in page', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload.js`,
webpreferences: 'sandbox=no',
src: `file://${fixtures}/pages/base-page.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object',
Buffer: 'function'
});
});
it('resolves relative URLs', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: '../module/preload.js',
webpreferences: 'sandbox=no',
src: `file://${fixtures}/pages/e.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object',
Buffer: 'function'
});
});
itremote('ignores empty values', async () => {
const webview = new WebView();
for (const emptyValue of ['', null, undefined]) {
webview.preload = emptyValue;
expect(webview.preload).to.equal('');
}
});
});
describe('httpreferrer attribute', () => {
it('sets the referrer url', async () => {
const referrer = 'http://github.com/';
const received = await new Promise<string | undefined>((resolve, reject) => {
const server = http.createServer((req, res) => {
try {
resolve(req.headers.referer);
} catch (e) {
reject(e);
} finally {
res.end();
server.close();
}
});
listen(server).then(({ url }) => {
loadWebView(w, {
httpreferrer: referrer,
src: url
});
});
});
expect(received).to.equal(referrer);
});
});
describe('useragent attribute', () => {
it('sets the user agent', async () => {
const referrer = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko';
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/useragent.html`,
useragent: referrer
});
expect(message).to.equal(referrer);
});
});
describe('disablewebsecurity attribute', () => {
it('does not disable web security when not set', async () => {
await loadWebView(w, { src: 'about:blank' });
const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`);
expect(result).to.equal('failed');
});
it('disables web security when set', async () => {
await loadWebView(w, { src: 'about:blank', disablewebsecurity: '' });
const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`);
expect(result).to.equal('ok');
});
it('does not break node integration', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
disablewebsecurity: '',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/d.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('does not break preload script', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
disablewebsecurity: '',
preload: `${fixtures}/module/preload.js`,
webpreferences: 'sandbox=no',
src: `file://${fixtures}/pages/e.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object',
Buffer: 'function'
});
});
});
describe('partition attribute', () => {
it('inserts no node symbols when not set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
partition: 'test1',
src: `file://${fixtures}/pages/c.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'undefined',
module: 'undefined',
process: 'undefined',
global: 'undefined'
});
});
it('inserts node symbols when set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'on',
partition: 'test2',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/d.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('isolates storage for different id', async () => {
await w.executeJavaScript('localStorage.setItem(\'test\', \'one\')');
const message = await loadWebViewAndWaitForMessage(w, {
partition: 'test3',
src: `file://${fixtures}/pages/partition/one.html`
});
const parsedMessage = JSON.parse(message);
expect(parsedMessage).to.include({
numberOfEntries: 0,
testValue: null
});
});
it('uses current session storage when no id is provided', async () => {
await w.executeJavaScript('localStorage.setItem(\'test\', \'two\')');
const testValue = 'two';
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/partition/one.html`
});
const parsedMessage = JSON.parse(message);
expect(parsedMessage).to.include({
testValue
});
});
});
describe('allowpopups attribute', () => {
const generateSpecs = (description: string, webpreferences = '') => {
describe(description, () => {
it('can not open new window when not set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
webpreferences,
src: `file://${fixtures}/pages/window-open-hide.html`
});
expect(message).to.equal('null');
});
it('can open new window when set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
webpreferences,
allowpopups: 'on',
src: `file://${fixtures}/pages/window-open-hide.html`
});
expect(message).to.equal('window');
});
});
};
generateSpecs('without sandbox');
generateSpecs('with sandbox', 'sandbox=yes');
});
describe('webpreferences attribute', () => {
it('can enable nodeintegration', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/d.html`,
webpreferences: 'nodeIntegration,contextIsolation=no'
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('can disable web security and enable nodeintegration', async () => {
await loadWebView(w, { src: 'about:blank', webpreferences: 'webSecurity=no, nodeIntegration=yes, contextIsolation=no' });
const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`);
expect(result).to.equal('ok');
const type = await w.executeJavaScript('webview.executeJavaScript("typeof require")');
expect(type).to.equal('function');
});
});
});
describe('events', () => {
useRemoteContext({ webPreferences: { webviewTag: true } });
let w: WebContents;
before(async () => {
const window = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
await window.loadURL(`file://${fixtures}/pages/blank.html`);
w = window.webContents;
});
afterEach(async () => {
await w.executeJavaScript(`{
for (const el of document.querySelectorAll('webview')) el.remove();
}`);
});
after(closeAllWindows);
describe('ipc-message event', () => {
it('emits when guest sends an ipc message to browser', async () => {
const { frameId, channel, args } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/ipc-message.html`,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
}, 'ipc-message');
expect(frameId).to.be.an('array').that.has.lengthOf(2);
expect(channel).to.equal('channel');
expect(args).to.deep.equal(['arg1', 'arg2']);
});
});
describe('page-title-updated event', () => {
it('emits when title is set', async () => {
const { title, explicitSet } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/a.html`
}, 'page-title-updated');
expect(title).to.equal('test');
expect(explicitSet).to.be.true();
});
});
describe('page-favicon-updated event', () => {
it('emits when favicon urls are received', async () => {
const { favicons } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/a.html`
}, 'page-favicon-updated');
expect(favicons).to.be.an('array').of.length(2);
if (process.platform === 'win32') {
expect(favicons[0]).to.match(/^file:\/\/\/[A-Z]:\/favicon.png$/i);
} else {
expect(favicons[0]).to.equal('file:///favicon.png');
}
});
});
describe('did-redirect-navigation event', () => {
it('is emitted on redirects', async () => {
const server = http.createServer((req, res) => {
if (req.url === '/302') {
res.setHeader('Location', '/200');
res.statusCode = 302;
res.end();
} else {
res.end();
}
});
const { url } = await listen(server);
defer(() => { server.close(); });
const event = await loadWebViewAndWaitForEvent(w, {
src: `${url}/302`
}, 'did-redirect-navigation');
expect(event.url).to.equal(`${url}/200`);
expect(event.isInPlace).to.be.false();
expect(event.isMainFrame).to.be.true();
expect(event.frameProcessId).to.be.a('number');
expect(event.frameRoutingId).to.be.a('number');
});
});
describe('will-navigate event', () => {
it('emits when a url that leads to outside of the page is loaded', async () => {
const { url } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/webview-will-navigate.html`
}, 'will-navigate');
expect(url).to.equal('http://host/');
});
});
describe('will-frame-navigate event', () => {
it('emits when a link that leads to outside of the page is loaded', async () => {
const { url, isMainFrame } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/webview-will-navigate.html`
}, 'will-frame-navigate');
expect(url).to.equal('http://host/');
expect(isMainFrame).to.be.true();
});
it('emits when a link within an iframe, which leads to outside of the page, is loaded', async () => {
await loadWebView(w, {
src: `file://${fixtures}/pages/webview-will-navigate-in-frame.html`,
nodeIntegration: ''
});
const { url, frameProcessId, frameRoutingId } = await w.executeJavaScript(`
new Promise((resolve, reject) => {
let hasFrameNavigatedOnce = false;
const webview = document.getElementById('webview');
webview.addEventListener('will-frame-navigate', ({url, isMainFrame, frameProcessId, frameRoutingId}) => {
if (isMainFrame) return;
if (hasFrameNavigatedOnce) resolve({
url,
isMainFrame,
frameProcessId,
frameRoutingId,
});
// First navigation is the initial iframe load within the <webview>
hasFrameNavigatedOnce = true;
});
webview.executeJavaScript('loadSubframe()');
});
`);
expect(url).to.equal('http://host/');
expect(frameProcessId).to.be.a('number');
expect(frameRoutingId).to.be.a('number');
});
});
describe('did-navigate event', () => {
it('emits when a url that leads to outside of the page is clicked', async () => {
const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-will-navigate.html')).toString();
const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate');
expect(event.url).to.equal(pageUrl);
});
});
describe('did-navigate-in-page event', () => {
it('emits when an anchor link is clicked', async () => {
const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-did-navigate-in-page.html')).toString();
const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate-in-page');
expect(event.url).to.equal(`${pageUrl}#test_content`);
});
it('emits when window.history.replaceState is called', async () => {
const { url } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/webview-did-navigate-in-page-with-history.html`
}, 'did-navigate-in-page');
expect(url).to.equal('http://host/');
});
it('emits when window.location.hash is changed', async () => {
const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-did-navigate-in-page-with-hash.html')).toString();
const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate-in-page');
expect(event.url).to.equal(`${pageUrl}#test`);
});
});
describe('close event', () => {
it('should fire when interior page calls window.close', async () => {
await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/close.html` }, 'close');
});
});
describe('devtools-opened event', () => {
it('should fire when webview.openDevTools() is called', async () => {
await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/base-page.html`
}, 'dom-ready');
await w.executeJavaScript(`new Promise((resolve) => {
webview.openDevTools()
webview.addEventListener('devtools-opened', () => resolve(), {once: true})
})`);
await w.executeJavaScript('webview.closeDevTools()');
});
});
describe('devtools-closed event', () => {
itremote('should fire when webview.closeDevTools() is called', async (fixtures: string) => {
const webview = new WebView();
webview.src = `file://${fixtures}/pages/base-page.html`;
document.body.appendChild(webview);
await new Promise(resolve => webview.addEventListener('dom-ready', resolve, { once: true }));
webview.openDevTools();
await new Promise(resolve => webview.addEventListener('devtools-opened', resolve, { once: true }));
webview.closeDevTools();
await new Promise(resolve => webview.addEventListener('devtools-closed', resolve, { once: true }));
}, [fixtures]);
});
describe('devtools-focused event', () => {
itremote('should fire when webview.openDevTools() is called', async (fixtures: string) => {
const webview = new WebView();
webview.src = `file://${fixtures}/pages/base-page.html`;
document.body.appendChild(webview);
const waitForDevToolsFocused = new Promise(resolve => webview.addEventListener('devtools-focused', resolve, { once: true }));
await new Promise(resolve => webview.addEventListener('dom-ready', resolve, { once: true }));
webview.openDevTools();
await waitForDevToolsFocused;
webview.closeDevTools();
}, [fixtures]);
});
describe('dom-ready event', () => {
it('emits when document is loaded', async () => {
const server = http.createServer(() => {});
const { port } = await listen(server);
await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/dom-ready.html?port=${port}`
}, 'dom-ready');
});
itremote('throws a custom error when an API method is called before the event is emitted', () => {
const expectedErrorMessage =
'The WebView must be attached to the DOM ' +
'and the dom-ready event emitted before this method can be called.';
const webview = new WebView();
expect(() => { webview.stop(); }).to.throw(expectedErrorMessage);
});
});
describe('context-menu event', () => {
it('emits when right-clicked in page', async () => {
await loadWebView(w, { src: 'about:blank' });
const { params, url } = await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('context-menu', (e) => resolve({...e, url: webview.getURL() }), {once: true})
// Simulate right-click to create context-menu event.
const opts = { x: 0, y: 0, button: 'right' };
webview.sendInputEvent({ ...opts, type: 'mouseDown' });
webview.sendInputEvent({ ...opts, type: 'mouseUp' });
})`);
expect(params.pageURL).to.equal(url);
expect(params.frame).to.be.undefined();
expect(params.x).to.be.a('number');
expect(params.y).to.be.a('number');
});
});
describe('found-in-page event', () => {
itremote('emits when a request is made', async (fixtures: string) => {
const webview = new WebView();
const didFinishLoad = new Promise(resolve => webview.addEventListener('did-finish-load', resolve, { once: true }));
webview.src = `file://${fixtures}/pages/content.html`;
document.body.appendChild(webview);
// TODO(deepak1556): With https://codereview.chromium.org/2836973002
// focus of the webContents is required when triggering the api.
// Remove this workaround after determining the cause for
// incorrect focus.
webview.focus();
await didFinishLoad;
const activeMatchOrdinal = [];
for (;;) {
const foundInPage = new Promise<any>(resolve => webview.addEventListener('found-in-page', resolve, { once: true }));
const requestId = webview.findInPage('virtual');
const event = await foundInPage;
expect(event.result.requestId).to.equal(requestId);
expect(event.result.matches).to.equal(3);
activeMatchOrdinal.push(event.result.activeMatchOrdinal);
if (event.result.activeMatchOrdinal === event.result.matches) {
break;
}
}
expect(activeMatchOrdinal).to.deep.equal([1, 2, 3]);
webview.stopFindInPage('clearSelection');
}, [fixtures]);
});
describe('will-attach-webview event', () => {
itremote('does not emit when src is not changed', async () => {
const webview = new WebView();
document.body.appendChild(webview);
await setTimeout();
const expectedErrorMessage = 'The WebView must be attached to the DOM and the dom-ready event emitted before this method can be called.';
expect(() => { webview.stop(); }).to.throw(expectedErrorMessage);
});
it('supports changing the web preferences', async () => {
w.once('will-attach-webview', (event, webPreferences, params) => {
params.src = `file://${path.join(fixtures, 'pages', 'c.html')}`;
webPreferences.nodeIntegration = false;
});
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'yes',
src: `file://${fixtures}/pages/a.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'undefined',
module: 'undefined',
process: 'undefined',
global: 'undefined'
});
});
it('handler modifying params.instanceId does not break <webview>', async () => {
w.once('will-attach-webview', (event, webPreferences, params) => {
params.instanceId = null as any;
});
await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/a.html`
});
});
it('supports preventing a webview from being created', async () => {
w.once('will-attach-webview', event => event.preventDefault());
await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/c.html`
}, 'destroyed');
});
it('supports removing the preload script', async () => {
w.once('will-attach-webview', (event, webPreferences, params) => {
params.src = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-stripped-preload.html')).toString();
delete webPreferences.preload;
});
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'yes',
preload: path.join(fixtures, 'module', 'preload-set-global.js'),
src: `file://${fixtures}/pages/a.html`
});
expect(message).to.equal('undefined');
});
});
describe('media-started-playing and media-paused events', () => {
it('emits when audio starts and stops playing', async function () {
if (!await w.executeJavaScript('document.createElement(\'audio\').canPlayType(\'audio/wav\')')) {
return this.skip();
}
await loadWebView(w, { src: blankPageUrl });
// With the new autoplay policy, audio elements must be unmuted
// see https://goo.gl/xX8pDD.
await w.executeJavaScript(`new Promise(resolve => {
webview.executeJavaScript(\`
const audio = document.createElement("audio")
audio.src = "../assets/tone.wav"
document.body.appendChild(audio);
audio.play()
\`, true)
webview.addEventListener('media-started-playing', () => resolve(), {once: true})
})`);
await w.executeJavaScript(`new Promise(resolve => {
webview.executeJavaScript(\`
document.querySelector("audio").pause()
\`, true)
webview.addEventListener('media-paused', () => resolve(), {once: true})
})`);
});
});
});
describe('methods', () => {
let w: WebContents;
before(async () => {
const window = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
await window.loadURL(`file://${fixtures}/pages/blank.html`);
w = window.webContents;
});
afterEach(async () => {
await w.executeJavaScript(`{
for (const el of document.querySelectorAll('webview')) el.remove();
}`);
});
after(closeAllWindows);
describe('<webview>.reload()', () => {
it('should emit beforeunload handler', async () => {
await loadWebView(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/beforeunload-false.html`
});
// Event handler has to be added before reload.
const channel = await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('ipc-message', e => resolve(e.channel))
webview.reload();
})`);
expect(channel).to.equal('onbeforeunload');
});
});
describe('<webview>.goForward()', () => {
useRemoteContext({ webPreferences: { webviewTag: true } });
itremote('should work after a replaced history entry', async (fixtures: string) => {
function waitForEvent (target: EventTarget, event: string) {
return new Promise<any>(resolve => target.addEventListener(event, resolve, { once: true }));
}
function waitForEvents (target: EventTarget, ...events: string[]) {
return Promise.all(events.map(event => waitForEvent(webview, event)));
}
const webview = new WebView();
webview.setAttribute('nodeintegration', 'on');
webview.setAttribute('webpreferences', 'contextIsolation=no');
webview.src = `file://${fixtures}/pages/history-replace.html`;
document.body.appendChild(webview);
{
const [e] = await waitForEvents(webview, 'ipc-message', 'did-stop-loading');
expect(e.channel).to.equal('history');
expect(e.args[0]).to.equal(1);
expect(webview.canGoBack()).to.be.false();
expect(webview.canGoForward()).to.be.false();
}
webview.src = `file://${fixtures}/pages/base-page.html`;
await new Promise<void>(resolve => webview.addEventListener('did-stop-loading', resolve, { once: true }));
expect(webview.canGoBack()).to.be.true();
expect(webview.canGoForward()).to.be.false();
webview.goBack();
{
const [e] = await waitForEvents(webview, 'ipc-message', 'did-stop-loading');
expect(e.channel).to.equal('history');
expect(e.args[0]).to.equal(2);
expect(webview.canGoBack()).to.be.false();
expect(webview.canGoForward()).to.be.true();
}
webview.goForward();
await new Promise<void>(resolve => webview.addEventListener('did-stop-loading', resolve, { once: true }));
expect(webview.canGoBack()).to.be.true();
expect(webview.canGoForward()).to.be.false();
}, [fixtures]);
});
describe('<webview>.clearHistory()', () => {
it('should clear the navigation history', async () => {
await loadWebView(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: blankPageUrl
});
// Navigation must be triggered by a user gesture to make canGoBack() return true
await w.executeJavaScript('webview.executeJavaScript(`history.pushState(null, "", "foo.html")`, true)');
expect(await w.executeJavaScript('webview.canGoBack()')).to.be.true();
await w.executeJavaScript('webview.clearHistory()');
expect(await w.executeJavaScript('webview.canGoBack()')).to.be.false();
});
});
describe('executeJavaScript', () => {
it('can return the result of the executed script', async () => {
await loadWebView(w, {
src: 'about:blank'
});
const jsScript = "'4'+2";
const expectedResult = '42';
const result = await w.executeJavaScript(`webview.executeJavaScript(${JSON.stringify(jsScript)})`);
expect(result).to.equal(expectedResult);
});
});
it('supports inserting CSS', async () => {
await loadWebView(w, { src: `file://${fixtures}/pages/base-page.html` });
await w.executeJavaScript('webview.insertCSS(\'body { background-repeat: round; }\')');
const result = await w.executeJavaScript('webview.executeJavaScript(\'window.getComputedStyle(document.body).getPropertyValue("background-repeat")\')');
expect(result).to.equal('round');
});
it('supports removing inserted CSS', async () => {
await loadWebView(w, { src: `file://${fixtures}/pages/base-page.html` });
const key = await w.executeJavaScript('webview.insertCSS(\'body { background-repeat: round; }\')');
await w.executeJavaScript(`webview.removeInsertedCSS(${JSON.stringify(key)})`);
const result = await w.executeJavaScript('webview.executeJavaScript(\'window.getComputedStyle(document.body).getPropertyValue("background-repeat")\')');
expect(result).to.equal('repeat');
});
describe('sendInputEvent', () => {
it('can send keyboard event', async () => {
await loadWebViewAndWaitForEvent(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/onkeyup.html`
}, 'dom-ready');
const waitForIpcMessage = w.executeJavaScript('new Promise(resolve => webview.addEventListener("ipc-message", e => resolve({...e})), {once: true})');
w.executeJavaScript(`webview.sendInputEvent({
type: 'keyup',
keyCode: 'c',
modifiers: ['shift']
})`);
const { channel, args } = await waitForIpcMessage;
expect(channel).to.equal('keyup');
expect(args).to.deep.equal(['C', 'KeyC', 67, true, false]);
});
it('can send mouse event', async () => {
await loadWebViewAndWaitForEvent(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/onmouseup.html`
}, 'dom-ready');
const waitForIpcMessage = w.executeJavaScript('new Promise(resolve => webview.addEventListener("ipc-message", e => resolve({...e})), {once: true})');
w.executeJavaScript(`webview.sendInputEvent({
type: 'mouseup',
modifiers: ['ctrl'],
x: 10,
y: 20
})`);
const { channel, args } = await waitForIpcMessage;
expect(channel).to.equal('mouseup');
expect(args).to.deep.equal([10, 20, false, true]);
});
});
describe('<webview>.getWebContentsId', () => {
it('can return the WebContents ID', async () => {
await loadWebView(w, { src: 'about:blank' });
expect(await w.executeJavaScript('webview.getWebContentsId()')).to.be.a('number');
});
});
ifdescribe(features.isPrintingEnabled())('<webview>.printToPDF()', () => {
it('rejects on incorrectly typed parameters', async () => {
const badTypes = {
landscape: [],
displayHeaderFooter: '123',
printBackground: 2,
scale: 'not-a-number',
pageSize: 'IAmAPageSize',
margins: 'terrible',
pageRanges: { oops: 'im-not-the-right-key' },
headerTemplate: [1, 2, 3],
footerTemplate: [4, 5, 6],
preferCSSPageSize: 'no'
};
// These will hard crash in Chromium unless we type-check
for (const [key, value] of Object.entries(badTypes)) {
const param = { [key]: value };
const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
await loadWebView(w, { src });
await expect(w.executeJavaScript(`webview.printToPDF(${JSON.stringify(param)})`)).to.eventually.be.rejected();
}
});
it('can print to PDF', async () => {
const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
await loadWebView(w, { src });
const data = await w.executeJavaScript('webview.printToPDF({})');
expect(data).to.be.an.instanceof(Uint8Array).that.is.not.empty();
});
});
describe('DOM events', () => {
for (const [description, sandbox] of [
['without sandbox', false] as const,
['with sandbox', true] as const
]) {
describe(description, () => {
it('emits focus event', async () => {
await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/a.html`,
webpreferences: `sandbox=${sandbox ? 'yes' : 'no'}`
}, 'dom-ready');
// If this test fails, check if webview.focus() still works.
await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('focus', () => resolve(), {once: true});
webview.focus();
})`);
});
});
}
});
// TODO(miniak): figure out why this is failing on windows
ifdescribe(process.platform !== 'win32')('<webview>.capturePage()', () => {
it('returns a Promise with a NativeImage', async () => {
const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
await loadWebViewAndWaitForEvent(w, { src }, 'did-stop-loading');
// Retry a few times due to flake.
for (let i = 0; i < 5; i++) {
try {
const image = await w.executeJavaScript('webview.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);
return;
} catch {
/* drop the error */
}
}
expect(false).to.be.true('could not successfully capture the page');
});
});
// FIXME(zcbenz): Disabled because of moving to OOPIF webview.
xdescribe('setDevToolsWebContents() API', () => {
/*
it('sets webContents of webview as devtools', async () => {
const webview2 = new WebView();
loadWebView(webview2);
// Setup an event handler for further usage.
const waitForDomReady = waitForEvent(webview2, 'dom-ready');
loadWebView(webview, { src: 'about:blank' });
await waitForEvent(webview, 'dom-ready');
webview.getWebContents().setDevToolsWebContents(webview2.getWebContents());
webview.getWebContents().openDevTools();
await waitForDomReady;
// Its WebContents should be a DevTools.
const devtools = webview2.getWebContents();
expect(devtools.getURL().startsWith('devtools://devtools')).to.be.true();
const name = await devtools.executeJavaScript('InspectorFrontendHost.constructor.name');
document.body.removeChild(webview2);
expect(name).to.be.equal('InspectorFrontendHostImpl');
});
*/
});
});
describe('basic auth', () => {
let w: WebContents;
before(async () => {
const window = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
await window.loadURL(`file://${fixtures}/pages/blank.html`);
w = window.webContents;
});
afterEach(async () => {
await w.executeJavaScript(`{
for (const el of document.querySelectorAll('webview')) el.remove();
}`);
});
after(closeAllWindows);
it('should authenticate with correct credentials', async () => {
const message = 'Authenticated';
const server = http.createServer((req, res) => {
const credentials = auth(req)!;
if (credentials.name === 'test' && credentials.pass === 'test') {
res.end(message);
} else {
res.end('failed');
}
});
defer(() => {
server.close();
});
const { port } = await listen(server);
const e = await loadWebViewAndWaitForEvent(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/basic-auth.html?port=${port}`
}, 'ipc-message');
expect(e.channel).to.equal(message);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,284 |
[Bug]: Unable to change file format in the openFile Dialog on Mac
|
### 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
27.0.0
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.5.2
### What arch are you using?
x64
### Last Known Working Electron version
27.0.0-nightly-20230803
### Expected Behavior
Can change the format:
<img width="649" alt="Screenshot 2023-10-20 at 12 53 48" src="https://github.com/electron/electron/assets/86096075/48d7faa9-6d8a-4360-9d40-bc8f68f76e2d">
### Actual Behavior
Can't change the format:
<img width="645" alt="Screenshot 2023-10-20 at 12 54 37" src="https://github.com/electron/electron/assets/86096075/3d8af0b1-0f40-4336-8325-37ba8b4f0282">
### Testcase Gist URL
_No response_
### Additional Information
Test code
```
// Display native system dialogs for opening and saving files, alerting, etc.
//
// For more info, see:
// https://electronjs.org/docs/api/dialog
const { app, BrowserWindow, dialog } = require('electron')
app.whenReady().then(() => {
const mainWindow = new BrowserWindow({ height: 600, width: 600 })
// Show an "Open File" dialog and attempt to open
// the chosen file in our window.
dialog.showOpenDialog({
properties: ['openFile'],
filters: [
{ name: 'Text files', extensions: ['txt'] },
{ name: 'All files', extensions: ['*']}
],
title: 'hello',
buttonLabel: 'show options',
}).then(result => {
if (result.canceled) {
console.log('Dialog was canceled')
} else {
const file = result.filePaths[0]
mainWindow.loadURL(`file://${file}`)
}
}).catch(err => {
console.log(err)
})
})
```
|
https://github.com/electron/electron/issues/40284
|
https://github.com/electron/electron/pull/40308
|
621b3ba897031319c214246ef6291ad1d3523f07
|
3f92a983156daa4e4c4d8ab7c7df90d861da2374
| 2023-10-20T04:55:11Z |
c++
| 2023-10-26T15:40:02Z |
shell/browser/ui/file_dialog_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/ui/file_dialog.h"
#include <string>
#include <utility>
#include <vector>
#import <Cocoa/Cocoa.h>
#import <CoreServices/CoreServices.h>
#include "base/apple/foundation_util.h"
#include "base/apple/scoped_cftyperef.h"
#include "base/files/file_util.h"
#include "base/mac/mac_util.h"
#include "base/strings/sys_string_conversions.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "shell/browser/native_window.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/thread_restrictions.h"
@interface PopUpButtonHandler : NSObject
@property(nonatomic, assign) NSSavePanel* savePanel;
@property(nonatomic, strong) NSArray* fileTypesList;
- (instancetype)initWithPanel:(NSSavePanel*)panel
andTypesList:(NSArray*)typesList;
- (void)selectFormat:(id)sender;
@end
@implementation PopUpButtonHandler
@synthesize savePanel;
@synthesize fileTypesList;
- (instancetype)initWithPanel:(NSSavePanel*)panel
andTypesList:(NSArray*)typesList {
self = [super init];
if (self) {
[self setSavePanel:panel];
[self setFileTypesList:typesList];
}
return self;
}
- (void)selectFormat:(id)sender {
NSPopUpButton* button = (NSPopUpButton*)sender;
NSInteger selectedItemIndex = [button indexOfSelectedItem];
NSArray* list = [self fileTypesList];
NSArray* fileTypes = [list objectAtIndex:selectedItemIndex];
// If we meet a '*' file extension, we allow all the file types and no
// need to set the specified file types.
if ([fileTypes count] == 0 || [fileTypes containsObject:@"*"])
[[self savePanel] setAllowedFileTypes:nil];
else
[[self savePanel] setAllowedFileTypes:fileTypes];
}
@end
// Manages the PopUpButtonHandler.
@interface ElectronAccessoryView : NSView
@end
@implementation ElectronAccessoryView
- (void)dealloc {
auto* popupButton =
static_cast<NSPopUpButton*>([[self subviews] objectAtIndex:1]);
popupButton.target = nil;
}
@end
namespace file_dialog {
DialogSettings::DialogSettings() = default;
DialogSettings::DialogSettings(const DialogSettings&) = default;
DialogSettings::~DialogSettings() = default;
namespace {
void SetAllowedFileTypes(NSSavePanel* dialog, const Filters& filters) {
NSMutableArray* file_types_list = [NSMutableArray array];
NSMutableArray* filter_names = [NSMutableArray array];
// Create array to keep file types and their name.
for (const Filter& filter : filters) {
NSMutableOrderedSet* file_type_set =
[NSMutableOrderedSet orderedSetWithCapacity:filters.size()];
[filter_names addObject:@(filter.first.c_str())];
for (std::string ext : filter.second) {
// macOS is incapable of understanding multiple file extensions,
// so we need to tokenize the extension that's been passed in.
// We want to err on the side of allowing files, so we pass
// along only the final extension ('tar.gz' => 'gz').
auto pos = ext.rfind('.');
if (pos != std::string::npos) {
ext.erase(0, pos + 1);
}
[file_type_set addObject:@(ext.c_str())];
}
[file_types_list addObject:[file_type_set array]];
}
// Passing empty array to setAllowedFileTypes will cause exception.
NSArray* file_types = nil;
NSUInteger count = [file_types_list count];
if (count > 0) {
file_types = [[file_types_list objectAtIndex:0] allObjects];
// If we meet a '*' file extension, we allow all the file types and no
// need to set the specified file types.
if ([file_types count] == 0 || [file_types containsObject:@"*"])
file_types = nil;
}
[dialog setAllowedFileTypes:file_types];
if (count <= 1)
return; // don't add file format picker
// Add file format picker.
ElectronAccessoryView* accessoryView = [[ElectronAccessoryView alloc]
initWithFrame:NSMakeRect(0.0, 0.0, 200, 32.0)];
NSTextField* label =
[[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 60, 22)];
[label setEditable:NO];
[label setStringValue:@"Format:"];
[label setBordered:NO];
[label setBezeled:NO];
[label setDrawsBackground:NO];
NSPopUpButton* popupButton =
[[NSPopUpButton alloc] initWithFrame:NSMakeRect(50.0, 2, 140, 22.0)
pullsDown:NO];
PopUpButtonHandler* popUpButtonHandler =
[[PopUpButtonHandler alloc] initWithPanel:dialog
andTypesList:file_types_list];
[popupButton addItemsWithTitles:filter_names];
[popupButton setTarget:popUpButtonHandler];
[popupButton setAction:@selector(selectFormat:)];
[accessoryView addSubview:label];
[accessoryView addSubview:popupButton];
[dialog setAccessoryView:accessoryView];
}
void SetupDialog(NSSavePanel* dialog, const DialogSettings& settings) {
if (!settings.title.empty())
[dialog setTitle:base::SysUTF8ToNSString(settings.title)];
if (!settings.button_label.empty())
[dialog setPrompt:base::SysUTF8ToNSString(settings.button_label)];
if (!settings.message.empty())
[dialog setMessage:base::SysUTF8ToNSString(settings.message)];
if (!settings.name_field_label.empty())
[dialog
setNameFieldLabel:base::SysUTF8ToNSString(settings.name_field_label)];
[dialog setShowsTagField:settings.shows_tag_field];
NSString* default_dir = nil;
NSString* default_filename = nil;
if (!settings.default_path.empty()) {
electron::ScopedAllowBlockingForElectron allow_blocking;
if (base::DirectoryExists(settings.default_path)) {
default_dir = base::SysUTF8ToNSString(settings.default_path.value());
} else {
if (settings.default_path.IsAbsolute()) {
default_dir =
base::SysUTF8ToNSString(settings.default_path.DirName().value());
}
default_filename =
base::SysUTF8ToNSString(settings.default_path.BaseName().value());
}
}
if (settings.filters.empty()) {
[dialog setAllowsOtherFileTypes:YES];
} else {
// Set setAllowedFileTypes before setNameFieldStringValue as it might
// override the extension set using setNameFieldStringValue
SetAllowedFileTypes(dialog, settings.filters);
}
// Make sure the extension is always visible. Without this, the extension in
// the default filename will not be used in the saved file.
[dialog setExtensionHidden:NO];
if (default_dir)
[dialog setDirectoryURL:[NSURL fileURLWithPath:default_dir]];
if (default_filename)
[dialog setNameFieldStringValue:default_filename];
}
void SetupOpenDialogForProperties(NSOpenPanel* dialog, int properties) {
[dialog setCanChooseFiles:(properties & OPEN_DIALOG_OPEN_FILE)];
if (properties & OPEN_DIALOG_OPEN_DIRECTORY)
[dialog setCanChooseDirectories:YES];
if (properties & OPEN_DIALOG_CREATE_DIRECTORY)
[dialog setCanCreateDirectories:YES];
if (properties & OPEN_DIALOG_MULTI_SELECTIONS)
[dialog setAllowsMultipleSelection:YES];
if (properties & OPEN_DIALOG_SHOW_HIDDEN_FILES)
[dialog setShowsHiddenFiles:YES];
if (properties & OPEN_DIALOG_NO_RESOLVE_ALIASES)
[dialog setResolvesAliases:NO];
if (properties & OPEN_DIALOG_TREAT_PACKAGE_APP_AS_DIRECTORY)
[dialog setTreatsFilePackagesAsDirectories:YES];
}
void SetupSaveDialogForProperties(NSSavePanel* dialog, int properties) {
if (properties & SAVE_DIALOG_CREATE_DIRECTORY)
[dialog setCanCreateDirectories:YES];
if (properties & SAVE_DIALOG_SHOW_HIDDEN_FILES)
[dialog setShowsHiddenFiles:YES];
if (properties & SAVE_DIALOG_TREAT_PACKAGE_APP_AS_DIRECTORY)
[dialog setTreatsFilePackagesAsDirectories:YES];
}
// Run modal dialog with parent window and return user's choice.
int RunModalDialog(NSSavePanel* dialog, const DialogSettings& settings) {
__block int chosen = NSModalResponseCancel;
if (!settings.parent_window || !settings.parent_window->GetNativeWindow() ||
settings.force_detached) {
chosen = [dialog runModal];
} else {
NSWindow* window =
settings.parent_window->GetNativeWindow().GetNativeNSWindow();
[dialog beginSheetModalForWindow:window
completionHandler:^(NSInteger c) {
chosen = c;
[NSApp stopModal];
}];
[NSApp runModalForWindow:window];
}
return chosen;
}
// Create bookmark data and serialise it into a base64 string.
std::string GetBookmarkDataFromNSURL(NSURL* url) {
// Create the file if it doesn't exist (necessary for NSSavePanel options).
NSFileManager* defaultManager = [NSFileManager defaultManager];
if (![defaultManager fileExistsAtPath:[url path]]) {
[defaultManager createFileAtPath:[url path] contents:nil attributes:nil];
}
NSError* error = nil;
NSData* bookmarkData =
[url bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope
includingResourceValuesForKeys:nil
relativeToURL:nil
error:&error];
if (error != nil) {
// Send back an empty string if there was an error.
return "";
} else {
// Encode NSData in base64 then convert to NSString.
NSString* base64data = [[NSString alloc]
initWithData:[bookmarkData base64EncodedDataWithOptions:0]
encoding:NSUTF8StringEncoding];
return base::SysNSStringToUTF8(base64data);
}
}
void ReadDialogPathsWithBookmarks(NSOpenPanel* dialog,
std::vector<base::FilePath>* paths,
std::vector<std::string>* bookmarks) {
NSArray* urls = [dialog URLs];
for (NSURL* url in urls) {
if (![url isFileURL])
continue;
NSString* path = [url path];
// There's a bug in macOS where despite a request to disallow file
// selection, files/packages can be selected. If file selection
// was disallowed, drop any files selected. See crbug.com/1357523.
if (![dialog canChooseFiles]) {
BOOL is_directory;
BOOL exists =
[[NSFileManager defaultManager] fileExistsAtPath:path
isDirectory:&is_directory];
BOOL is_package =
[[NSWorkspace sharedWorkspace] isFilePackageAtPath:path];
if (!exists || !is_directory || is_package)
continue;
}
paths->emplace_back(base::SysNSStringToUTF8(path));
bookmarks->push_back(GetBookmarkDataFromNSURL(url));
}
}
void ReadDialogPaths(NSOpenPanel* dialog, std::vector<base::FilePath>* paths) {
std::vector<std::string> ignored_bookmarks;
ReadDialogPathsWithBookmarks(dialog, paths, &ignored_bookmarks);
}
void ResolvePromiseInNextTick(gin_helper::Promise<v8::Local<v8::Value>> promise,
v8::Local<v8::Value> value) {
// The completionHandler runs inside a transaction commit, and we should
// not do any runModal inside it. However since we can not control what
// users will run in the microtask, we have to delay the resolution until
// next tick, otherwise crash like this may happen:
// https://github.com/electron/electron/issues/26884
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(
[](gin_helper::Promise<v8::Local<v8::Value>> promise,
v8::Global<v8::Value> global) {
v8::Isolate* isolate = promise.isolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Value> value = global.Get(isolate);
promise.Resolve(value);
},
std::move(promise), v8::Global<v8::Value>(promise.isolate(), value)));
}
} // namespace
bool ShowOpenDialogSync(const DialogSettings& settings,
std::vector<base::FilePath>* paths) {
DCHECK(paths);
NSOpenPanel* dialog = [NSOpenPanel openPanel];
SetupDialog(dialog, settings);
SetupOpenDialogForProperties(dialog, settings.properties);
int chosen = RunModalDialog(dialog, settings);
if (chosen == NSModalResponseCancel)
return false;
ReadDialogPaths(dialog, paths);
return true;
}
void OpenDialogCompletion(int chosen,
NSOpenPanel* dialog,
bool security_scoped_bookmarks,
gin_helper::Promise<gin_helper::Dictionary> promise) {
v8::HandleScope scope(promise.isolate());
auto dict = gin_helper::Dictionary::CreateEmpty(promise.isolate());
if (chosen == NSModalResponseCancel) {
dict.Set("canceled", true);
dict.Set("filePaths", std::vector<base::FilePath>());
#if IS_MAS_BUILD()
dict.Set("bookmarks", std::vector<std::string>());
#endif
} else {
std::vector<base::FilePath> paths;
dict.Set("canceled", false);
#if IS_MAS_BUILD()
std::vector<std::string> bookmarks;
if (security_scoped_bookmarks)
ReadDialogPathsWithBookmarks(dialog, &paths, &bookmarks);
else
ReadDialogPaths(dialog, &paths);
dict.Set("filePaths", paths);
dict.Set("bookmarks", bookmarks);
#else
ReadDialogPaths(dialog, &paths);
dict.Set("filePaths", paths);
#endif
}
ResolvePromiseInNextTick(promise.As<v8::Local<v8::Value>>(),
dict.GetHandle());
}
void ShowOpenDialog(const DialogSettings& settings,
gin_helper::Promise<gin_helper::Dictionary> promise) {
NSOpenPanel* dialog = [NSOpenPanel openPanel];
SetupDialog(dialog, settings);
SetupOpenDialogForProperties(dialog, settings.properties);
// Capture the value of the security_scoped_bookmarks settings flag
// and pass it to the completion handler.
bool security_scoped_bookmarks = settings.security_scoped_bookmarks;
__block gin_helper::Promise<gin_helper::Dictionary> p = std::move(promise);
if (!settings.parent_window || !settings.parent_window->GetNativeWindow() ||
settings.force_detached) {
[dialog beginWithCompletionHandler:^(NSInteger chosen) {
OpenDialogCompletion(chosen, dialog, security_scoped_bookmarks,
std::move(p));
}];
} else {
NSWindow* window =
settings.parent_window->GetNativeWindow().GetNativeNSWindow();
[dialog
beginSheetModalForWindow:window
completionHandler:^(NSInteger chosen) {
OpenDialogCompletion(chosen, dialog, security_scoped_bookmarks,
std::move(p));
}];
}
}
bool ShowSaveDialogSync(const DialogSettings& settings, base::FilePath* path) {
DCHECK(path);
NSSavePanel* dialog = [NSSavePanel savePanel];
SetupDialog(dialog, settings);
SetupSaveDialogForProperties(dialog, settings.properties);
int chosen = RunModalDialog(dialog, settings);
if (chosen == NSModalResponseCancel || ![[dialog URL] isFileURL])
return false;
*path = base::FilePath(base::SysNSStringToUTF8([[dialog URL] path]));
return true;
}
void SaveDialogCompletion(int chosen,
NSSavePanel* dialog,
bool security_scoped_bookmarks,
gin_helper::Promise<gin_helper::Dictionary> promise) {
v8::HandleScope scope(promise.isolate());
auto dict = gin_helper::Dictionary::CreateEmpty(promise.isolate());
if (chosen == NSModalResponseCancel) {
dict.Set("canceled", true);
dict.Set("filePath", base::FilePath());
#if IS_MAS_BUILD()
dict.Set("bookmark", base::StringPiece());
#endif
} else {
std::string path = base::SysNSStringToUTF8([[dialog URL] path]);
dict.Set("filePath", base::FilePath(path));
dict.Set("canceled", false);
#if IS_MAS_BUILD()
std::string bookmark;
if (security_scoped_bookmarks) {
bookmark = GetBookmarkDataFromNSURL([dialog URL]);
dict.Set("bookmark", bookmark);
}
#endif
}
ResolvePromiseInNextTick(promise.As<v8::Local<v8::Value>>(),
dict.GetHandle());
}
void ShowSaveDialog(const DialogSettings& settings,
gin_helper::Promise<gin_helper::Dictionary> promise) {
NSSavePanel* dialog = [NSSavePanel savePanel];
SetupDialog(dialog, settings);
SetupSaveDialogForProperties(dialog, settings.properties);
[dialog setCanSelectHiddenExtension:YES];
// Capture the value of the security_scoped_bookmarks settings flag
// and pass it to the completion handler.
bool security_scoped_bookmarks = settings.security_scoped_bookmarks;
__block gin_helper::Promise<gin_helper::Dictionary> p = std::move(promise);
if (!settings.parent_window || !settings.parent_window->GetNativeWindow() ||
settings.force_detached) {
[dialog beginWithCompletionHandler:^(NSInteger chosen) {
SaveDialogCompletion(chosen, dialog, security_scoped_bookmarks,
std::move(p));
}];
} else {
NSWindow* window =
settings.parent_window->GetNativeWindow().GetNativeNSWindow();
[dialog
beginSheetModalForWindow:window
completionHandler:^(NSInteger chosen) {
SaveDialogCompletion(chosen, dialog, security_scoped_bookmarks,
std::move(p));
}];
}
}
} // namespace file_dialog
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,284 |
[Bug]: Unable to change file format in the openFile Dialog on Mac
|
### 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
27.0.0
### What operating system are you using?
macOS
### Operating System Version
macOS Ventura 13.5.2
### What arch are you using?
x64
### Last Known Working Electron version
27.0.0-nightly-20230803
### Expected Behavior
Can change the format:
<img width="649" alt="Screenshot 2023-10-20 at 12 53 48" src="https://github.com/electron/electron/assets/86096075/48d7faa9-6d8a-4360-9d40-bc8f68f76e2d">
### Actual Behavior
Can't change the format:
<img width="645" alt="Screenshot 2023-10-20 at 12 54 37" src="https://github.com/electron/electron/assets/86096075/3d8af0b1-0f40-4336-8325-37ba8b4f0282">
### Testcase Gist URL
_No response_
### Additional Information
Test code
```
// Display native system dialogs for opening and saving files, alerting, etc.
//
// For more info, see:
// https://electronjs.org/docs/api/dialog
const { app, BrowserWindow, dialog } = require('electron')
app.whenReady().then(() => {
const mainWindow = new BrowserWindow({ height: 600, width: 600 })
// Show an "Open File" dialog and attempt to open
// the chosen file in our window.
dialog.showOpenDialog({
properties: ['openFile'],
filters: [
{ name: 'Text files', extensions: ['txt'] },
{ name: 'All files', extensions: ['*']}
],
title: 'hello',
buttonLabel: 'show options',
}).then(result => {
if (result.canceled) {
console.log('Dialog was canceled')
} else {
const file = result.filePaths[0]
mainWindow.loadURL(`file://${file}`)
}
}).catch(err => {
console.log(err)
})
})
```
|
https://github.com/electron/electron/issues/40284
|
https://github.com/electron/electron/pull/40308
|
621b3ba897031319c214246ef6291ad1d3523f07
|
3f92a983156daa4e4c4d8ab7c7df90d861da2374
| 2023-10-20T04:55:11Z |
c++
| 2023-10-26T15:40:02Z |
shell/browser/ui/file_dialog_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/ui/file_dialog.h"
#include <string>
#include <utility>
#include <vector>
#import <Cocoa/Cocoa.h>
#import <CoreServices/CoreServices.h>
#include "base/apple/foundation_util.h"
#include "base/apple/scoped_cftyperef.h"
#include "base/files/file_util.h"
#include "base/mac/mac_util.h"
#include "base/strings/sys_string_conversions.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "shell/browser/native_window.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/thread_restrictions.h"
@interface PopUpButtonHandler : NSObject
@property(nonatomic, assign) NSSavePanel* savePanel;
@property(nonatomic, strong) NSArray* fileTypesList;
- (instancetype)initWithPanel:(NSSavePanel*)panel
andTypesList:(NSArray*)typesList;
- (void)selectFormat:(id)sender;
@end
@implementation PopUpButtonHandler
@synthesize savePanel;
@synthesize fileTypesList;
- (instancetype)initWithPanel:(NSSavePanel*)panel
andTypesList:(NSArray*)typesList {
self = [super init];
if (self) {
[self setSavePanel:panel];
[self setFileTypesList:typesList];
}
return self;
}
- (void)selectFormat:(id)sender {
NSPopUpButton* button = (NSPopUpButton*)sender;
NSInteger selectedItemIndex = [button indexOfSelectedItem];
NSArray* list = [self fileTypesList];
NSArray* fileTypes = [list objectAtIndex:selectedItemIndex];
// If we meet a '*' file extension, we allow all the file types and no
// need to set the specified file types.
if ([fileTypes count] == 0 || [fileTypes containsObject:@"*"])
[[self savePanel] setAllowedFileTypes:nil];
else
[[self savePanel] setAllowedFileTypes:fileTypes];
}
@end
// Manages the PopUpButtonHandler.
@interface ElectronAccessoryView : NSView
@end
@implementation ElectronAccessoryView
- (void)dealloc {
auto* popupButton =
static_cast<NSPopUpButton*>([[self subviews] objectAtIndex:1]);
popupButton.target = nil;
}
@end
namespace file_dialog {
DialogSettings::DialogSettings() = default;
DialogSettings::DialogSettings(const DialogSettings&) = default;
DialogSettings::~DialogSettings() = default;
namespace {
void SetAllowedFileTypes(NSSavePanel* dialog, const Filters& filters) {
NSMutableArray* file_types_list = [NSMutableArray array];
NSMutableArray* filter_names = [NSMutableArray array];
// Create array to keep file types and their name.
for (const Filter& filter : filters) {
NSMutableOrderedSet* file_type_set =
[NSMutableOrderedSet orderedSetWithCapacity:filters.size()];
[filter_names addObject:@(filter.first.c_str())];
for (std::string ext : filter.second) {
// macOS is incapable of understanding multiple file extensions,
// so we need to tokenize the extension that's been passed in.
// We want to err on the side of allowing files, so we pass
// along only the final extension ('tar.gz' => 'gz').
auto pos = ext.rfind('.');
if (pos != std::string::npos) {
ext.erase(0, pos + 1);
}
[file_type_set addObject:@(ext.c_str())];
}
[file_types_list addObject:[file_type_set array]];
}
// Passing empty array to setAllowedFileTypes will cause exception.
NSArray* file_types = nil;
NSUInteger count = [file_types_list count];
if (count > 0) {
file_types = [[file_types_list objectAtIndex:0] allObjects];
// If we meet a '*' file extension, we allow all the file types and no
// need to set the specified file types.
if ([file_types count] == 0 || [file_types containsObject:@"*"])
file_types = nil;
}
[dialog setAllowedFileTypes:file_types];
if (count <= 1)
return; // don't add file format picker
// Add file format picker.
ElectronAccessoryView* accessoryView = [[ElectronAccessoryView alloc]
initWithFrame:NSMakeRect(0.0, 0.0, 200, 32.0)];
NSTextField* label =
[[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 60, 22)];
[label setEditable:NO];
[label setStringValue:@"Format:"];
[label setBordered:NO];
[label setBezeled:NO];
[label setDrawsBackground:NO];
NSPopUpButton* popupButton =
[[NSPopUpButton alloc] initWithFrame:NSMakeRect(50.0, 2, 140, 22.0)
pullsDown:NO];
PopUpButtonHandler* popUpButtonHandler =
[[PopUpButtonHandler alloc] initWithPanel:dialog
andTypesList:file_types_list];
[popupButton addItemsWithTitles:filter_names];
[popupButton setTarget:popUpButtonHandler];
[popupButton setAction:@selector(selectFormat:)];
[accessoryView addSubview:label];
[accessoryView addSubview:popupButton];
[dialog setAccessoryView:accessoryView];
}
void SetupDialog(NSSavePanel* dialog, const DialogSettings& settings) {
if (!settings.title.empty())
[dialog setTitle:base::SysUTF8ToNSString(settings.title)];
if (!settings.button_label.empty())
[dialog setPrompt:base::SysUTF8ToNSString(settings.button_label)];
if (!settings.message.empty())
[dialog setMessage:base::SysUTF8ToNSString(settings.message)];
if (!settings.name_field_label.empty())
[dialog
setNameFieldLabel:base::SysUTF8ToNSString(settings.name_field_label)];
[dialog setShowsTagField:settings.shows_tag_field];
NSString* default_dir = nil;
NSString* default_filename = nil;
if (!settings.default_path.empty()) {
electron::ScopedAllowBlockingForElectron allow_blocking;
if (base::DirectoryExists(settings.default_path)) {
default_dir = base::SysUTF8ToNSString(settings.default_path.value());
} else {
if (settings.default_path.IsAbsolute()) {
default_dir =
base::SysUTF8ToNSString(settings.default_path.DirName().value());
}
default_filename =
base::SysUTF8ToNSString(settings.default_path.BaseName().value());
}
}
if (settings.filters.empty()) {
[dialog setAllowsOtherFileTypes:YES];
} else {
// Set setAllowedFileTypes before setNameFieldStringValue as it might
// override the extension set using setNameFieldStringValue
SetAllowedFileTypes(dialog, settings.filters);
}
// Make sure the extension is always visible. Without this, the extension in
// the default filename will not be used in the saved file.
[dialog setExtensionHidden:NO];
if (default_dir)
[dialog setDirectoryURL:[NSURL fileURLWithPath:default_dir]];
if (default_filename)
[dialog setNameFieldStringValue:default_filename];
}
void SetupOpenDialogForProperties(NSOpenPanel* dialog, int properties) {
[dialog setCanChooseFiles:(properties & OPEN_DIALOG_OPEN_FILE)];
if (properties & OPEN_DIALOG_OPEN_DIRECTORY)
[dialog setCanChooseDirectories:YES];
if (properties & OPEN_DIALOG_CREATE_DIRECTORY)
[dialog setCanCreateDirectories:YES];
if (properties & OPEN_DIALOG_MULTI_SELECTIONS)
[dialog setAllowsMultipleSelection:YES];
if (properties & OPEN_DIALOG_SHOW_HIDDEN_FILES)
[dialog setShowsHiddenFiles:YES];
if (properties & OPEN_DIALOG_NO_RESOLVE_ALIASES)
[dialog setResolvesAliases:NO];
if (properties & OPEN_DIALOG_TREAT_PACKAGE_APP_AS_DIRECTORY)
[dialog setTreatsFilePackagesAsDirectories:YES];
}
void SetupSaveDialogForProperties(NSSavePanel* dialog, int properties) {
if (properties & SAVE_DIALOG_CREATE_DIRECTORY)
[dialog setCanCreateDirectories:YES];
if (properties & SAVE_DIALOG_SHOW_HIDDEN_FILES)
[dialog setShowsHiddenFiles:YES];
if (properties & SAVE_DIALOG_TREAT_PACKAGE_APP_AS_DIRECTORY)
[dialog setTreatsFilePackagesAsDirectories:YES];
}
// Run modal dialog with parent window and return user's choice.
int RunModalDialog(NSSavePanel* dialog, const DialogSettings& settings) {
__block int chosen = NSModalResponseCancel;
if (!settings.parent_window || !settings.parent_window->GetNativeWindow() ||
settings.force_detached) {
chosen = [dialog runModal];
} else {
NSWindow* window =
settings.parent_window->GetNativeWindow().GetNativeNSWindow();
[dialog beginSheetModalForWindow:window
completionHandler:^(NSInteger c) {
chosen = c;
[NSApp stopModal];
}];
[NSApp runModalForWindow:window];
}
return chosen;
}
// Create bookmark data and serialise it into a base64 string.
std::string GetBookmarkDataFromNSURL(NSURL* url) {
// Create the file if it doesn't exist (necessary for NSSavePanel options).
NSFileManager* defaultManager = [NSFileManager defaultManager];
if (![defaultManager fileExistsAtPath:[url path]]) {
[defaultManager createFileAtPath:[url path] contents:nil attributes:nil];
}
NSError* error = nil;
NSData* bookmarkData =
[url bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope
includingResourceValuesForKeys:nil
relativeToURL:nil
error:&error];
if (error != nil) {
// Send back an empty string if there was an error.
return "";
} else {
// Encode NSData in base64 then convert to NSString.
NSString* base64data = [[NSString alloc]
initWithData:[bookmarkData base64EncodedDataWithOptions:0]
encoding:NSUTF8StringEncoding];
return base::SysNSStringToUTF8(base64data);
}
}
void ReadDialogPathsWithBookmarks(NSOpenPanel* dialog,
std::vector<base::FilePath>* paths,
std::vector<std::string>* bookmarks) {
NSArray* urls = [dialog URLs];
for (NSURL* url in urls) {
if (![url isFileURL])
continue;
NSString* path = [url path];
// There's a bug in macOS where despite a request to disallow file
// selection, files/packages can be selected. If file selection
// was disallowed, drop any files selected. See crbug.com/1357523.
if (![dialog canChooseFiles]) {
BOOL is_directory;
BOOL exists =
[[NSFileManager defaultManager] fileExistsAtPath:path
isDirectory:&is_directory];
BOOL is_package =
[[NSWorkspace sharedWorkspace] isFilePackageAtPath:path];
if (!exists || !is_directory || is_package)
continue;
}
paths->emplace_back(base::SysNSStringToUTF8(path));
bookmarks->push_back(GetBookmarkDataFromNSURL(url));
}
}
void ReadDialogPaths(NSOpenPanel* dialog, std::vector<base::FilePath>* paths) {
std::vector<std::string> ignored_bookmarks;
ReadDialogPathsWithBookmarks(dialog, paths, &ignored_bookmarks);
}
void ResolvePromiseInNextTick(gin_helper::Promise<v8::Local<v8::Value>> promise,
v8::Local<v8::Value> value) {
// The completionHandler runs inside a transaction commit, and we should
// not do any runModal inside it. However since we can not control what
// users will run in the microtask, we have to delay the resolution until
// next tick, otherwise crash like this may happen:
// https://github.com/electron/electron/issues/26884
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(
[](gin_helper::Promise<v8::Local<v8::Value>> promise,
v8::Global<v8::Value> global) {
v8::Isolate* isolate = promise.isolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Value> value = global.Get(isolate);
promise.Resolve(value);
},
std::move(promise), v8::Global<v8::Value>(promise.isolate(), value)));
}
} // namespace
bool ShowOpenDialogSync(const DialogSettings& settings,
std::vector<base::FilePath>* paths) {
DCHECK(paths);
NSOpenPanel* dialog = [NSOpenPanel openPanel];
SetupDialog(dialog, settings);
SetupOpenDialogForProperties(dialog, settings.properties);
int chosen = RunModalDialog(dialog, settings);
if (chosen == NSModalResponseCancel)
return false;
ReadDialogPaths(dialog, paths);
return true;
}
void OpenDialogCompletion(int chosen,
NSOpenPanel* dialog,
bool security_scoped_bookmarks,
gin_helper::Promise<gin_helper::Dictionary> promise) {
v8::HandleScope scope(promise.isolate());
auto dict = gin_helper::Dictionary::CreateEmpty(promise.isolate());
if (chosen == NSModalResponseCancel) {
dict.Set("canceled", true);
dict.Set("filePaths", std::vector<base::FilePath>());
#if IS_MAS_BUILD()
dict.Set("bookmarks", std::vector<std::string>());
#endif
} else {
std::vector<base::FilePath> paths;
dict.Set("canceled", false);
#if IS_MAS_BUILD()
std::vector<std::string> bookmarks;
if (security_scoped_bookmarks)
ReadDialogPathsWithBookmarks(dialog, &paths, &bookmarks);
else
ReadDialogPaths(dialog, &paths);
dict.Set("filePaths", paths);
dict.Set("bookmarks", bookmarks);
#else
ReadDialogPaths(dialog, &paths);
dict.Set("filePaths", paths);
#endif
}
ResolvePromiseInNextTick(promise.As<v8::Local<v8::Value>>(),
dict.GetHandle());
}
void ShowOpenDialog(const DialogSettings& settings,
gin_helper::Promise<gin_helper::Dictionary> promise) {
NSOpenPanel* dialog = [NSOpenPanel openPanel];
SetupDialog(dialog, settings);
SetupOpenDialogForProperties(dialog, settings.properties);
// Capture the value of the security_scoped_bookmarks settings flag
// and pass it to the completion handler.
bool security_scoped_bookmarks = settings.security_scoped_bookmarks;
__block gin_helper::Promise<gin_helper::Dictionary> p = std::move(promise);
if (!settings.parent_window || !settings.parent_window->GetNativeWindow() ||
settings.force_detached) {
[dialog beginWithCompletionHandler:^(NSInteger chosen) {
OpenDialogCompletion(chosen, dialog, security_scoped_bookmarks,
std::move(p));
}];
} else {
NSWindow* window =
settings.parent_window->GetNativeWindow().GetNativeNSWindow();
[dialog
beginSheetModalForWindow:window
completionHandler:^(NSInteger chosen) {
OpenDialogCompletion(chosen, dialog, security_scoped_bookmarks,
std::move(p));
}];
}
}
bool ShowSaveDialogSync(const DialogSettings& settings, base::FilePath* path) {
DCHECK(path);
NSSavePanel* dialog = [NSSavePanel savePanel];
SetupDialog(dialog, settings);
SetupSaveDialogForProperties(dialog, settings.properties);
int chosen = RunModalDialog(dialog, settings);
if (chosen == NSModalResponseCancel || ![[dialog URL] isFileURL])
return false;
*path = base::FilePath(base::SysNSStringToUTF8([[dialog URL] path]));
return true;
}
void SaveDialogCompletion(int chosen,
NSSavePanel* dialog,
bool security_scoped_bookmarks,
gin_helper::Promise<gin_helper::Dictionary> promise) {
v8::HandleScope scope(promise.isolate());
auto dict = gin_helper::Dictionary::CreateEmpty(promise.isolate());
if (chosen == NSModalResponseCancel) {
dict.Set("canceled", true);
dict.Set("filePath", base::FilePath());
#if IS_MAS_BUILD()
dict.Set("bookmark", base::StringPiece());
#endif
} else {
std::string path = base::SysNSStringToUTF8([[dialog URL] path]);
dict.Set("filePath", base::FilePath(path));
dict.Set("canceled", false);
#if IS_MAS_BUILD()
std::string bookmark;
if (security_scoped_bookmarks) {
bookmark = GetBookmarkDataFromNSURL([dialog URL]);
dict.Set("bookmark", bookmark);
}
#endif
}
ResolvePromiseInNextTick(promise.As<v8::Local<v8::Value>>(),
dict.GetHandle());
}
void ShowSaveDialog(const DialogSettings& settings,
gin_helper::Promise<gin_helper::Dictionary> promise) {
NSSavePanel* dialog = [NSSavePanel savePanel];
SetupDialog(dialog, settings);
SetupSaveDialogForProperties(dialog, settings.properties);
[dialog setCanSelectHiddenExtension:YES];
// Capture the value of the security_scoped_bookmarks settings flag
// and pass it to the completion handler.
bool security_scoped_bookmarks = settings.security_scoped_bookmarks;
__block gin_helper::Promise<gin_helper::Dictionary> p = std::move(promise);
if (!settings.parent_window || !settings.parent_window->GetNativeWindow() ||
settings.force_detached) {
[dialog beginWithCompletionHandler:^(NSInteger chosen) {
SaveDialogCompletion(chosen, dialog, security_scoped_bookmarks,
std::move(p));
}];
} else {
NSWindow* window =
settings.parent_window->GetNativeWindow().GetNativeNSWindow();
[dialog
beginSheetModalForWindow:window
completionHandler:^(NSInteger chosen) {
SaveDialogCompletion(chosen, dialog, security_scoped_bookmarks,
std::move(p));
}];
}
}
} // namespace file_dialog
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,342 |
[Bug]: Navigator.keyboard.lock() icw requestFullscreen does not change behavior to 'Press and Hold Escape'
|
### 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
27.0.2
### What operating system are you using?
Windows
### Operating System Version
Windows 10 Pro version 22H2
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
When an element is brought to fullscreen with:
[elem.requestFullscreen()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen)
and an event listener exists like:
```
document.addEventListener('fullscreenchange', async () => {
const nav: any = navigator;
const elem = document.getElementById('app');
if (elem) {
await nav.keyboard.lock(['Escape']);
return;
}
nav.keyboard.unlock();
});
```
I would expect that the behavior of the Esc key changes, where I would now need to press and hold Esc for a few seconds before fullscreen is actually exited. As described here: [https://developer.chrome.com/blog/better-full-screen-mode/](https://developer.chrome.com/blog/better-full-screen-mode/)
I imagine the same behavior change should hold for when [requestPointerLock()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestPointerLock) is used.
### Actual Behavior
When the Esc key is pressed after bringing an element to fullscreen, it ALWAYS exits fullscreen immediately, even when used in combination with [keyboard.lock() API](https://developer.mozilla.org/en-US/docs/Web/API/Keyboard/lock).
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/40342
|
https://github.com/electron/electron/pull/40365
|
4b1c31e4dbd00cd58e159cbc2ab41de3b1ce3a86
|
fcdd5cba71b82c13c4f64a3e529dea91ed72d23c
| 2023-10-26T09:51:51Z |
c++
| 2023-10-31T15:59:39Z |
shell/browser/api/electron_api_web_contents.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_web_contents.h"
#include <limits>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/containers/contains.h"
#include "base/containers/fixed_flat_map.h"
#include "base/containers/id_map.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/current_thread.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
#include "chrome/browser/ui/views/eye_dropper/eye_dropper.h"
#include "chrome/common/pref_names.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/security_state/content/content_utils.h"
#include "components/security_state/core/security_state.h"
#include "content/browser/renderer_host/frame_tree_node.h" // nogncheck
#include "content/browser/renderer_host/navigation_controller_impl.h" // nogncheck
#include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/desktop_media_id.h"
#include "content/public/browser/desktop_streams_registry.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/service_worker_context.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/input/native_web_keyboard_event.h"
#include "content/public/common/referrer_type_converters.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/webplugininfo.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "gin/arguments.h"
#include "gin/data_object_builder.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "media/base/mime_util.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "ppapi/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "printing/print_job_constants.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/browser/api/electron_api_browser_window.h"
#include "shell/browser/api/electron_api_debugger.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/api/electron_api_web_frame_main.h"
#include "shell/browser/api/message_port.h"
#include "shell/browser/browser.h"
#include "shell/browser/child_web_contents_tracker.h"
#include "shell/browser/electron_autofill_driver_factory.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/electron_javascript_dialog_manager.h"
#include "shell/browser/electron_navigation_throttle.h"
#include "shell/browser/file_select_helper.h"
#include "shell/browser/native_window.h"
#include "shell/browser/osr/osr_render_widget_host_view.h"
#include "shell/browser/osr/osr_web_contents_view.h"
#include "shell/browser/session_preferences.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/file_dialog.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/browser/web_contents_zoom_controller.h"
#include "shell/browser/web_view_guest_delegate.h"
#include "shell/browser/web_view_manager.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/color_util.h"
#include "shell/common/electron_constants.h"
#include "shell/common/gin_converters/base_converter.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/content_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/frame_converter.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/optional_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/language_util.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "shell/common/thread_restrictions.h"
#include "shell/common/v8_value_serializer.h"
#include "storage/browser/file_system/isolated_context.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/mojom/frame/find_in_page.mojom.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h"
#include "third_party/blink/public/mojom/renderer_preferences.mojom.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
#if BUILDFLAG(IS_WIN)
#include "shell/browser/native_window_views.h"
#endif
#if !BUILDFLAG(IS_MAC)
#include "ui/aura/window.h"
#else
#include "ui/base/cocoa/defaults_utils.h"
#endif
#if BUILDFLAG(IS_LINUX)
#include "ui/linux/linux_ui.h"
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
#include "ui/gfx/font_render_params.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/script_executor.h"
#include "extensions/browser/view_type_utils.h"
#include "extensions/common/mojom/view_type.mojom.h"
#include "shell/browser/extensions/electron_extension_web_contents_observer.h"
#endif
#if BUILDFLAG(ENABLE_PRINTING)
#include "chrome/browser/printing/print_view_manager_base.h"
#include "components/printing/browser/print_manager_utils.h"
#include "components/printing/browser/print_to_pdf/pdf_print_result.h"
#include "components/printing/browser/print_to_pdf/pdf_print_utils.h"
#include "printing/backend/print_backend.h" // nogncheck
#include "printing/mojom/print.mojom.h" // nogncheck
#include "printing/page_range.h"
#include "shell/browser/printing/print_view_manager_electron.h"
#if BUILDFLAG(IS_WIN)
#include "printing/backend/win_helper.h"
#endif
#endif // BUILDFLAG(ENABLE_PRINTING)
#if BUILDFLAG(ENABLE_PDF_VIEWER)
#include "components/pdf/browser/pdf_document_helper.h" // nogncheck
#include "shell/browser/electron_pdf_document_helper_client.h"
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/public/browser/plugin_service.h"
#endif
#if !IS_MAS_BUILD()
#include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck
#endif
namespace gin {
#if BUILDFLAG(ENABLE_PRINTING)
template <>
struct Converter<printing::mojom::MarginType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::MarginType* out) {
using Val = printing::mojom::MarginType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"custom", Val::kCustomMargins},
{"default", Val::kDefaultMargins},
{"none", Val::kNoMargins},
{"printableArea", Val::kPrintableAreaMargins},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<printing::mojom::DuplexMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::DuplexMode* out) {
using Val = printing::mojom::DuplexMode;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"longEdge", Val::kLongEdge},
{"shortEdge", Val::kShortEdge},
{"simplex", Val::kSimplex},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
#endif
template <>
struct Converter<WindowOpenDisposition> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
WindowOpenDisposition val) {
std::string disposition = "other";
switch (val) {
case WindowOpenDisposition::CURRENT_TAB:
disposition = "default";
break;
case WindowOpenDisposition::NEW_FOREGROUND_TAB:
disposition = "foreground-tab";
break;
case WindowOpenDisposition::NEW_BACKGROUND_TAB:
disposition = "background-tab";
break;
case WindowOpenDisposition::NEW_POPUP:
case WindowOpenDisposition::NEW_WINDOW:
disposition = "new-window";
break;
case WindowOpenDisposition::SAVE_TO_DISK:
disposition = "save-to-disk";
break;
default:
break;
}
return gin::ConvertToV8(isolate, disposition);
}
};
template <>
struct Converter<content::SavePageType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
content::SavePageType* out) {
using Val = content::SavePageType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"htmlcomplete", Val::SAVE_PAGE_TYPE_AS_COMPLETE_HTML},
{"htmlonly", Val::SAVE_PAGE_TYPE_AS_ONLY_HTML},
{"mhtml", Val::SAVE_PAGE_TYPE_AS_MHTML},
});
return FromV8WithLowerLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<electron::api::WebContents::Type> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
electron::api::WebContents::Type val) {
using Type = electron::api::WebContents::Type;
std::string type;
switch (val) {
case Type::kBackgroundPage:
type = "backgroundPage";
break;
case Type::kBrowserWindow:
type = "window";
break;
case Type::kBrowserView:
type = "browserView";
break;
case Type::kRemote:
type = "remote";
break;
case Type::kWebView:
type = "webview";
break;
case Type::kOffScreen:
type = "offscreen";
break;
default:
break;
}
return gin::ConvertToV8(isolate, type);
}
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::api::WebContents::Type* out) {
using Val = electron::api::WebContents::Type;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"backgroundPage", Val::kBackgroundPage},
{"browserView", Val::kBrowserView},
{"offscreen", Val::kOffScreen},
{"webview", Val::kWebView},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<scoped_refptr<content::DevToolsAgentHost>> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const scoped_refptr<content::DevToolsAgentHost>& val) {
gin_helper::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("id", val->GetId());
dict.Set("url", val->GetURL().spec());
return dict.GetHandle();
}
};
} // namespace gin
namespace electron::api {
namespace {
constexpr base::StringPiece CursorTypeToString(
ui::mojom::CursorType cursor_type) {
switch (cursor_type) {
case ui::mojom::CursorType::kPointer:
return "pointer";
case ui::mojom::CursorType::kCross:
return "crosshair";
case ui::mojom::CursorType::kHand:
return "hand";
case ui::mojom::CursorType::kIBeam:
return "text";
case ui::mojom::CursorType::kWait:
return "wait";
case ui::mojom::CursorType::kHelp:
return "help";
case ui::mojom::CursorType::kEastResize:
return "e-resize";
case ui::mojom::CursorType::kNorthResize:
return "n-resize";
case ui::mojom::CursorType::kNorthEastResize:
return "ne-resize";
case ui::mojom::CursorType::kNorthWestResize:
return "nw-resize";
case ui::mojom::CursorType::kSouthResize:
return "s-resize";
case ui::mojom::CursorType::kSouthEastResize:
return "se-resize";
case ui::mojom::CursorType::kSouthWestResize:
return "sw-resize";
case ui::mojom::CursorType::kWestResize:
return "w-resize";
case ui::mojom::CursorType::kNorthSouthResize:
return "ns-resize";
case ui::mojom::CursorType::kEastWestResize:
return "ew-resize";
case ui::mojom::CursorType::kNorthEastSouthWestResize:
return "nesw-resize";
case ui::mojom::CursorType::kNorthWestSouthEastResize:
return "nwse-resize";
case ui::mojom::CursorType::kColumnResize:
return "col-resize";
case ui::mojom::CursorType::kRowResize:
return "row-resize";
case ui::mojom::CursorType::kMiddlePanning:
return "m-panning";
case ui::mojom::CursorType::kMiddlePanningVertical:
return "m-panning-vertical";
case ui::mojom::CursorType::kMiddlePanningHorizontal:
return "m-panning-horizontal";
case ui::mojom::CursorType::kEastPanning:
return "e-panning";
case ui::mojom::CursorType::kNorthPanning:
return "n-panning";
case ui::mojom::CursorType::kNorthEastPanning:
return "ne-panning";
case ui::mojom::CursorType::kNorthWestPanning:
return "nw-panning";
case ui::mojom::CursorType::kSouthPanning:
return "s-panning";
case ui::mojom::CursorType::kSouthEastPanning:
return "se-panning";
case ui::mojom::CursorType::kSouthWestPanning:
return "sw-panning";
case ui::mojom::CursorType::kWestPanning:
return "w-panning";
case ui::mojom::CursorType::kMove:
return "move";
case ui::mojom::CursorType::kVerticalText:
return "vertical-text";
case ui::mojom::CursorType::kCell:
return "cell";
case ui::mojom::CursorType::kContextMenu:
return "context-menu";
case ui::mojom::CursorType::kAlias:
return "alias";
case ui::mojom::CursorType::kProgress:
return "progress";
case ui::mojom::CursorType::kNoDrop:
return "nodrop";
case ui::mojom::CursorType::kCopy:
return "copy";
case ui::mojom::CursorType::kNone:
return "none";
case ui::mojom::CursorType::kNotAllowed:
return "not-allowed";
case ui::mojom::CursorType::kZoomIn:
return "zoom-in";
case ui::mojom::CursorType::kZoomOut:
return "zoom-out";
case ui::mojom::CursorType::kGrab:
return "grab";
case ui::mojom::CursorType::kGrabbing:
return "grabbing";
case ui::mojom::CursorType::kCustom:
return "custom";
case ui::mojom::CursorType::kNull:
return "null";
case ui::mojom::CursorType::kDndNone:
return "drag-drop-none";
case ui::mojom::CursorType::kDndMove:
return "drag-drop-move";
case ui::mojom::CursorType::kDndCopy:
return "drag-drop-copy";
case ui::mojom::CursorType::kDndLink:
return "drag-drop-link";
case ui::mojom::CursorType::kNorthSouthNoResize:
return "ns-no-resize";
case ui::mojom::CursorType::kEastWestNoResize:
return "ew-no-resize";
case ui::mojom::CursorType::kNorthEastSouthWestNoResize:
return "nesw-no-resize";
case ui::mojom::CursorType::kNorthWestSouthEastNoResize:
return "nwse-no-resize";
default:
return "default";
}
}
base::IDMap<WebContents*>& GetAllWebContents() {
static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents;
return *s_all_web_contents;
}
void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise,
base::ScopedClosureRunner capture_handle,
const SkBitmap& bitmap) {
auto ui_task_runner = content::GetUIThreadTaskRunner({});
if (!ui_task_runner->RunsTasksInCurrentSequence()) {
ui_task_runner->PostTask(
FROM_HERE, base::BindOnce(&OnCapturePageDone, std::move(promise),
std::move(capture_handle), bitmap));
return;
}
// Hack to enable transparency in captured image
promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap));
capture_handle.RunAndReset();
}
absl::optional<base::TimeDelta> GetCursorBlinkInterval() {
#if BUILDFLAG(IS_MAC)
absl::optional<base::TimeDelta> system_value(
ui::TextInsertionCaretBlinkPeriodFromDefaults());
if (system_value)
return *system_value;
#elif BUILDFLAG(IS_LINUX)
if (auto* linux_ui = ui::LinuxUi::instance())
return linux_ui->GetCursorBlinkInterval();
#elif BUILDFLAG(IS_WIN)
const auto system_msec = ::GetCaretBlinkTime();
if (system_msec != 0) {
return (system_msec == INFINITE) ? base::TimeDelta()
: base::Milliseconds(system_msec);
}
#endif
return absl::nullopt;
}
#if BUILDFLAG(ENABLE_PRINTING)
// This will return false if no printer with the provided device_name can be
// found on the network. We need to check this because Chromium does not do
// sanity checking of device_name validity and so will crash on invalid names.
bool IsDeviceNameValid(const std::u16string& device_name) {
#if BUILDFLAG(IS_MAC)
base::apple::ScopedCFTypeRef<CFStringRef> new_printer_id(
base::SysUTF16ToCFStringRef(device_name));
PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get());
bool printer_exists = new_printer != nullptr;
PMRelease(new_printer);
return printer_exists;
#else
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name));
#endif
}
// This function returns a validated device name.
// If the user passed one to webContents.print(), we check that it's valid and
// return it or fail if the network doesn't recognize it. If the user didn't
// pass a device name, we first try to return the system default printer. If one
// isn't set, then pull all the printers and use the first one or fail if none
// exist.
std::pair<std::string, std::u16string> GetDeviceNameToUse(
const std::u16string& device_name) {
#if BUILDFLAG(IS_WIN)
// Blocking is needed here because Windows printer drivers are oftentimes
// not thread-safe and have to be accessed on the UI thread.
ScopedAllowBlockingForElectron allow_blocking;
#endif
if (!device_name.empty()) {
if (!IsDeviceNameValid(device_name))
return std::make_pair("Invalid deviceName provided", std::u16string());
return std::make_pair(std::string(), device_name);
}
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
std::string printer_name;
printing::mojom::ResultCode code =
print_backend->GetDefaultPrinterName(printer_name);
// We don't want to return if this fails since some devices won't have a
// default printer.
if (code != printing::mojom::ResultCode::kSuccess)
LOG(ERROR) << "Failed to get default printer name";
if (printer_name.empty()) {
printing::PrinterList printers;
if (print_backend->EnumeratePrinters(printers) !=
printing::mojom::ResultCode::kSuccess)
return std::make_pair("Failed to enumerate printers", std::u16string());
if (printers.empty())
return std::make_pair("No printers available on the network",
std::u16string());
printer_name = printers.front().printer_name;
}
return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name));
}
// Copied from
// chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54
scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() {
// USER_VISIBLE because the result is displayed in the print preview dialog.
#if !BUILDFLAG(IS_WIN)
static constexpr base::TaskTraits kTraits = {
base::MayBlock(), base::TaskPriority::USER_VISIBLE};
#endif
#if defined(USE_CUPS)
// CUPS is thread safe.
return base::ThreadPool::CreateTaskRunner(kTraits);
#elif BUILDFLAG(IS_WIN)
// Windows drivers are likely not thread-safe and need to be accessed on the
// UI thread.
return content::GetUIThreadTaskRunner({base::TaskPriority::USER_VISIBLE});
#else
// Be conservative on unsupported platforms.
return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits);
#endif
}
#endif
struct UserDataLink : public base::SupportsUserData::Data {
explicit UserDataLink(base::WeakPtr<WebContents> contents)
: web_contents(contents) {}
base::WeakPtr<WebContents> web_contents;
};
const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey;
const char kRootName[] = "<root>";
struct FileSystem {
FileSystem() = default;
FileSystem(const std::string& type,
const std::string& file_system_name,
const std::string& root_url,
const std::string& file_system_path)
: type(type),
file_system_name(file_system_name),
root_url(root_url),
file_system_path(file_system_path) {}
std::string type;
std::string file_system_name;
std::string root_url;
std::string file_system_path;
};
std::string RegisterFileSystem(content::WebContents* web_contents,
const base::FilePath& path) {
auto* isolated_context = storage::IsolatedContext::GetInstance();
std::string root_name(kRootName);
storage::IsolatedContext::ScopedFSHandle file_system =
isolated_context->RegisterFileSystemForPath(
storage::kFileSystemTypeLocal, std::string(), path, &root_name);
content::ChildProcessSecurityPolicy* policy =
content::ChildProcessSecurityPolicy::GetInstance();
content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
int renderer_id = render_view_host->GetProcess()->GetID();
policy->GrantReadFileSystem(renderer_id, file_system.id());
policy->GrantWriteFileSystem(renderer_id, file_system.id());
policy->GrantCreateFileForFileSystem(renderer_id, file_system.id());
policy->GrantDeleteFromFileSystem(renderer_id, file_system.id());
if (!policy->CanReadFile(renderer_id, path))
policy->GrantReadFile(renderer_id, path);
return file_system.id();
}
FileSystem CreateFileSystemStruct(content::WebContents* web_contents,
const std::string& file_system_id,
const std::string& file_system_path,
const std::string& type) {
const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL();
std::string file_system_name =
storage::GetIsolatedFileSystemName(origin, file_system_id);
std::string root_url = storage::GetIsolatedFileSystemRootURIString(
origin, file_system_id, kRootName);
return FileSystem(type, file_system_name, root_url, file_system_path);
}
base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) {
base::Value::Dict value;
value.Set("type", file_system.type);
value.Set("fileSystemName", file_system.file_system_name);
value.Set("rootURL", file_system.root_url);
value.Set("fileSystemPath", file_system.file_system_path);
return value;
}
void WriteToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::WriteFile(path, content.data(), content.size());
}
void AppendToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::AppendToFile(path, content);
}
PrefService* GetPrefService(content::WebContents* web_contents) {
auto* context = web_contents->GetBrowserContext();
return static_cast<electron::ElectronBrowserContext*>(context)->prefs();
}
std::map<std::string, std::string> GetAddedFileSystemPaths(
content::WebContents* web_contents) {
auto* pref_service = GetPrefService(web_contents);
const base::Value::Dict& file_system_paths =
pref_service->GetDict(prefs::kDevToolsFileSystemPaths);
std::map<std::string, std::string> result;
for (auto it : file_system_paths) {
std::string type =
it.second.is_string() ? it.second.GetString() : std::string();
result[it.first] = type;
}
return result;
}
bool IsDevToolsFileSystemAdded(content::WebContents* web_contents,
const std::string& file_system_path) {
return base::Contains(GetAddedFileSystemPaths(web_contents),
file_system_path);
}
void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) {
rwhv->SetBackgroundColor(color);
static_cast<content::RenderWidgetHostViewBase*>(rwhv)
->SetContentBackgroundColor(color);
}
content::RenderFrameHost* GetRenderFrameHost(
content::NavigationHandle* navigation_handle) {
int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId();
content::FrameTreeNode* frame_tree_node =
content::FrameTreeNode::GloballyFindByID(frame_tree_node_id);
content::RenderFrameHostManager* render_manager =
frame_tree_node->render_manager();
content::RenderFrameHost* frame_host = nullptr;
if (render_manager) {
frame_host = render_manager->speculative_frame_host();
if (!frame_host)
frame_host = render_manager->current_frame_host();
}
return frame_host;
}
} // namespace
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) {
switch (view_type) {
case extensions::mojom::ViewType::kExtensionBackgroundPage:
return WebContents::Type::kBackgroundPage;
case extensions::mojom::ViewType::kAppWindow:
case extensions::mojom::ViewType::kComponent:
case extensions::mojom::ViewType::kExtensionPopup:
case extensions::mojom::ViewType::kBackgroundContents:
case extensions::mojom::ViewType::kExtensionGuest:
case extensions::mojom::ViewType::kTabContents:
case extensions::mojom::ViewType::kOffscreenDocument:
case extensions::mojom::ViewType::kExtensionSidePanel:
case extensions::mojom::ViewType::kInvalid:
return WebContents::Type::kRemote;
}
}
#endif
WebContents::WebContents(v8::Isolate* isolate,
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
type_(Type::kRemote),
id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// WebContents created by extension host will have valid ViewType set.
extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents);
if (view_type != extensions::mojom::ViewType::kInvalid) {
InitWithExtensionView(isolate, web_contents, view_type);
}
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents);
script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents);
#endif
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
SetUserAgent(GetBrowserContext()->GetUserAgent());
web_contents->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type)
: content::WebContentsObserver(web_contents.get()),
type_(type),
id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
DCHECK(type != Type::kRemote)
<< "Can't take ownership of a remote WebContents";
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
InitWithSessionAndOptions(isolate, std::move(web_contents), session,
gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
const gin_helper::Dictionary& options)
: id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
// Read options.
options.Get("backgroundThrottling", &background_throttling_);
// Get type
options.Get("type", &type_);
bool b = false;
if (options.Get(options::kOffscreen, &b) && b)
type_ = Type::kOffScreen;
// Init embedder earlier
options.Get("embedder", &embedder_);
// Whether to enable DevTools.
options.Get("devTools", &enable_devtools_);
// BrowserViews are not attached to a window initially so they should start
// off as hidden. This is also important for compositor recycling. See:
// https://github.com/electron/electron/pull/21372
bool initially_shown = type_ != Type::kBrowserView;
options.Get(options::kShow, &initially_shown);
// Obtain the session.
std::string partition;
gin::Handle<api::Session> session;
if (options.Get("session", &session) && !session.IsEmpty()) {
} else if (options.Get("partition", &partition)) {
session = Session::FromPartition(isolate, partition);
} else {
// Use the default session if not specified.
session = Session::FromPartition(isolate, "");
}
session_.Reset(isolate, session.ToV8());
std::unique_ptr<content::WebContents> web_contents;
if (IsGuest()) {
scoped_refptr<content::SiteInstance> site_instance =
content::SiteInstance::CreateForURL(session->browser_context(),
GURL("chrome-guest://fake-host"));
content::WebContents::CreateParams params(session->browser_context(),
site_instance);
guest_delegate_ =
std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this);
params.guest_delegate = guest_delegate_.get();
if (embedder_ && embedder_->IsOffScreen()) {
auto* view = new OffScreenWebContentsView(
false,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
web_contents = content::WebContents::Create(params);
}
} else if (IsOffScreen()) {
// webPreferences does not have a transparent option, so if the window needs
// to be transparent, that will be set at electron_api_browser_window.cc#L57
// and we then need to pull it back out and check it here.
std::string background_color;
options.GetHidden(options::kBackgroundColor, &background_color);
bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT;
content::WebContents::CreateParams params(session->browser_context());
auto* view = new OffScreenWebContentsView(
transparent,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
content::WebContents::CreateParams params(session->browser_context());
params.initially_hidden = !initially_shown;
web_contents = content::WebContents::Create(params);
}
InitWithSessionAndOptions(isolate, std::move(web_contents), session, options);
}
void WebContents::InitZoomController(content::WebContents* web_contents,
const gin_helper::Dictionary& options) {
WebContentsZoomController::CreateForWebContents(web_contents);
zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
double zoom_factor;
if (options.Get(options::kZoomFactor, &zoom_factor))
zoom_controller_->SetDefaultZoomFactor(zoom_factor);
// Nothing to do with ZoomController, but this function gets called in all
// init cases!
content::RenderViewHost* host = web_contents->GetRenderViewHost();
if (host)
host->GetWidget()->AddInputEventObserver(this);
}
void WebContents::InitWithSessionAndOptions(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> owned_web_contents,
gin::Handle<api::Session> session,
const gin_helper::Dictionary& options) {
Observe(owned_web_contents.get());
InitWithWebContents(std::move(owned_web_contents), session->browser_context(),
IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
auto* prefs = web_contents()->GetMutableRendererPrefs();
// Collect preferred languages from OS and browser process. accept_languages
// effects HTTP header, navigator.languages, and CJK fallback font selection.
//
// Note that an application locale set to the browser process might be
// different with the one set to the preference list.
// (e.g. overridden with --lang)
std::string accept_languages =
g_browser_process->GetApplicationLocale() + ",";
for (auto const& language : electron::GetPreferredLanguages()) {
if (language == g_browser_process->GetApplicationLocale())
continue;
accept_languages += language + ",";
}
accept_languages.pop_back();
prefs->accept_languages = accept_languages;
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
// Update font settings.
static const gfx::FontRenderParams params(
gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr));
prefs->should_antialias_text = params.antialiasing;
prefs->use_subpixel_positioning = params.subpixel_positioning;
prefs->hinting = params.hinting;
prefs->use_autohinter = params.autohinter;
prefs->use_bitmaps = params.use_bitmaps;
prefs->subpixel_rendering = params.subpixel_rendering;
#endif
// Honor the system's cursor blink rate settings
if (auto interval = GetCursorBlinkInterval())
prefs->caret_blink_interval = *interval;
// Save the preferences in C++.
// If there's already a WebContentsPreferences object, we created it as part
// of the webContents.setWindowOpenHandler path, so don't overwrite it.
if (!WebContentsPreferences::From(web_contents())) {
new WebContentsPreferences(web_contents(), options);
}
// Trigger re-calculation of webkit prefs.
web_contents()->NotifyPreferencesChanged();
WebContentsPermissionHelper::CreateForWebContents(web_contents());
InitZoomController(web_contents(), options);
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents());
script_executor_ =
std::make_unique<extensions::ScriptExecutor>(web_contents());
#endif
AutofillDriverFactory::CreateForWebContents(web_contents());
SetUserAgent(GetBrowserContext()->GetUserAgent());
if (IsGuest()) {
NativeWindow* owner_window = nullptr;
if (embedder_) {
// New WebContents's owner_window is the embedder's owner_window.
auto* relay =
NativeWindowRelay::FromWebContents(embedder_->web_contents());
if (relay)
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
}
web_contents()->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
void WebContents::InitWithExtensionView(v8::Isolate* isolate,
content::WebContents* web_contents,
extensions::mojom::ViewType view_type) {
// Must reassign type prior to calling `Init`.
type_ = GetTypeFromViewType(view_type);
if (type_ == Type::kRemote)
return;
if (type_ == Type::kBackgroundPage)
// non-background-page WebContents are retained by other classes. We need
// to pin here to prevent background-page WebContents from being GC'd.
// The background page api::WebContents will live until the underlying
// content::WebContents is destroyed.
Pin(isolate);
// Allow toggling DevTools for background pages
Observe(web_contents);
InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents),
GetBrowserContext(), IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
}
#endif
void WebContents::InitWithWebContents(
std::unique_ptr<content::WebContents> web_contents,
ElectronBrowserContext* browser_context,
bool is_guest) {
browser_context_ = browser_context;
web_contents->SetDelegate(this);
#if BUILDFLAG(ENABLE_PRINTING)
PrintViewManagerElectron::CreateForWebContents(web_contents.get());
#endif
// Determine whether the WebContents is offscreen.
auto* web_preferences = WebContentsPreferences::From(web_contents.get());
offscreen_ = web_preferences && web_preferences->IsOffscreen();
// Create InspectableWebContents.
inspectable_web_contents_ = std::make_unique<InspectableWebContents>(
std::move(web_contents), browser_context->prefs(), is_guest);
inspectable_web_contents_->SetDelegate(this);
}
WebContents::~WebContents() {
if (owner_window_) {
owner_window_->RemoveBackgroundThrottlingSource(this);
}
if (web_contents()) {
content::RenderViewHost* host = web_contents()->GetRenderViewHost();
if (host)
host->GetWidget()->RemoveInputEventObserver(this);
}
if (!inspectable_web_contents_) {
WebContentsDestroyed();
return;
}
inspectable_web_contents_->GetView()->SetDelegate(nullptr);
// This event is only for internal use, which is emitted when WebContents is
// being destroyed.
Emit("will-destroy");
// For guest view based on OOPIF, the WebContents is released by the embedder
// frame, and we need to clear the reference to the memory.
bool not_owned_by_this = IsGuest() && attached_;
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// And background pages are owned by extensions::ExtensionHost.
if (type_ == Type::kBackgroundPage)
not_owned_by_this = true;
#endif
if (not_owned_by_this) {
inspectable_web_contents_->ReleaseWebContents();
WebContentsDestroyed();
}
// InspectableWebContents will be automatically destroyed.
}
void WebContents::DeleteThisIfAlive() {
// It is possible that the FirstWeakCallback has been called but the
// SecondWeakCallback has not, in this case the garbage collection of
// WebContents has already started and we should not |delete this|.
// Calling |GetWrapper| can detect this corner case.
auto* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
delete this;
}
void WebContents::Destroy() {
// The content::WebContents should be destroyed asynchronously when possible
// as user may choose to destroy WebContents during an event of it.
if (Browser::Get()->is_shutting_down() || IsGuest()) {
DeleteThisIfAlive();
} else {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&WebContents::DeleteThisIfAlive, GetWeakPtr()));
}
}
void WebContents::Close(absl::optional<gin_helper::Dictionary> options) {
bool dispatch_beforeunload = false;
if (options)
options->Get("waitForBeforeUnload", &dispatch_beforeunload);
if (dispatch_beforeunload &&
web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) {
NotifyUserActivation();
web_contents()->DispatchBeforeUnload(false /* auto_cancel */);
} else {
web_contents()->Close();
}
}
bool WebContents::DidAddMessageToConsole(
content::WebContents* source,
blink::mojom::ConsoleMessageLevel level,
const std::u16string& message,
int32_t line_no,
const std::u16string& source_id) {
return Emit("console-message", static_cast<int32_t>(level), message, line_no,
source_id);
}
void WebContents::OnCreateWindow(
const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const std::string& features,
const scoped_refptr<network::ResourceRequestBody>& body) {
Emit("-new-window", target_url, frame_name, disposition, features, referrer,
body);
}
void WebContents::WebContentsCreatedWithFullParams(
content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const content::mojom::CreateNewWindowParams& params,
content::WebContents* new_contents) {
ChildWebContentsTracker::CreateForWebContents(new_contents);
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents);
tracker->url = params.target_url;
tracker->frame_name = params.frame_name;
tracker->referrer = params.referrer.To<content::Referrer>();
tracker->raw_features = params.raw_features;
tracker->body = params.body;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary dict;
gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate),
&dict);
pending_child_web_preferences_.Reset();
// Associate the preferences passed in via `setWindowOpenHandler` with the
// content::WebContents that was just created for the child window. These
// preferences will be picked up by the RenderWidgetHost via its call to the
// delegate's OverrideWebkitPrefs.
new WebContentsPreferences(new_contents, dict);
}
bool WebContents::IsWebContentsCreationOverridden(
content::SiteInstance* source_site_instance,
content::mojom::WindowContainerType window_container_type,
const GURL& opener_url,
const content::mojom::CreateNewWindowParams& params) {
bool default_prevented = Emit(
"-will-add-new-contents", params.target_url, params.frame_name,
params.raw_features, params.disposition, *params.referrer, params.body);
// If the app prevented the default, redirect to CreateCustomWebContents,
// which always returns nullptr, which will result in the window open being
// prevented (window.open() will return null in the renderer).
return default_prevented;
}
void WebContents::SetNextChildWebPreferences(
const gin_helper::Dictionary preferences) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
// Store these prefs for when Chrome calls WebContentsCreatedWithFullParams
// with the new child contents.
pending_child_web_preferences_.Reset(isolate, preferences.GetHandle());
}
content::WebContents* WebContents::CreateCustomWebContents(
content::RenderFrameHost* opener,
content::SiteInstance* source_site_instance,
bool is_new_browsing_instance,
const GURL& opener_url,
const std::string& frame_name,
const GURL& target_url,
const content::StoragePartitionConfig& partition_config,
content::SessionStorageNamespace* session_storage_namespace) {
return nullptr;
}
void WebContents::AddNewContents(
content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) {
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get());
DCHECK(tracker);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto api_web_contents =
CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow);
// We call RenderFrameCreated here as at this point the empty "about:blank"
// render frame has already been created. If the window never navigates again
// RenderFrameCreated won't be called and certain prefs like
// "kBackgroundColor" will not be applied.
auto* frame = api_web_contents->MainFrame();
if (frame) {
api_web_contents->HandleNewRenderFrame(frame);
}
if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
window_features.bounds.x(), window_features.bounds.y(),
window_features.bounds.width(), window_features.bounds.height(),
tracker->url, tracker->frame_name, tracker->referrer,
tracker->raw_features, tracker->body)) {
api_web_contents->Destroy();
}
}
content::WebContents* WebContents::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
auto weak_this = GetWeakPtr();
if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {
Emit("-new-window", params.url, "", params.disposition, "", params.referrer,
params.post_data);
return nullptr;
}
if (!weak_this || !web_contents())
return nullptr;
content::NavigationController::LoadURLParams load_url_params(params.url);
load_url_params.referrer = params.referrer;
load_url_params.transition_type = params.transition;
load_url_params.extra_headers = params.extra_headers;
load_url_params.should_replace_current_entry =
params.should_replace_current_entry;
load_url_params.is_renderer_initiated = params.is_renderer_initiated;
load_url_params.started_from_context_menu = params.started_from_context_menu;
load_url_params.initiator_origin = params.initiator_origin;
load_url_params.source_site_instance = params.source_site_instance;
load_url_params.frame_tree_node_id = params.frame_tree_node_id;
load_url_params.redirect_chain = params.redirect_chain;
load_url_params.has_user_gesture = params.user_gesture;
load_url_params.blob_url_loader_factory = params.blob_url_loader_factory;
load_url_params.href_translate = params.href_translate;
load_url_params.reload_type = params.reload_type;
if (params.post_data) {
load_url_params.load_type =
content::NavigationController::LOAD_TYPE_HTTP_POST;
load_url_params.post_data = params.post_data;
}
source->GetController().LoadURLWithParams(load_url_params);
return source;
}
void WebContents::BeforeUnloadFired(content::WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) {
if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen ||
type_ == Type::kBrowserView)
*proceed_to_fire_unload = proceed;
else
*proceed_to_fire_unload = true;
// Note that Chromium does not emit this for navigations.
Emit("before-unload-fired", proceed);
}
void WebContents::SetContentsBounds(content::WebContents* source,
const gfx::Rect& rect) {
if (!Emit("content-bounds-updated", rect))
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnSetContentBounds(rect);
}
void WebContents::CloseContents(content::WebContents* source) {
Emit("close");
auto* autofill_driver_factory =
AutofillDriverFactory::FromWebContents(web_contents());
if (autofill_driver_factory) {
autofill_driver_factory->CloseAllPopups();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnCloseContents();
// This is handled by the embedder frame.
if (!IsGuest())
Destroy();
}
void WebContents::ActivateContents(content::WebContents* source) {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnActivateContents();
}
void WebContents::UpdateTargetURL(content::WebContents* source,
const GURL& url) {
Emit("update-target-url", url);
}
bool WebContents::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (type_ == Type::kWebView && embedder_) {
// Send the unhandled keyboard events back to the embedder.
return embedder_->HandleKeyboardEvent(source, event);
} else {
return PlatformHandleKeyboardEvent(source, event);
}
}
#if !BUILDFLAG(IS_MAC)
// NOTE: The macOS version of this function is found in
// electron_api_web_contents_mac.mm, as it requires calling into objective-C
// code.
bool WebContents::PlatformHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
// Escape exits tabbed fullscreen mode.
if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) {
ExitFullscreenModeForTab(source);
return true;
}
// Check if the webContents has preferences and to ignore shortcuts
auto* web_preferences = WebContentsPreferences::From(source);
if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts())
return false;
// Let the NativeWindow handle other parts.
if (owner_window()) {
owner_window()->HandleKeyboardEvent(source, event);
return true;
}
return false;
}
#endif
content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (exclusive_access_manager_.HandleUserKeyEvent(event))
return content::KeyboardEventProcessingResult::HANDLED;
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown ||
event.GetType() == blink::WebInputEvent::Type::kKeyUp) {
// For backwards compatibility, pretend that `kRawKeyDown` events are
// actually `kKeyDown`.
content::NativeWebKeyboardEvent tweaked_event(event);
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown)
tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown);
bool prevent_default = Emit("before-input-event", tweaked_event);
if (prevent_default) {
return content::KeyboardEventProcessingResult::HANDLED;
}
}
return content::KeyboardEventProcessingResult::NOT_HANDLED;
}
void WebContents::ContentsZoomChange(bool zoom_in) {
Emit("zoom-changed", zoom_in ? "in" : "out");
}
Profile* WebContents::GetProfile() {
return nullptr;
}
bool WebContents::IsFullscreen() const {
if (!owner_window())
return false;
return owner_window()->IsFullscreen() || is_html_fullscreen();
}
void WebContents::EnterFullscreen(const GURL& url,
ExclusiveAccessBubbleType bubble_type,
const int64_t display_id) {}
void WebContents::ExitFullscreen() {}
void WebContents::UpdateExclusiveAccessExitBubbleContent(
const GURL& url,
ExclusiveAccessBubbleType bubble_type,
ExclusiveAccessBubbleHideCallback bubble_first_hide_callback,
bool notify_download,
bool force_update) {}
void WebContents::OnExclusiveAccessUserInput() {}
content::WebContents* WebContents::GetActiveWebContents() {
return web_contents();
}
bool WebContents::CanUserExitFullscreen() const {
return true;
}
bool WebContents::IsExclusiveAccessBubbleDisplayed() const {
return false;
}
void WebContents::EnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options) {
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(source);
auto callback =
base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab,
base::Unretained(this), requesting_frame, options);
permission_helper->RequestFullscreenPermission(requesting_frame, callback);
}
void WebContents::OnEnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options,
bool allowed) {
if (!allowed || !owner_window())
return;
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
if (IsFullscreenForTabOrPending(source)) {
DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame());
return;
}
owner_window()->set_fullscreen_transition_type(
NativeWindow::FullScreenTransitionType::kHTML);
exclusive_access_manager_.fullscreen_controller()->EnterFullscreenModeForTab(
requesting_frame, options.display_id);
SetHtmlApiFullscreen(true);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
if (!owner_window())
return;
// This needs to be called before we exit fullscreen on the native window,
// or the controller will incorrectly think we weren't fullscreen and bail.
exclusive_access_manager_.fullscreen_controller()->ExitFullscreenModeForTab(
source);
SetHtmlApiFullscreen(false);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too. Chrome does this indirectly from
// `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::RendererUnresponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host,
base::RepeatingClosure hang_monitor_restarter) {
Emit("unresponsive");
}
void WebContents::RendererResponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host) {
Emit("responsive");
}
bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) {
Emit("context-menu", std::make_pair(params, &render_frame_host));
return true;
}
void WebContents::FindReply(content::WebContents* web_contents,
int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update) {
if (!final_update)
return;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto result = gin_helper::Dictionary::CreateEmpty(isolate);
result.Set("requestId", request_id);
result.Set("matches", number_of_matches);
result.Set("selectionArea", selection_rect);
result.Set("activeMatchOrdinal", active_match_ordinal);
result.Set("finalUpdate", final_update); // Deprecate after 2.0
Emit("found-in-page", result.GetHandle());
}
void WebContents::RequestExclusivePointerAccess(
content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target,
bool allowed) {
if (allowed) {
exclusive_access_manager_.mouse_lock_controller()->RequestToLockMouse(
web_contents, user_gesture, last_unlocked_by_target);
} else {
web_contents->GotResponseToLockMouseRequest(
blink::mojom::PointerLockResult::kPermissionDenied);
}
}
void WebContents::RequestToLockMouse(content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestPointerLockPermission(
user_gesture, last_unlocked_by_target,
base::BindOnce(&WebContents::RequestExclusivePointerAccess,
base::Unretained(this)));
}
void WebContents::LostMouseLock() {
exclusive_access_manager_.mouse_lock_controller()->LostMouseLock();
}
void WebContents::RequestKeyboardLock(content::WebContents* web_contents,
bool esc_key_locked) {
exclusive_access_manager_.keyboard_lock_controller()->RequestKeyboardLock(
web_contents, esc_key_locked);
}
void WebContents::CancelKeyboardLockRequest(
content::WebContents* web_contents) {
exclusive_access_manager_.keyboard_lock_controller()
->CancelKeyboardLockRequest(web_contents);
}
bool WebContents::CheckMediaAccessPermission(
content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::mojom::MediaStreamType type) {
auto* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
return permission_helper->CheckMediaAccessPermission(security_origin, type);
}
void WebContents::RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestMediaAccessPermission(request, std::move(callback));
}
content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager(
content::WebContents* source) {
if (!dialog_manager_)
dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>();
return dialog_manager_.get();
}
void WebContents::OnAudioStateChanged(bool audible) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
gin::Dictionary dict(isolate, event_object);
dict.Set("audible", audible);
EmitWithoutEvent("audio-state-changed", event);
}
void WebContents::BeforeUnloadFired(bool proceed) {
// Do nothing, we override this method just to avoid compilation error since
// there are two virtual functions named BeforeUnloadFired.
}
void WebContents::HandleNewRenderFrame(
content::RenderFrameHost* render_frame_host) {
auto* rwhv = render_frame_host->GetView();
if (!rwhv)
return;
// Set the background color of RenderWidgetHostView.
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences) {
auto maybe_color = web_preferences->GetBackgroundColor();
bool guest = IsGuest() || type_ == Type::kBrowserView;
// If webPreferences has no color stored we need to explicitly set guest
// webContents background color to transparent.
auto bg_color =
maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE);
web_contents()->SetPageBaseBackgroundColor(bg_color);
SetBackgroundColor(rwhv, bg_color);
}
if (!background_throttling_)
render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false);
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (rwh_impl)
rwh_impl->disable_hidden_ = !background_throttling_;
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->MaybeSetupMojoConnection();
}
void WebContents::OnBackgroundColorChanged() {
absl::optional<SkColor> color = web_contents()->GetBackgroundColor();
if (color.has_value()) {
auto* const view = web_contents()->GetRenderWidgetHostView();
static_cast<content::RenderWidgetHostViewBase*>(view)
->SetContentBackgroundColor(color.value());
}
}
void WebContents::RenderFrameCreated(
content::RenderFrameHost* render_frame_host) {
HandleNewRenderFrame(render_frame_host);
// RenderFrameCreated is called for speculative frames which may not be
// used in certain cross-origin navigations. Invoking
// RenderFrameHost::GetLifecycleState currently crashes when called for
// speculative frames so we need to filter it out for now. Check
// https://crbug.com/1183639 for details on when this can be removed.
auto* rfh_impl =
static_cast<content::RenderFrameHostImpl*>(render_frame_host);
if (rfh_impl->lifecycle_state() ==
content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) {
return;
}
content::RenderFrameHost::LifecycleState lifecycle_state =
render_frame_host->GetLifecycleState();
if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.SetGetter("frame", render_frame_host);
Emit("frame-created", details);
}
}
void WebContents::RenderFrameDeleted(
content::RenderFrameHost* render_frame_host) {
// A RenderFrameHost can be deleted when:
// - A WebContents is removed and its containing frames are disposed.
// - An <iframe> is removed from the DOM.
// - Cross-origin navigation creates a new RFH in a separate process which
// is swapped by content::RenderFrameHostManager.
//
// WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID
// to find an existing instance of WebFrameMain. During a cross-origin
// navigation, the deleted RFH will be the old host which was swapped out. In
// this special case, we need to also ensure that WebFrameMain's internal RFH
// matches before marking it as disposed.
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame && web_frame->render_frame_host() == render_frame_host)
web_frame->MarkRenderFrameDisposed();
}
void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) {
if (new_host->IsInPrimaryMainFrame()) {
if (old_host)
old_host->GetRenderWidgetHost()->RemoveInputEventObserver(this);
if (new_host)
new_host->GetRenderWidgetHost()->AddInputEventObserver(this);
}
// During cross-origin navigation, a FrameTreeNode will swap out its RFH.
// If an instance of WebFrameMain exists, it will need to have its RFH
// swapped as well.
//
// |old_host| can be a nullptr so we use |new_host| for looking up the
// WebFrameMain instance.
auto* web_frame = WebFrameMain::FromRenderFrameHost(new_host);
if (web_frame) {
web_frame->UpdateRenderFrameHost(new_host);
}
}
void WebContents::FrameDeleted(int frame_tree_node_id) {
auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id);
if (web_frame)
web_frame->Destroyed();
}
void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
// This event is necessary for tracking any states with respect to
// intermediate render view hosts aka speculative render view hosts. Currently
// used by object-registry.js to ref count remote objects.
Emit("render-view-deleted", render_view_host->GetProcess()->GetID());
if (web_contents()->GetRenderViewHost() == render_view_host) {
// When the RVH that has been deleted is the current RVH it means that the
// the web contents are being closed. This is communicated by this event.
// Currently tracked by guest-window-manager.ts to destroy the
// BrowserWindow.
Emit("current-render-view-deleted",
render_view_host->GetProcess()->GetID());
}
}
void WebContents::PrimaryMainFrameRenderProcessGone(
base::TerminationStatus status) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("reason", status);
details.Set("exitCode", web_contents()->GetCrashedErrorCode());
Emit("render-process-gone", details);
}
void WebContents::PluginCrashed(const base::FilePath& plugin_path,
base::ProcessId plugin_pid) {
#if BUILDFLAG(ENABLE_PLUGINS)
content::WebPluginInfo info;
auto* plugin_service = content::PluginService::GetInstance();
plugin_service->GetPluginInfoByPath(plugin_path, &info);
Emit("plugin-crashed", info.name, info.version);
#endif // BUILDFLAG(ENABLE_PLUGINS)
}
void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id) {
Emit("media-started-playing");
}
void WebContents::MediaStoppedPlaying(
const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id,
content::WebContentsObserver::MediaStoppedReason reason) {
Emit("media-paused");
}
void WebContents::DidChangeThemeColor() {
auto theme_color = web_contents()->GetThemeColor();
if (theme_color) {
Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value()));
} else {
Emit("did-change-theme-color", nullptr);
}
}
void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) {
set_fullscreen_frame(rfh);
}
void WebContents::OnWebContentsFocused(
content::RenderWidgetHost* render_widget_host) {
Emit("focus");
}
void WebContents::OnWebContentsLostFocus(
content::RenderWidgetHost* render_widget_host) {
Emit("blur");
}
void WebContents::DOMContentLoaded(
content::RenderFrameHost* render_frame_host) {
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->DOMContentLoaded();
if (!render_frame_host->GetParent())
Emit("dom-ready");
}
void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url) {
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
auto weak_this = GetWeakPtr();
Emit("did-frame-finish-load", is_main_frame, frame_process_id,
frame_routing_id);
// β οΈWARNING!β οΈ
// Emit() triggers JS which can call destroy() on |this|. It's not safe to
// assume that |this| points to valid memory at this point.
if (is_main_frame && weak_this && web_contents())
Emit("did-finish-load");
}
void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
const GURL& url,
int error_code) {
// See DocumentLoader::StartLoadingResponse() - when we navigate to a media
// resource the original request for the media resource, which resulted in a
// committed navigation, is simply discarded. The media element created
// inside the MediaDocument then makes *another new* request for the same
// media resource.
bool is_media_document =
media::IsSupportedMediaMimeType(web_contents()->GetContentsMimeType());
if (error_code == net::ERR_ABORTED && is_media_document)
return;
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id,
frame_routing_id);
}
void WebContents::DidStartLoading() {
Emit("did-start-loading");
}
void WebContents::DidStopLoading() {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences && web_preferences->ShouldUsePreferredSizeMode())
web_contents()->GetRenderViewHost()->EnablePreferredSizeMode();
Emit("did-stop-loading");
}
bool WebContents::EmitNavigationEvent(
const std::string& event_name,
content::NavigationHandle* navigation_handle) {
bool is_main_frame = navigation_handle->IsInMainFrame();
int frame_process_id = -1, frame_routing_id = -1;
content::RenderFrameHost* frame_host = GetRenderFrameHost(navigation_handle);
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
bool is_same_document = navigation_handle->IsSameDocument();
auto url = navigation_handle->GetURL();
content::RenderFrameHost* initiator_frame_host =
navigation_handle->GetInitiatorFrameToken().has_value()
? content::RenderFrameHost::FromFrameToken(
navigation_handle->GetInitiatorProcessId(),
navigation_handle->GetInitiatorFrameToken().value())
: nullptr;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
gin_helper::Dictionary dict(isolate, event_object);
dict.Set("url", url);
dict.Set("isSameDocument", is_same_document);
dict.Set("isMainFrame", is_main_frame);
dict.SetGetter("frame", frame_host);
dict.SetGetter("initiator", initiator_frame_host);
EmitWithoutEvent(event_name, event, url, is_same_document, is_main_frame,
frame_process_id, frame_routing_id);
return event->GetDefaultPrevented();
}
void WebContents::Message(bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Message", "channel", channel);
// webContents.emit('-ipc-message', new Event(), internal, channel,
// arguments);
EmitWithSender("-ipc-message", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), internal,
channel, std::move(arguments));
}
void WebContents::Invoke(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::InvokeCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel);
// webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments);
EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::OnFirstNonEmptyLayout(
content::RenderFrameHost* render_frame_host) {
if (render_frame_host == web_contents()->GetPrimaryMainFrame()) {
Emit("ready-to-show");
}
}
// This object wraps the InvokeCallback so that if it gets GC'd by V8, we can
// still call the callback and send an error. Not doing so causes a Mojo DCHECK,
// since Mojo requires callbacks to be called before they are destroyed.
class ReplyChannel : public gin::Wrappable<ReplyChannel> {
public:
using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback;
static gin::Handle<ReplyChannel> Create(v8::Isolate* isolate,
InvokeCallback callback) {
return gin::CreateHandle(isolate, new ReplyChannel(std::move(callback)));
}
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override {
return gin::Wrappable<ReplyChannel>::GetObjectTemplateBuilder(isolate)
.SetMethod("sendReply", &ReplyChannel::SendReply);
}
const char* GetTypeName() override { return "ReplyChannel"; }
void SendError(const std::string& msg) {
v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
// If there's no current context, it means we're shutting down, so we
// don't need to send an event.
if (!isolate->GetCurrentContext().IsEmpty()) {
v8::HandleScope scope(isolate);
auto message = gin::DataObjectBuilder(isolate).Set("error", msg).Build();
SendReply(isolate, message);
}
}
private:
explicit ReplyChannel(InvokeCallback callback)
: callback_(std::move(callback)) {}
~ReplyChannel() override {
if (callback_)
SendError("reply was never sent");
}
bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> arg) {
if (!callback_)
return false;
blink::CloneableMessage message;
if (!gin::ConvertFromV8(isolate, arg, &message)) {
return false;
}
std::move(callback_).Run(std::move(message));
return true;
}
InvokeCallback callback_;
};
gin::WrapperInfo ReplyChannel::kWrapperInfo = {gin::kEmbedderNativeGin};
gin::Handle<gin_helper::internal::Event> WebContents::MakeEventWithSender(
v8::Isolate* isolate,
content::RenderFrameHost* frame,
electron::mojom::ElectronApiIPC::InvokeCallback callback) {
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper)) {
if (callback) {
// We must always invoke the callback if present.
ReplyChannel::Create(isolate, std::move(callback))
->SendError("WebContents was destroyed");
}
return gin::Handle<gin_helper::internal::Event>();
}
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
gin_helper::Dictionary dict(isolate, event.ToV8().As<v8::Object>());
if (callback)
dict.Set("_replyChannel",
ReplyChannel::Create(isolate, std::move(callback)));
if (frame) {
dict.Set("frameId", frame->GetRoutingID());
dict.Set("processId", frame->GetProcess()->GetID());
}
return event;
}
void WebContents::ReceivePostMessage(
const std::string& channel,
blink::TransferableMessage message,
content::RenderFrameHost* render_frame_host) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto wrapped_ports =
MessagePort::EntanglePorts(isolate, std::move(message.ports));
v8::Local<v8::Value> message_value =
electron::DeserializeV8Value(isolate, message);
EmitWithSender("-ipc-ports", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), false,
channel, message_value, std::move(wrapped_ports));
}
void WebContents::MessageSync(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::MessageSyncCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel);
// webContents.emit('-ipc-message-sync', new Event(sender, message), internal,
// channel, arguments);
EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::MessageHost(const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel);
// webContents.emit('ipc-message-host', new Event(), channel, args);
EmitWithSender("ipc-message-host", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), channel,
std::move(arguments));
}
void WebContents::UpdateDraggableRegions(
std::vector<mojom::DraggableRegionPtr> regions) {
if (owner_window() && owner_window()->has_frame())
return;
draggable_region_ = DraggableRegionsToSkRegion(regions);
}
void WebContents::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-start-navigation", navigation_handle);
}
void WebContents::DidRedirectNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-redirect-navigation", navigation_handle);
}
void WebContents::ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) {
// Don't focus content in an inactive window.
if (!owner_window())
return;
#if BUILDFLAG(IS_MAC)
if (!owner_window()->IsActive())
return;
#else
if (!owner_window()->widget()->IsActive())
return;
#endif
// Don't focus content after subframe navigations.
if (!navigation_handle->IsInMainFrame())
return;
// Only focus for top-level contents.
if (type_ != Type::kBrowserWindow)
return;
web_contents()->SetInitialFocus();
}
void WebContents::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (owner_window_) {
owner_window_->NotifyLayoutWindowControlsOverlay();
}
if (!navigation_handle->HasCommitted())
return;
bool is_main_frame = navigation_handle->IsInMainFrame();
content::RenderFrameHost* frame_host =
navigation_handle->GetRenderFrameHost();
int frame_process_id = -1, frame_routing_id = -1;
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
if (!navigation_handle->IsErrorPage()) {
// FIXME: All the Emit() calls below could potentially result in |this|
// being destroyed (by JS listening for the event and calling
// webContents.destroy()).
auto url = navigation_handle->GetURL();
bool is_same_document = navigation_handle->IsSameDocument();
if (is_same_document) {
Emit("did-navigate-in-page", url, is_main_frame, frame_process_id,
frame_routing_id);
} else {
const net::HttpResponseHeaders* http_response =
navigation_handle->GetResponseHeaders();
std::string http_status_text;
int http_response_code = -1;
if (http_response) {
http_status_text = http_response->GetStatusText();
http_response_code = http_response->response_code();
}
Emit("did-frame-navigate", url, http_response_code, http_status_text,
is_main_frame, frame_process_id, frame_routing_id);
if (is_main_frame) {
Emit("did-navigate", url, http_response_code, http_status_text);
}
}
if (IsGuest())
Emit("load-commit", url, is_main_frame);
} else {
auto url = navigation_handle->GetURL();
int code = navigation_handle->GetNetErrorCode();
auto description = net::ErrorToShortString(code);
Emit("did-fail-provisional-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
// Do not emit "did-fail-load" for canceled requests.
if (code != net::ERR_ABORTED) {
EmitWarning(
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()),
"Failed to load URL: " + url.possibly_invalid_spec() +
" with error: " + description,
"electron");
Emit("did-fail-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
}
}
content::NavigationEntry* entry = navigation_handle->GetNavigationEntry();
// This check is needed due to an issue in Chromium
// Check the Chromium issue to keep updated:
// https://bugs.chromium.org/p/chromium/issues/detail?id=1178663
// If a history entry has been made and the forward/back call has been made,
// proceed with setting the new title
if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK))
WebContents::TitleWasSet(entry);
}
void WebContents::TitleWasSet(content::NavigationEntry* entry) {
std::u16string final_title;
bool explicit_set = true;
if (entry) {
auto title = entry->GetTitle();
auto url = entry->GetURL();
if (url.SchemeIsFile() && title.empty()) {
final_title = base::UTF8ToUTF16(url.ExtractFileName());
explicit_set = false;
} else {
final_title = title;
}
} else {
final_title = web_contents()->GetTitle();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnPageTitleUpdated(final_title, explicit_set);
Emit("page-title-updated", final_title, explicit_set);
}
void WebContents::DidUpdateFaviconURL(
content::RenderFrameHost* render_frame_host,
const std::vector<blink::mojom::FaviconURLPtr>& urls) {
std::set<GURL> unique_urls;
for (const auto& iter : urls) {
if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon)
continue;
const GURL& url = iter->icon_url;
if (url.is_valid())
unique_urls.insert(url);
}
Emit("page-favicon-updated", unique_urls);
}
void WebContents::DevToolsReloadPage() {
Emit("devtools-reload-page");
}
void WebContents::DevToolsFocused() {
Emit("devtools-focused");
}
void WebContents::DevToolsOpened() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
DCHECK(inspectable_web_contents_);
DCHECK(inspectable_web_contents_->GetDevToolsWebContents());
auto handle = FromOrCreate(
isolate, inspectable_web_contents_->GetDevToolsWebContents());
devtools_web_contents_.Reset(isolate, handle.ToV8());
// Set inspected tabID.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "setInspectedTabId", base::Value(ID()));
// Inherit owner window in devtools when it doesn't have one.
auto* devtools = inspectable_web_contents_->GetDevToolsWebContents();
bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey());
if (owner_window() && !has_window)
handle->SetOwnerWindow(devtools, owner_window());
Emit("devtools-opened");
}
void WebContents::DevToolsClosed() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
devtools_web_contents_.Reset();
Emit("devtools-closed");
}
void WebContents::DevToolsResized() {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnDevToolsResized();
}
void WebContents::SetOwnerWindow(NativeWindow* owner_window) {
SetOwnerWindow(GetWebContents(), owner_window);
}
void WebContents::SetOwnerWindow(content::WebContents* web_contents,
NativeWindow* owner_window) {
if (owner_window_) {
owner_window_->RemoveBackgroundThrottlingSource(this);
}
if (owner_window) {
owner_window_ = owner_window->GetWeakPtr();
NativeWindowRelay::CreateForWebContents(web_contents,
owner_window->GetWeakPtr());
owner_window_->AddBackgroundThrottlingSource(this);
} else {
owner_window_ = nullptr;
web_contents->RemoveUserData(NativeWindowRelay::UserDataKey());
}
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetNativeWindow(owner_window);
}
content::WebContents* WebContents::GetWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetWebContents();
}
content::WebContents* WebContents::GetDevToolsWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetDevToolsWebContents();
}
void WebContents::WebContentsDestroyed() {
// Clear the pointer stored in wrapper.
if (GetAllWebContents().Lookup(id_))
GetAllWebContents().Remove(id_);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
wrapper->SetAlignedPointerInInternalField(0, nullptr);
// Tell WebViewGuestDelegate that the WebContents has been destroyed.
if (guest_delegate_)
guest_delegate_->WillDestroy();
Observe(nullptr);
Emit("destroyed");
}
void WebContents::NavigationEntryCommitted(
const content::LoadCommittedDetails& details) {
Emit("navigation-entry-committed", details.entry->GetURL(),
details.is_same_document, details.did_replace_entry);
}
bool WebContents::GetBackgroundThrottling() const {
return background_throttling_;
}
void WebContents::SetBackgroundThrottling(bool allowed) {
background_throttling_ = allowed;
if (owner_window_) {
owner_window_->UpdateBackgroundThrottlingState();
}
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (!rfh)
return;
auto* rwhv = rfh->GetView();
if (!rwhv)
return;
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (!rwh_impl)
return;
rwh_impl->disable_hidden_ = !background_throttling_;
web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed);
if (rwh_impl->is_hidden()) {
rwh_impl->WasShown({});
}
}
int WebContents::GetProcessID() const {
return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
}
base::ProcessId WebContents::GetOSProcessID() const {
base::ProcessHandle process_handle = web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->GetProcess()
.Handle();
return base::GetProcId(process_handle);
}
WebContents::Type WebContents::GetType() const {
return type_;
}
bool WebContents::Equal(const WebContents* web_contents) const {
return ID() == web_contents->ID();
}
GURL WebContents::GetURL() const {
return web_contents()->GetLastCommittedURL();
}
void WebContents::LoadURL(const GURL& url,
const gin_helper::Dictionary& options) {
if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL),
net::ErrorToShortString(net::ERR_INVALID_URL),
url.possibly_invalid_spec(), true);
return;
}
content::NavigationController::LoadURLParams params(url);
if (!options.Get("httpReferrer", ¶ms.referrer)) {
GURL http_referrer;
if (options.Get("httpReferrer", &http_referrer))
params.referrer =
content::Referrer(http_referrer.GetAsReferrer(),
network::mojom::ReferrerPolicy::kDefault);
}
std::string user_agent;
if (options.Get("userAgent", &user_agent))
SetUserAgent(user_agent);
std::string extra_headers;
if (options.Get("extraHeaders", &extra_headers))
params.extra_headers = extra_headers;
scoped_refptr<network::ResourceRequestBody> body;
if (options.Get("postData", &body)) {
params.post_data = body;
params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
}
GURL base_url_for_data_url;
if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
params.base_url_for_data_url = base_url_for_data_url;
params.load_type = content::NavigationController::LOAD_TYPE_DATA;
}
bool reload_ignoring_cache = false;
if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) &&
reload_ignoring_cache) {
params.reload_type = content::ReloadType::BYPASSING_CACHE;
}
// Calling LoadURLWithParams() can trigger JS which destroys |this|.
auto weak_this = GetWeakPtr();
params.transition_type = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
// It's not safe to start a new navigation or otherwise discard the current
// one while the call that started it is still on the stack. See
// http://crbug.com/347742.
auto& ctrl_impl = static_cast<content::NavigationControllerImpl&>(
web_contents()->GetController());
if (ctrl_impl.in_navigate_to_pending_entry()) {
Emit("did-fail-load", static_cast<int>(net::ERR_FAILED),
net::ErrorToShortString(net::ERR_FAILED), url.possibly_invalid_spec(),
true);
return;
}
// Discard non-committed entries to ensure we don't re-use a pending entry.
web_contents()->GetController().DiscardNonCommittedEntries();
web_contents()->GetController().LoadURLWithParams(params);
// β οΈWARNING!β οΈ
// LoadURLWithParams() triggers JS events which can call destroy() on |this|.
// It's not safe to assume that |this| points to valid memory at this point.
if (!weak_this || !web_contents())
return;
// Required to make beforeunload handler work.
NotifyUserActivation();
}
// TODO(MarshallOfSound): Figure out what we need to do with post data here, I
// believe the default behavior when we pass "true" is to phone out to the
// delegate and then the controller expects this method to be called again with
// "false" if the user approves the reload. For now this would result in
// ".reload()" calls on POST data domains failing silently. Passing false would
// result in them succeeding, but reposting which although more correct could be
// considering a breaking change.
void WebContents::Reload() {
web_contents()->GetController().Reload(content::ReloadType::NORMAL,
/* check_for_repost */ true);
}
void WebContents::ReloadIgnoringCache() {
web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE,
/* check_for_repost */ true);
}
void WebContents::DownloadURL(const GURL& url, gin::Arguments* args) {
std::map<std::string, std::string> headers;
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
if (options.Has("headers") && !options.Get("headers", &headers)) {
args->ThrowTypeError("Invalid value for headers - must be an object");
return;
}
}
std::unique_ptr<download::DownloadUrlParameters> download_params(
content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
web_contents(), url, MISSING_TRAFFIC_ANNOTATION));
for (const auto& [name, value] : headers) {
download_params->add_request_header(name, value);
}
auto* download_manager =
web_contents()->GetBrowserContext()->GetDownloadManager();
download_manager->DownloadUrl(std::move(download_params));
}
std::u16string WebContents::GetTitle() const {
return web_contents()->GetTitle();
}
bool WebContents::IsLoading() const {
return web_contents()->IsLoading();
}
bool WebContents::IsLoadingMainFrame() const {
return web_contents()->ShouldShowLoadingUI();
}
bool WebContents::IsWaitingForResponse() const {
return web_contents()->IsWaitingForResponse();
}
void WebContents::Stop() {
web_contents()->Stop();
}
bool WebContents::CanGoBack() const {
return web_contents()->GetController().CanGoBack();
}
void WebContents::GoBack() {
if (CanGoBack())
web_contents()->GetController().GoBack();
}
bool WebContents::CanGoForward() const {
return web_contents()->GetController().CanGoForward();
}
void WebContents::GoForward() {
if (CanGoForward())
web_contents()->GetController().GoForward();
}
bool WebContents::CanGoToOffset(int offset) const {
return web_contents()->GetController().CanGoToOffset(offset);
}
void WebContents::GoToOffset(int offset) {
if (CanGoToOffset(offset))
web_contents()->GetController().GoToOffset(offset);
}
bool WebContents::CanGoToIndex(int index) const {
return index >= 0 && index < GetHistoryLength();
}
void WebContents::GoToIndex(int index) {
if (CanGoToIndex(index))
web_contents()->GetController().GoToIndex(index);
}
int WebContents::GetActiveIndex() const {
return web_contents()->GetController().GetCurrentEntryIndex();
}
void WebContents::ClearHistory() {
// In some rare cases (normally while there is no real history) we are in a
// state where we can't prune navigation entries
if (web_contents()->GetController().CanPruneAllButLastCommitted()) {
web_contents()->GetController().PruneAllButLastCommitted();
}
}
int WebContents::GetHistoryLength() const {
return web_contents()->GetController().GetEntryCount();
}
const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy;
}
void WebContents::SetWebRTCIPHandlingPolicy(
const std::string& webrtc_ip_handling_policy) {
if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
return;
web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
webrtc_ip_handling_policy;
web_contents()->SyncRendererPrefs();
}
v8::Local<v8::Value> WebContents::GetWebRTCUDPPortRange(
v8::Isolate* isolate) const {
auto* prefs = web_contents()->GetMutableRendererPrefs();
auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
dict.Set("min", static_cast<uint32_t>(prefs->webrtc_udp_min_port));
dict.Set("max", static_cast<uint32_t>(prefs->webrtc_udp_max_port));
return dict.GetHandle();
}
void WebContents::SetWebRTCUDPPortRange(gin::Arguments* args) {
uint32_t min = 0, max = 0;
gin_helper::Dictionary range;
if (!args->GetNext(&range) || !range.Get("min", &min) ||
!range.Get("max", &max)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'min' and 'max' are both required");
return;
}
if ((0 == min && 0 != max) || max > UINT16_MAX) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError(
"'min' and 'max' must be in the (0, 65535] range or [0, 0]");
return;
}
if (min > max) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'max' must be greater than or equal to 'min'");
return;
}
auto* prefs = web_contents()->GetMutableRendererPrefs();
if (prefs->webrtc_udp_min_port == static_cast<uint16_t>(min) &&
prefs->webrtc_udp_max_port == static_cast<uint16_t>(max)) {
return;
}
prefs->webrtc_udp_min_port = min;
prefs->webrtc_udp_max_port = max;
web_contents()->SyncRendererPrefs();
}
std::string WebContents::GetMediaSourceID(
content::WebContents* request_web_contents) {
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host)
return std::string();
content::DesktopMediaID media_id(
content::DesktopMediaID::TYPE_WEB_CONTENTS,
content::DesktopMediaID::kNullId,
content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(),
frame_host->GetRoutingID()));
auto* request_frame_host = request_web_contents->GetPrimaryMainFrame();
if (!request_frame_host)
return std::string();
std::string id =
content::DesktopStreamsRegistry::GetInstance()->RegisterStream(
request_frame_host->GetProcess()->GetID(),
request_frame_host->GetRoutingID(),
url::Origin::Create(request_frame_host->GetLastCommittedURL()
.DeprecatedGetOriginAsURL()),
media_id, content::kRegistryStreamTypeTab);
return id;
}
bool WebContents::IsCrashed() const {
return web_contents()->IsCrashed();
}
void WebContents::ForcefullyCrashRenderer() {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
if (!rwh)
return;
content::RenderProcessHost* rph = rwh->GetProcess();
if (rph) {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// A generic |CrashDumpHungChildProcess()| is not implemented for Linux.
// Instead we send an explicit IPC to crash on the renderer's IO thread.
rph->ForceCrash();
#else
// Try to generate a crash report for the hung process.
#if !IS_MAS_BUILD()
CrashDumpHungChildProcess(rph->GetProcess().Handle());
#endif
rph->Shutdown(content::RESULT_CODE_HUNG);
#endif
}
}
void WebContents::SetUserAgent(const std::string& user_agent) {
blink::UserAgentOverride ua_override;
ua_override.ua_string_override = user_agent;
if (!user_agent.empty())
ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata();
web_contents()->SetUserAgentOverride(ua_override, false);
}
std::string WebContents::GetUserAgent() {
return web_contents()->GetUserAgentOverride().ua_string_override;
}
v8::Local<v8::Promise> WebContents::SavePage(
const base::FilePath& full_file_path,
const content::SavePageType& save_type) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!full_file_path.IsAbsolute()) {
promise.RejectWithErrorMessage("Path must be absolute");
return handle;
}
auto* handler = new SavePageHandler(web_contents(), std::move(promise));
handler->Handle(full_file_path, save_type);
return handle;
}
void WebContents::OpenDevTools(gin::Arguments* args) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
std::string state;
if (type_ == Type::kWebView || type_ == Type::kBackgroundPage ||
!owner_window()) {
state = "detach";
}
bool activate = true;
std::string title;
if (args && args->Length() == 1) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("mode", &state);
options.Get("activate", &activate);
options.Get("title", &title);
}
}
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->SetDockState(state);
inspectable_web_contents_->SetDevToolsTitle(base::UTF8ToUTF16(title));
inspectable_web_contents_->ShowDevTools(activate);
}
void WebContents::CloseDevTools() {
if (type_ == Type::kRemote)
return;
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->CloseDevTools();
}
bool WebContents::IsDevToolsOpened() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->IsDevToolsViewShowing();
}
std::u16string WebContents::GetDevToolsTitle() {
if (type_ == Type::kRemote)
return std::u16string();
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->GetDevToolsTitle();
}
void WebContents::SetDevToolsTitle(const std::u16string& title) {
inspectable_web_contents_->SetDevToolsTitle(title);
}
bool WebContents::IsDevToolsFocused() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->GetView()->IsDevToolsViewFocused();
}
void WebContents::EnableDeviceEmulation(
const blink::DeviceEmulationParams& params) {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->EnableDeviceEmulation(params);
}
}
}
void WebContents::DisableDeviceEmulation() {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->DisableDeviceEmulation();
}
}
}
void WebContents::ToggleDevTools() {
if (IsDevToolsOpened())
CloseDevTools();
else
OpenDevTools(nullptr);
}
void WebContents::InspectElement(int x, int y) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
DCHECK(inspectable_web_contents_);
if (!inspectable_web_contents_->GetDevToolsWebContents())
OpenDevTools(nullptr);
inspectable_web_contents_->InspectElement(x, y);
}
void WebContents::InspectSharedWorkerById(const std::string& workerId) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
if (agent_host->GetId() == workerId) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
}
std::vector<scoped_refptr<content::DevToolsAgentHost>>
WebContents::GetAllSharedWorkers() {
std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers;
if (type_ == Type::kRemote)
return shared_workers;
if (!enable_devtools_)
return shared_workers;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
shared_workers.push_back(agent_host);
}
}
return shared_workers;
}
void WebContents::InspectSharedWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::InspectServiceWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeServiceWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::SetIgnoreMenuShortcuts(bool ignore) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
DCHECK(web_preferences);
web_preferences->SetIgnoreMenuShortcuts(ignore);
}
void WebContents::SetAudioMuted(bool muted) {
web_contents()->SetAudioMuted(muted);
}
bool WebContents::IsAudioMuted() {
return web_contents()->IsAudioMuted();
}
bool WebContents::IsCurrentlyAudible() {
return web_contents()->IsCurrentlyAudible();
}
#if BUILDFLAG(ENABLE_PRINTING)
void WebContents::OnGetDeviceNameToUse(
base::Value::Dict print_settings,
printing::CompletionCallback print_callback,
bool silent,
// <error, device_name>
std::pair<std::string, std::u16string> info) {
// The content::WebContents might be already deleted at this point, and the
// PrintViewManagerElectron class does not do null check.
if (!web_contents()) {
if (print_callback)
std::move(print_callback).Run(false, "failed");
return;
}
if (!info.first.empty()) {
if (print_callback)
std::move(print_callback).Run(false, info.first);
return;
}
// If the user has passed a deviceName use it, otherwise use default printer.
print_settings.Set(printing::kSettingDeviceName, info.second);
auto* print_view_manager =
PrintViewManagerElectron::FromWebContents(web_contents());
if (!print_view_manager)
return;
auto* focused_frame = web_contents()->GetFocusedFrame();
auto* rfh = focused_frame && focused_frame->HasSelection()
? focused_frame
: web_contents()->GetPrimaryMainFrame();
print_view_manager->PrintNow(rfh, silent, std::move(print_settings),
std::move(print_callback));
}
void WebContents::Print(gin::Arguments* args) {
auto options = gin_helper::Dictionary::CreateEmpty(args->isolate());
base::Value::Dict settings;
if (args->Length() >= 1 && !args->GetNext(&options)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid print settings specified.");
return;
}
printing::CompletionCallback callback;
if (args->Length() == 2 && !args->GetNext(&callback)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid optional callback provided.");
return;
}
// Set optional silent printing
bool silent = false;
options.Get("silent", &silent);
bool print_background = false;
options.Get("printBackground", &print_background);
settings.Set(printing::kSettingShouldPrintBackgrounds, print_background);
// Set custom margin settings
auto margins = gin_helper::Dictionary::CreateEmpty(args->isolate());
if (options.Get("margins", &margins)) {
printing::mojom::MarginType margin_type =
printing::mojom::MarginType::kDefaultMargins;
margins.Get("marginType", &margin_type);
settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type));
if (margin_type == printing::mojom::MarginType::kCustomMargins) {
base::Value::Dict custom_margins;
int top = 0;
margins.Get("top", &top);
custom_margins.Set(printing::kSettingMarginTop, top);
int bottom = 0;
margins.Get("bottom", &bottom);
custom_margins.Set(printing::kSettingMarginBottom, bottom);
int left = 0;
margins.Get("left", &left);
custom_margins.Set(printing::kSettingMarginLeft, left);
int right = 0;
margins.Get("right", &right);
custom_margins.Set(printing::kSettingMarginRight, right);
settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins));
}
} else {
settings.Set(
printing::kSettingMarginsType,
static_cast<int>(printing::mojom::MarginType::kDefaultMargins));
}
// Set whether to print color or greyscale
bool print_color = true;
options.Get("color", &print_color);
auto const color_model = print_color ? printing::mojom::ColorModel::kColor
: printing::mojom::ColorModel::kGray;
settings.Set(printing::kSettingColor, static_cast<int>(color_model));
// Is the orientation landscape or portrait.
bool landscape = false;
options.Get("landscape", &landscape);
settings.Set(printing::kSettingLandscape, landscape);
// We set the default to the system's default printer and only update
// if at the Chromium level if the user overrides.
// Printer device name as opened by the OS.
std::u16string device_name;
options.Get("deviceName", &device_name);
int scale_factor = 100;
options.Get("scaleFactor", &scale_factor);
settings.Set(printing::kSettingScaleFactor, scale_factor);
int pages_per_sheet = 1;
options.Get("pagesPerSheet", &pages_per_sheet);
settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet);
// True if the user wants to print with collate.
bool collate = true;
options.Get("collate", &collate);
settings.Set(printing::kSettingCollate, collate);
// The number of individual copies to print
int copies = 1;
options.Get("copies", &copies);
settings.Set(printing::kSettingCopies, copies);
// Strings to be printed as headers and footers if requested by the user.
std::string header;
options.Get("header", &header);
std::string footer;
options.Get("footer", &footer);
if (!(header.empty() && footer.empty())) {
settings.Set(printing::kSettingHeaderFooterEnabled, true);
settings.Set(printing::kSettingHeaderFooterTitle, header);
settings.Set(printing::kSettingHeaderFooterURL, footer);
} else {
settings.Set(printing::kSettingHeaderFooterEnabled, false);
}
// We don't want to allow the user to enable these settings
// but we need to set them or a CHECK is hit.
settings.Set(printing::kSettingPrinterType,
static_cast<int>(printing::mojom::PrinterType::kLocal));
settings.Set(printing::kSettingShouldPrintSelectionOnly, false);
settings.Set(printing::kSettingRasterizePdf, false);
// Set custom page ranges to print
std::vector<gin_helper::Dictionary> page_ranges;
if (options.Get("pageRanges", &page_ranges)) {
base::Value::List page_range_list;
for (auto& range : page_ranges) {
int from, to;
if (range.Get("from", &from) && range.Get("to", &to)) {
base::Value::Dict range_dict;
// Chromium uses 1-based page ranges, so increment each by 1.
range_dict.Set(printing::kSettingPageRangeFrom, from + 1);
range_dict.Set(printing::kSettingPageRangeTo, to + 1);
page_range_list.Append(std::move(range_dict));
} else {
continue;
}
}
if (!page_range_list.empty())
settings.Set(printing::kSettingPageRange, std::move(page_range_list));
}
// Duplex type user wants to use.
printing::mojom::DuplexMode duplex_mode =
printing::mojom::DuplexMode::kSimplex;
options.Get("duplexMode", &duplex_mode);
settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode));
// We've already done necessary parameter sanitization at the
// JS level, so we can simply pass this through.
base::Value media_size(base::Value::Type::DICT);
if (options.Get("mediaSize", &media_size))
settings.Set(printing::kSettingMediaSize, std::move(media_size));
// Set custom dots per inch (dpi)
gin_helper::Dictionary dpi_settings;
int dpi = 72;
if (options.Get("dpi", &dpi_settings)) {
int horizontal = 72;
dpi_settings.Get("horizontal", &horizontal);
settings.Set(printing::kSettingDpiHorizontal, horizontal);
int vertical = 72;
dpi_settings.Get("vertical", &vertical);
settings.Set(printing::kSettingDpiVertical, vertical);
} else {
settings.Set(printing::kSettingDpiHorizontal, dpi);
settings.Set(printing::kSettingDpiVertical, dpi);
}
print_task_runner_->PostTaskAndReplyWithResult(
FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name),
base::BindOnce(&WebContents::OnGetDeviceNameToUse,
weak_factory_.GetWeakPtr(), std::move(settings),
std::move(callback), silent));
}
// Partially duplicated and modified from
// headless/lib/browser/protocol/page_handler.cc;l=41
v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
// This allows us to track headless printing calls.
auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID);
auto landscape = settings.GetDict().FindBool("landscape");
auto display_header_footer =
settings.GetDict().FindBool("displayHeaderFooter");
auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds");
auto scale = settings.GetDict().FindDouble("scale");
auto paper_width = settings.GetDict().FindDouble("paperWidth");
auto paper_height = settings.GetDict().FindDouble("paperHeight");
auto margin_top = settings.GetDict().FindDouble("marginTop");
auto margin_bottom = settings.GetDict().FindDouble("marginBottom");
auto margin_left = settings.GetDict().FindDouble("marginLeft");
auto margin_right = settings.GetDict().FindDouble("marginRight");
auto page_ranges = *settings.GetDict().FindString("pageRanges");
auto header_template = *settings.GetDict().FindString("headerTemplate");
auto footer_template = *settings.GetDict().FindString("footerTemplate");
auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize");
auto generate_tagged_pdf = settings.GetDict().FindBool("generateTaggedPDF");
absl::variant<printing::mojom::PrintPagesParamsPtr, std::string>
print_pages_params = print_to_pdf::GetPrintPagesParams(
web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(),
landscape, display_header_footer, print_background, scale,
paper_width, paper_height, margin_top, margin_bottom, margin_left,
margin_right, absl::make_optional(header_template),
absl::make_optional(footer_template), prefer_css_page_size,
generate_tagged_pdf);
if (absl::holds_alternative<std::string>(print_pages_params)) {
auto error = absl::get<std::string>(print_pages_params);
promise.RejectWithErrorMessage("Invalid print parameters: " + error);
return handle;
}
auto* manager = PrintViewManagerElectron::FromWebContents(web_contents());
if (!manager) {
promise.RejectWithErrorMessage("Failed to find print manager");
return handle;
}
auto params = std::move(
absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params));
params->params->document_cookie = unique_id.value_or(0);
manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges,
std::move(params),
base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(),
std::move(promise)));
return handle;
}
void WebContents::OnPDFCreated(
gin_helper::Promise<v8::Local<v8::Value>> promise,
print_to_pdf::PdfPrintResult print_result,
scoped_refptr<base::RefCountedMemory> data) {
if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) {
promise.RejectWithErrorMessage(
"Failed to generate PDF: " +
print_to_pdf::PdfPrintResultToString(print_result));
return;
}
v8::Isolate* isolate = promise.isolate();
gin_helper::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate, promise.GetContext()));
v8::Local<v8::Value> buffer =
node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()),
data->size())
.ToLocalChecked();
promise.Resolve(buffer);
}
#endif
void WebContents::AddWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsAddFileSystem(std::string(), path);
}
void WebContents::RemoveWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsRemoveFileSystem(path);
}
void WebContents::Undo() {
web_contents()->Undo();
}
void WebContents::Redo() {
web_contents()->Redo();
}
void WebContents::Cut() {
web_contents()->Cut();
}
void WebContents::Copy() {
web_contents()->Copy();
}
void WebContents::CenterSelection() {
web_contents()->CenterSelection();
}
void WebContents::Paste() {
web_contents()->Paste();
}
void WebContents::PasteAndMatchStyle() {
web_contents()->PasteAndMatchStyle();
}
void WebContents::Delete() {
web_contents()->Delete();
}
void WebContents::SelectAll() {
web_contents()->SelectAll();
}
void WebContents::Unselect() {
web_contents()->CollapseSelection();
}
void WebContents::ScrollToTopOfDocument() {
web_contents()->ScrollToTopOfDocument();
}
void WebContents::ScrollToBottomOfDocument() {
web_contents()->ScrollToBottomOfDocument();
}
void WebContents::AdjustSelectionByCharacterOffset(gin::Arguments* args) {
int start_adjust = 0;
int end_adjust = 0;
gin_helper::Dictionary dict;
if (args->GetNext(&dict)) {
dict.Get("start", &start_adjust);
dict.Get("matchCase", &end_adjust);
}
// The selection menu is a Chrome-specific piece of UI.
// TODO(codebytere): maybe surface as an event in the future?
web_contents()->AdjustSelectionByCharacterOffset(
start_adjust, end_adjust, false /* show_selection_menu */);
}
void WebContents::Replace(const std::u16string& word) {
web_contents()->Replace(word);
}
void WebContents::ReplaceMisspelling(const std::u16string& word) {
web_contents()->ReplaceMisspelling(word);
}
uint32_t WebContents::FindInPage(gin::Arguments* args) {
std::u16string search_text;
if (!args->GetNext(&search_text) || search_text.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must provide a non-empty search content");
return 0;
}
uint32_t request_id = ++find_in_page_request_id_;
gin_helper::Dictionary dict;
auto options = blink::mojom::FindOptions::New();
if (args->GetNext(&dict)) {
dict.Get("forward", &options->forward);
dict.Get("matchCase", &options->match_case);
dict.Get("findNext", &options->new_session);
}
web_contents()->Find(request_id, search_text, std::move(options));
return request_id;
}
void WebContents::StopFindInPage(content::StopFindAction action) {
web_contents()->StopFinding(action);
}
void WebContents::ShowDefinitionForSelection() {
#if BUILDFLAG(IS_MAC)
auto* const view = web_contents()->GetRenderWidgetHostView();
if (view)
view->ShowDefinitionForSelection();
#endif
}
void WebContents::CopyImageAt(int x, int y) {
auto* const host = web_contents()->GetPrimaryMainFrame();
if (host)
host->CopyImageAt(x, y);
}
void WebContents::Focus() {
// Focusing on WebContents does not automatically focus the window on macOS
// and Linux, do it manually to match the behavior on Windows.
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
if (owner_window())
owner_window()->Focus(true);
#endif
web_contents()->Focus();
}
#if !BUILDFLAG(IS_MAC)
bool WebContents::IsFocused() const {
auto* view = web_contents()->GetRenderWidgetHostView();
if (!view)
return false;
if (GetType() != Type::kBackgroundPage) {
auto* window = web_contents()->GetNativeView()->GetToplevelWindow();
if (window && !window->IsVisible())
return false;
}
return view->HasFocus();
}
#endif
void WebContents::SendInputEvent(v8::Isolate* isolate,
v8::Local<v8::Value> input_event) {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
blink::WebInputEvent::Type type =
gin::GetWebInputEventType(isolate, input_event);
if (blink::WebInputEvent::IsMouseEventType(type)) {
blink::WebMouseEvent mouse_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) {
if (IsOffScreen()) {
GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event);
} else {
rwh->ForwardMouseEvent(mouse_event);
}
return;
}
} else if (blink::WebInputEvent::IsKeyboardEventType(type)) {
content::NativeWebKeyboardEvent keyboard_event(
blink::WebKeyboardEvent::Type::kRawKeyDown,
blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow());
if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) {
// For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`.
if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown)
keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown);
rwh->ForwardKeyboardEvent(keyboard_event);
return;
}
} else if (type == blink::WebInputEvent::Type::kMouseWheel) {
blink::WebMouseWheelEvent mouse_wheel_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
if (IsOffScreen()) {
GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent(
mouse_wheel_event);
} else {
// Chromium expects phase info in wheel events (and applies a
// DCHECK to verify it). See: https://crbug.com/756524.
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
// Send a synthetic wheel event with phaseEnded to finish scrolling.
mouse_wheel_event.has_synthetic_phase = true;
mouse_wheel_event.delta_x = 0;
mouse_wheel_event.delta_y = 0;
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kEventNonBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
}
return;
}
}
isolate->ThrowException(
v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object")));
}
void WebContents::BeginFrameSubscription(gin::Arguments* args) {
bool only_dirty = false;
FrameSubscriber::FrameCaptureCallback callback;
if (args->Length() > 1) {
if (!args->GetNext(&only_dirty)) {
args->ThrowError();
return;
}
}
if (!args->GetNext(&callback)) {
args->ThrowError();
return;
}
frame_subscriber_ =
std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty);
}
void WebContents::EndFrameSubscription() {
frame_subscriber_.reset();
}
void WebContents::StartDrag(const gin_helper::Dictionary& item,
gin::Arguments* args) {
base::FilePath file;
std::vector<base::FilePath> files;
if (!item.Get("files", &files) && item.Get("file", &file)) {
files.push_back(file);
}
v8::Local<v8::Value> icon_value;
if (!item.Get("icon", &icon_value)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'icon' parameter is required");
return;
}
NativeImage* icon = nullptr;
if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) ||
icon->image().IsEmpty()) {
return;
}
// Start dragging.
if (!files.empty()) {
base::CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop allow;
DragFileItems(files, icon->image(), web_contents()->GetNativeView());
} else {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must specify either 'file' or 'files' option");
}
}
v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) {
gin_helper::Promise<gfx::Image> promise(args->isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
gfx::Rect rect;
args->GetNext(&rect);
bool stay_hidden = false;
bool stay_awake = false;
if (args && args->Length() == 2) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("stayHidden", &stay_hidden);
options.Get("stayAwake", &stay_awake);
}
}
auto* const view = web_contents()->GetRenderWidgetHostView();
if (!view || view->GetViewBounds().size().IsEmpty()) {
promise.Resolve(gfx::Image());
return handle;
}
if (!view->IsSurfaceAvailableForCopy()) {
promise.RejectWithErrorMessage(
"Current display surface not available for capture");
return handle;
}
auto capture_handle = web_contents()->IncrementCapturerCount(
rect.size(), stay_hidden, stay_awake);
// Capture full page if user doesn't specify a |rect|.
const gfx::Size view_size =
rect.IsEmpty() ? view->GetViewBounds().size() : rect.size();
// By default, the requested bitmap size is the view size in screen
// coordinates. However, if there's more pixel detail available on the
// current system, increase the requested bitmap size to capture it all.
gfx::Size bitmap_size = view_size;
const gfx::NativeView native_view = view->GetNativeView();
const float scale = display::Screen::GetScreen()
->GetDisplayNearestView(native_view)
.device_scale_factor();
if (scale > 1.0f)
bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size,
base::BindOnce(&OnCapturePageDone, std::move(promise),
std::move(capture_handle)));
return handle;
}
bool WebContents::IsBeingCaptured() {
return web_contents()->IsBeingCaptured();
}
void WebContents::OnCursorChanged(const ui::Cursor& cursor) {
if (cursor.type() == ui::mojom::CursorType::kCustom) {
Emit("cursor-changed", CursorTypeToString(cursor.type()),
gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()),
cursor.image_scale_factor(),
gfx::Size(cursor.custom_bitmap().width(),
cursor.custom_bitmap().height()),
cursor.custom_hotspot());
} else {
Emit("cursor-changed", CursorTypeToString(cursor.type()));
}
}
bool WebContents::IsGuest() const {
return type_ == Type::kWebView;
}
void WebContents::AttachToIframe(content::WebContents* embedder_web_contents,
int embedder_frame_id) {
attached_ = true;
if (guest_delegate_)
guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id);
}
bool WebContents::IsOffScreen() const {
return type_ == Type::kOffScreen;
}
void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap));
}
void WebContents::StartPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(true);
}
void WebContents::StopPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(false);
}
bool WebContents::IsPainting() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv && osr_wcv->IsPainting();
}
void WebContents::SetFrameRate(int frame_rate) {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetFrameRate(frame_rate);
}
int WebContents::GetFrameRate() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv ? osr_wcv->GetFrameRate() : 0;
}
void WebContents::Invalidate() {
if (IsOffScreen()) {
auto* osr_rwhv = GetOffScreenRenderWidgetHostView();
if (osr_rwhv)
osr_rwhv->Invalidate();
} else {
auto* const window = owner_window();
if (window)
window->Invalidate();
}
}
gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) {
if (IsOffScreen() && wc == web_contents()) {
auto* relay = NativeWindowRelay::FromWebContents(web_contents());
if (relay) {
auto* owner_window = relay->GetNativeWindow();
return owner_window ? owner_window->GetSize() : gfx::Size();
}
}
return gfx::Size();
}
void WebContents::SetZoomLevel(double level) {
zoom_controller_->SetZoomLevel(level);
}
double WebContents::GetZoomLevel() const {
return zoom_controller_->GetZoomLevel();
}
void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower,
double factor) {
if (factor < std::numeric_limits<double>::epsilon()) {
thrower.ThrowError("'zoomFactor' must be a double greater than 0.0");
return;
}
auto level = blink::PageZoomFactorToZoomLevel(factor);
SetZoomLevel(level);
}
double WebContents::GetZoomFactor() const {
auto level = GetZoomLevel();
return blink::PageZoomLevelToZoomFactor(level);
}
void WebContents::SetTemporaryZoomLevel(double level) {
zoom_controller_->SetTemporaryZoomLevel(level);
}
void WebContents::DoGetZoomLevel(
electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback
callback) {
std::move(callback).Run(GetZoomLevel());
}
std::vector<base::FilePath> WebContents::GetPreloadPaths() const {
auto result = SessionPreferences::GetValidPreloads(GetBrowserContext());
if (auto* web_preferences = WebContentsPreferences::From(web_contents())) {
base::FilePath preload;
if (web_preferences->GetPreloadPath(&preload)) {
result.emplace_back(preload);
}
}
return result;
}
v8::Local<v8::Value> WebContents::GetLastWebPreferences(
v8::Isolate* isolate) const {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (!web_preferences)
return v8::Null(isolate);
return gin::ConvertToV8(isolate, *web_preferences->last_preference());
}
v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow(
v8::Isolate* isolate) const {
if (owner_window())
return BrowserWindow::From(isolate, owner_window());
else
return v8::Null(isolate);
}
v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
return v8::Local<v8::Value>::New(isolate, session_);
}
content::WebContents* WebContents::HostWebContents() const {
if (!embedder_)
return nullptr;
return embedder_->web_contents();
}
void WebContents::SetEmbedder(const WebContents* embedder) {
if (embedder) {
NativeWindow* owner_window = nullptr;
auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
if (relay) {
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
content::RenderWidgetHostView* rwhv =
web_contents()->GetRenderWidgetHostView();
if (rwhv) {
rwhv->Hide();
rwhv->Show();
}
}
}
void WebContents::SetDevToolsWebContents(const WebContents* devtools) {
if (inspectable_web_contents_)
inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents());
}
v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const {
gfx::NativeView ptr = web_contents()->GetNativeView();
auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr),
sizeof(gfx::NativeView));
if (buffer.IsEmpty())
return v8::Null(isolate);
else
return buffer.ToLocalChecked();
}
v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
if (devtools_web_contents_.IsEmpty())
return v8::Null(isolate);
else
return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
}
v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
if (debugger_.IsEmpty()) {
auto handle = electron::api::Debugger::Create(isolate, web_contents());
debugger_.Reset(isolate, handle.ToV8());
}
return v8::Local<v8::Value>::New(isolate, debugger_);
}
content::RenderFrameHost* WebContents::MainFrame() {
return web_contents()->GetPrimaryMainFrame();
}
content::RenderFrameHost* WebContents::Opener() {
return web_contents()->GetOpener();
}
void WebContents::NotifyUserActivation() {
content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame();
if (frame)
frame->NotifyUserActivation(
blink::mojom::UserActivationNotificationType::kInteraction);
}
void WebContents::SetImageAnimationPolicy(const std::string& new_policy) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
web_preferences->SetImageAnimationPolicy(new_policy);
web_contents()->OnWebPreferencesChanged();
}
void WebContents::OnInputEvent(const blink::WebInputEvent& event) {
Emit("input-event", event);
}
v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage("Failed to create memory dump");
return handle;
}
auto pid = frame_host->GetProcess()->GetProcess().Pid();
v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext());
memory_instrumentation::MemoryInstrumentation::GetInstance()
->RequestGlobalDumpForPid(
pid, std::vector<std::string>(),
base::BindOnce(&ElectronBindings::DidReceiveMemoryDump,
std::move(context), std::move(promise), pid));
return handle;
}
v8::Local<v8::Promise> WebContents::TakeHeapSnapshot(
v8::Isolate* isolate,
const base::FilePath& file_path) {
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
ScopedAllowBlockingForElectron allow_blocking;
uint32_t flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE;
// The snapshot file is passed to an untrusted process.
flags = base::File::AddFlagsForPassingToUntrustedProcess(flags);
base::File file(file_path, flags);
if (!file.IsValid()) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with invalid file path " +
#if BUILDFLAG(IS_WIN)
base::WideToUTF8(file_path.value()));
#else
file_path.value());
#endif
return handle;
}
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with invalid webContents main frame");
return handle;
}
if (!frame_host->IsRenderFrameLive()) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with nonexistent render frame");
return handle;
}
// This dance with `base::Owned` is to ensure that the interface stays alive
// until the callback is called. Otherwise it would be closed at the end of
// this function.
auto electron_renderer =
std::make_unique<mojo::Remote<mojom::ElectronRenderer>>();
frame_host->GetRemoteInterfaces()->GetInterface(
electron_renderer->BindNewPipeAndPassReceiver());
auto* raw_ptr = electron_renderer.get();
(*raw_ptr)->TakeHeapSnapshot(
mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())),
base::BindOnce(
[](mojo::Remote<mojom::ElectronRenderer>* ep,
gin_helper::Promise<void> promise, bool success) {
if (success) {
promise.Resolve();
} else {
promise.RejectWithErrorMessage("Failed to take heap snapshot");
}
},
base::Owned(std::move(electron_renderer)), std::move(promise)));
return handle;
}
void WebContents::UpdatePreferredSize(content::WebContents* web_contents,
const gfx::Size& pref_size) {
Emit("preferred-size-changed", pref_size);
}
bool WebContents::CanOverscrollContent() {
return false;
}
std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper(
content::RenderFrameHost* frame,
content::EyeDropperListener* listener) {
return ShowEyeDropper(frame, listener);
}
void WebContents::RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) {
FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener),
params);
}
void WebContents::EnumerateDirectory(
content::WebContents* web_contents,
scoped_refptr<content::FileSelectListener> listener,
const base::FilePath& path) {
FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path);
}
bool WebContents::IsFullscreenForTabOrPending(
const content::WebContents* source) {
if (!owner_window())
return is_html_fullscreen();
bool in_transition = owner_window()->fullscreen_transition_state() !=
NativeWindow::FullScreenTransitionState::kNone;
bool is_html_transition = owner_window()->fullscreen_transition_type() ==
NativeWindow::FullScreenTransitionType::kHTML;
return is_html_fullscreen() || (in_transition && is_html_transition);
}
content::FullscreenState WebContents::GetFullscreenState(
const content::WebContents* source) const {
// `const_cast` here because EAM does not have const getters
return const_cast<ExclusiveAccessManager*>(&exclusive_access_manager_)
->fullscreen_controller()
->GetFullscreenState(source);
}
bool WebContents::TakeFocus(content::WebContents* source, bool reverse) {
if (source && source->GetOutermostWebContents() == source) {
// If this is the outermost web contents and the user has tabbed or
// shift + tabbed through all the elements, reset the focus back to
// the first or last element so that it doesn't stay in the body.
source->FocusThroughTabTraversal(reverse);
return true;
}
return false;
}
content::PictureInPictureResult WebContents::EnterPictureInPicture(
content::WebContents* web_contents) {
return PictureInPictureWindowManager::GetInstance()
->EnterVideoPictureInPicture(web_contents);
}
void WebContents::ExitPictureInPicture() {
PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture();
}
void WebContents::DevToolsSaveToFile(const std::string& url,
const std::string& content,
bool save_as) {
base::FilePath path;
auto it = saved_files_.find(url);
if (it != saved_files_.end() && !save_as) {
path = it->second;
} else {
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.title = url;
settings.default_path = base::FilePath::FromUTF8Unsafe(url);
if (!file_dialog::ShowSaveDialogSync(settings, &path)) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "canceledSaveURL", base::Value(url));
return;
}
}
saved_files_[url] = path;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "savedURL", base::Value(url),
base::Value(path.AsUTF8Unsafe()));
file_task_runner_->PostTask(FROM_HERE,
base::BindOnce(&WriteToFile, path, content));
}
void WebContents::DevToolsAppendToFile(const std::string& url,
const std::string& content) {
auto it = saved_files_.find(url);
if (it == saved_files_.end())
return;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL",
base::Value(url));
file_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&AppendToFile, it->second, content));
}
void WebContents::DevToolsRequestFileSystems() {
auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents());
if (file_system_paths.empty()) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List()));
return;
}
std::vector<FileSystem> file_systems;
for (const auto& file_system_path : file_system_paths) {
base::FilePath path =
base::FilePath::FromUTF8Unsafe(file_system_path.first);
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
FileSystem file_system =
CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id,
file_system_path.first, file_system_path.second);
file_systems.push_back(file_system);
}
base::Value::List file_system_value;
for (const auto& file_system : file_systems)
file_system_value.Append(CreateFileSystemValue(file_system));
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded",
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsAddFileSystem(
const std::string& type,
const base::FilePath& file_system_path) {
base::FilePath path = file_system_path;
if (path.empty()) {
std::vector<base::FilePath> paths;
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY;
if (!file_dialog::ShowOpenDialogSync(settings, &paths))
return;
path = paths[0];
}
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe()))
return;
FileSystem file_system = CreateFileSystemStruct(
GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type);
base::Value::Dict file_system_value = CreateFileSystemValue(file_system);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Set(path.AsUTF8Unsafe(), type);
std::string error = ""; // No error
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemAdded", base::Value(error),
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsRemoveFileSystem(
const base::FilePath& file_system_path) {
if (!inspectable_web_contents_)
return;
std::string path = file_system_path.AsUTF8Unsafe();
storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath(
file_system_path);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Remove(path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemRemoved", base::Value(path));
}
void WebContents::DevToolsIndexPath(
int request_id,
const std::string& file_system_path,
const std::string& excluded_folders_message) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsIndexingDone(request_id, file_system_path);
return;
}
if (devtools_indexing_jobs_.count(request_id) != 0)
return;
std::vector<std::string> excluded_folders;
absl::optional<base::Value> parsed_excluded_folders =
base::JSONReader::Read(excluded_folders_message);
if (parsed_excluded_folders && parsed_excluded_folders->is_list()) {
for (const base::Value& folder_path : parsed_excluded_folders->GetList()) {
if (folder_path.is_string())
excluded_folders.push_back(folder_path.GetString());
}
}
devtools_indexing_jobs_[request_id] =
scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>(
devtools_file_system_indexer_->IndexPath(
file_system_path, excluded_folders,
base::BindRepeating(
&WebContents::OnDevToolsIndexingWorkCalculated,
weak_factory_.GetWeakPtr(), request_id, file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingWorked,
weak_factory_.GetWeakPtr(), request_id,
file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingDone,
weak_factory_.GetWeakPtr(), request_id,
file_system_path)));
}
void WebContents::DevToolsStopIndexing(int request_id) {
auto it = devtools_indexing_jobs_.find(request_id);
if (it == devtools_indexing_jobs_.end())
return;
it->second->Stop();
devtools_indexing_jobs_.erase(it);
}
void WebContents::DevToolsOpenInNewTab(const std::string& url) {
Emit("devtools-open-url", url);
}
void WebContents::DevToolsSearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsSearchCompleted(request_id, file_system_path,
std::vector<std::string>());
return;
}
devtools_file_system_indexer_->SearchInPath(
file_system_path, query,
base::BindRepeating(&WebContents::OnDevToolsSearchCompleted,
weak_factory_.GetWeakPtr(), request_id,
file_system_path));
}
void WebContents::DevToolsSetEyeDropperActive(bool active) {
auto* web_contents = GetWebContents();
if (!web_contents)
return;
if (active) {
eye_dropper_ = std::make_unique<DevToolsEyeDropper>(
web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper,
base::Unretained(this)));
} else {
eye_dropper_.reset();
}
}
void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) {
base::Value::Dict color;
color.Set("r", r);
color.Set("g", g);
color.Set("b", b);
color.Set("a", a);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color)));
}
#if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
ui::ImageModel WebContents::GetDevToolsWindowIcon() {
return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{};
}
#endif
#if BUILDFLAG(IS_LINUX)
void WebContents::GetDevToolsWindowWMClass(std::string* name,
std::string* class_name) {
*class_name = Browser::Get()->GetName();
*name = base::ToLowerASCII(*class_name);
}
#endif
void WebContents::OnDevToolsIndexingWorkCalculated(
int request_id,
const std::string& file_system_path,
int total_work) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id),
base::Value(file_system_path), base::Value(total_work));
}
void WebContents::OnDevToolsIndexingWorked(int request_id,
const std::string& file_system_path,
int worked) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingWorked", base::Value(request_id),
base::Value(file_system_path), base::Value(worked));
}
void WebContents::OnDevToolsIndexingDone(int request_id,
const std::string& file_system_path) {
devtools_indexing_jobs_.erase(request_id);
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone",
base::Value(request_id),
base::Value(file_system_path));
}
void WebContents::OnDevToolsSearchCompleted(
int request_id,
const std::string& file_system_path,
const std::vector<std::string>& file_paths) {
base::Value::List file_paths_value;
for (const auto& file_path : file_paths)
file_paths_value.Append(file_path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "searchCompleted", base::Value(request_id),
base::Value(file_system_path), base::Value(std::move(file_paths_value)));
}
void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) {
// Window is already in fullscreen mode, save the state.
if (enter_fullscreen && owner_window()->IsFullscreen()) {
native_fullscreen_ = true;
UpdateHtmlApiFullscreen(true);
return;
}
// Exit html fullscreen state but not window's fullscreen mode.
if (!enter_fullscreen && native_fullscreen_) {
UpdateHtmlApiFullscreen(false);
return;
}
// Set fullscreen on window if allowed.
auto* web_preferences = WebContentsPreferences::From(GetWebContents());
bool html_fullscreenable =
web_preferences
? !web_preferences->ShouldDisableHtmlFullscreenWindowResize()
: true;
if (html_fullscreenable)
owner_window_->SetFullScreen(enter_fullscreen);
UpdateHtmlApiFullscreen(enter_fullscreen);
native_fullscreen_ = false;
}
void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) {
if (fullscreen == is_html_fullscreen())
return;
html_fullscreen_ = fullscreen;
// Notify renderer of the html fullscreen change.
web_contents()
->GetRenderViewHost()
->GetWidget()
->SynchronizeVisualProperties();
// The embedder WebContents is separated from the frame tree of webview, so
// we must manually sync their fullscreen states.
if (embedder_)
embedder_->SetHtmlApiFullscreen(fullscreen);
if (fullscreen) {
Emit("enter-html-full-screen");
owner_window_->NotifyWindowEnterHtmlFullScreen();
} else {
Emit("leave-html-full-screen");
owner_window_->NotifyWindowLeaveHtmlFullScreen();
}
// Make sure all child webviews quit html fullscreen.
if (!fullscreen && !IsGuest()) {
auto* manager = WebViewManager::GetWebViewManager(web_contents());
manager->ForEachGuest(
web_contents(), base::BindRepeating([](content::WebContents* guest) {
WebContents* api_web_contents = WebContents::From(guest);
api_web_contents->SetHtmlApiFullscreen(false);
return false;
}));
}
}
// static
void WebContents::FillObjectTemplate(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin::InvokerOptions options;
options.holder_is_first_argument = true;
options.holder_type = GetClassName();
templ->Set(
gin::StringToSymbol(isolate, "isDestroyed"),
gin::CreateFunctionTemplate(
isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed),
options));
// We use gin_helper::ObjectTemplateBuilder instead of
// gin::ObjectTemplateBuilder here to handle the fact that WebContents is
// destroyable.
gin_helper::ObjectTemplateBuilder(isolate, templ)
.SetMethod("destroy", &WebContents::Destroy)
.SetMethod("close", &WebContents::Close)
.SetMethod("getBackgroundThrottling",
&WebContents::GetBackgroundThrottling)
.SetMethod("setBackgroundThrottling",
&WebContents::SetBackgroundThrottling)
.SetMethod("getProcessId", &WebContents::GetProcessID)
.SetMethod("getOSProcessId", &WebContents::GetOSProcessID)
.SetMethod("equal", &WebContents::Equal)
.SetMethod("_loadURL", &WebContents::LoadURL)
.SetMethod("reload", &WebContents::Reload)
.SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache)
.SetMethod("downloadURL", &WebContents::DownloadURL)
.SetMethod("getURL", &WebContents::GetURL)
.SetMethod("getTitle", &WebContents::GetTitle)
.SetMethod("isLoading", &WebContents::IsLoading)
.SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
.SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
.SetMethod("stop", &WebContents::Stop)
.SetMethod("canGoBack", &WebContents::CanGoBack)
.SetMethod("goBack", &WebContents::GoBack)
.SetMethod("canGoForward", &WebContents::CanGoForward)
.SetMethod("goForward", &WebContents::GoForward)
.SetMethod("canGoToOffset", &WebContents::CanGoToOffset)
.SetMethod("goToOffset", &WebContents::GoToOffset)
.SetMethod("canGoToIndex", &WebContents::CanGoToIndex)
.SetMethod("goToIndex", &WebContents::GoToIndex)
.SetMethod("getActiveIndex", &WebContents::GetActiveIndex)
.SetMethod("clearHistory", &WebContents::ClearHistory)
.SetMethod("length", &WebContents::GetHistoryLength)
.SetMethod("isCrashed", &WebContents::IsCrashed)
.SetMethod("forcefullyCrashRenderer",
&WebContents::ForcefullyCrashRenderer)
.SetMethod("setUserAgent", &WebContents::SetUserAgent)
.SetMethod("getUserAgent", &WebContents::GetUserAgent)
.SetMethod("savePage", &WebContents::SavePage)
.SetMethod("openDevTools", &WebContents::OpenDevTools)
.SetMethod("closeDevTools", &WebContents::CloseDevTools)
.SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
.SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
.SetMethod("getDevToolsTitle", &WebContents::GetDevToolsTitle)
.SetMethod("setDevToolsTitle", &WebContents::SetDevToolsTitle)
.SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation)
.SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation)
.SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
.SetMethod("inspectElement", &WebContents::InspectElement)
.SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts)
.SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
.SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
.SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible)
.SetMethod("undo", &WebContents::Undo)
.SetMethod("redo", &WebContents::Redo)
.SetMethod("cut", &WebContents::Cut)
.SetMethod("copy", &WebContents::Copy)
.SetMethod("centerSelection", &WebContents::CenterSelection)
.SetMethod("paste", &WebContents::Paste)
.SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
.SetMethod("delete", &WebContents::Delete)
.SetMethod("selectAll", &WebContents::SelectAll)
.SetMethod("unselect", &WebContents::Unselect)
.SetMethod("scrollToTop", &WebContents::ScrollToTopOfDocument)
.SetMethod("scrollToBottom", &WebContents::ScrollToBottomOfDocument)
.SetMethod("adjustSelection",
&WebContents::AdjustSelectionByCharacterOffset)
.SetMethod("replace", &WebContents::Replace)
.SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
.SetMethod("findInPage", &WebContents::FindInPage)
.SetMethod("stopFindInPage", &WebContents::StopFindInPage)
.SetMethod("focus", &WebContents::Focus)
.SetMethod("isFocused", &WebContents::IsFocused)
.SetMethod("sendInputEvent", &WebContents::SendInputEvent)
.SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription)
.SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
.SetMethod("startDrag", &WebContents::StartDrag)
.SetMethod("attachToIframe", &WebContents::AttachToIframe)
.SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame)
.SetMethod("isOffscreen", &WebContents::IsOffScreen)
.SetMethod("startPainting", &WebContents::StartPainting)
.SetMethod("stopPainting", &WebContents::StopPainting)
.SetMethod("isPainting", &WebContents::IsPainting)
.SetMethod("setFrameRate", &WebContents::SetFrameRate)
.SetMethod("getFrameRate", &WebContents::GetFrameRate)
.SetMethod("invalidate", &WebContents::Invalidate)
.SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
.SetMethod("getZoomLevel", &WebContents::GetZoomLevel)
.SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
.SetMethod("getZoomFactor", &WebContents::GetZoomFactor)
.SetMethod("getType", &WebContents::GetType)
.SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths)
.SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences)
.SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
.SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
.SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker)
.SetMethod("inspectSharedWorkerById",
&WebContents::InspectSharedWorkerById)
.SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers)
#if BUILDFLAG(ENABLE_PRINTING)
.SetMethod("_print", &WebContents::Print)
.SetMethod("_printToPDF", &WebContents::PrintToPDF)
#endif
.SetMethod("_setNextChildWebPreferences",
&WebContents::SetNextChildWebPreferences)
.SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
.SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
.SetMethod("showDefinitionForSelection",
&WebContents::ShowDefinitionForSelection)
.SetMethod("copyImageAt", &WebContents::CopyImageAt)
.SetMethod("capturePage", &WebContents::CapturePage)
.SetMethod("setEmbedder", &WebContents::SetEmbedder)
.SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents)
.SetMethod("getNativeView", &WebContents::GetNativeView)
.SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured)
.SetMethod("setWebRTCIPHandlingPolicy",
&WebContents::SetWebRTCIPHandlingPolicy)
.SetMethod("setWebRTCUDPPortRange", &WebContents::SetWebRTCUDPPortRange)
.SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID)
.SetMethod("getWebRTCIPHandlingPolicy",
&WebContents::GetWebRTCIPHandlingPolicy)
.SetMethod("getWebRTCUDPPortRange", &WebContents::GetWebRTCUDPPortRange)
.SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot)
.SetMethod("setImageAnimationPolicy",
&WebContents::SetImageAnimationPolicy)
.SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo)
.SetProperty("id", &WebContents::ID)
.SetProperty("session", &WebContents::Session)
.SetProperty("hostWebContents", &WebContents::HostWebContents)
.SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
.SetProperty("debugger", &WebContents::Debugger)
.SetProperty("mainFrame", &WebContents::MainFrame)
.SetProperty("opener", &WebContents::Opener)
.Build();
}
const char* WebContents::GetTypeName() {
return GetClassName();
}
ElectronBrowserContext* WebContents::GetBrowserContext() const {
return static_cast<ElectronBrowserContext*>(
web_contents()->GetBrowserContext());
}
// static
gin::Handle<WebContents> WebContents::New(
v8::Isolate* isolate,
const gin_helper::Dictionary& options) {
gin::Handle<WebContents> handle =
gin::CreateHandle(isolate, new WebContents(isolate, options));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
gin::Handle<WebContents> WebContents::CreateAndTake(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type) {
gin::Handle<WebContents> handle = gin::CreateHandle(
isolate, new WebContents(isolate, std::move(web_contents), type));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
WebContents* WebContents::From(content::WebContents* web_contents) {
if (!web_contents)
return nullptr;
auto* data = static_cast<UserDataLink*>(
web_contents->GetUserData(kElectronApiWebContentsKey));
return data ? data->web_contents.get() : nullptr;
}
// static
gin::Handle<WebContents> WebContents::FromOrCreate(
v8::Isolate* isolate,
content::WebContents* web_contents) {
WebContents* api_web_contents = From(web_contents);
if (!api_web_contents) {
api_web_contents = new WebContents(isolate, web_contents);
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, api_web_contents, "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
}
return gin::CreateHandle(isolate, api_web_contents);
}
// static
gin::Handle<WebContents> WebContents::CreateFromWebPreferences(
v8::Isolate* isolate,
const gin_helper::Dictionary& web_preferences) {
// Check if webPreferences has |webContents| option.
gin::Handle<WebContents> web_contents;
if (web_preferences.GetHidden("webContents", &web_contents) &&
!web_contents.IsEmpty()) {
// Set webPreferences from options if using an existing webContents.
// These preferences will be used when the webContent launches new
// render processes.
auto* existing_preferences =
WebContentsPreferences::From(web_contents->web_contents());
gin_helper::Dictionary web_preferences_dict;
if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(),
&web_preferences_dict)) {
existing_preferences->SetFromDictionary(web_preferences_dict);
absl::optional<SkColor> color =
existing_preferences->GetBackgroundColor();
web_contents->web_contents()->SetPageBaseBackgroundColor(color);
// Because web preferences don't recognize transparency,
// only set rwhv background color if a color exists
auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView();
if (rwhv && color.has_value())
SetBackgroundColor(rwhv, color.value());
}
} else {
// Create one if not.
web_contents = WebContents::New(isolate, web_preferences);
}
return web_contents;
}
// static
WebContents* WebContents::FromID(int32_t id) {
return GetAllWebContents().Lookup(id);
}
// static
std::list<WebContents*> WebContents::GetWebContentsList() {
std::list<WebContents*> list;
for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
!iter.IsAtEnd(); iter.Advance()) {
list.push_back(iter.GetCurrentValue());
}
return list;
}
// static
gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin};
} // namespace electron::api
namespace {
using electron::api::GetAllWebContents;
using electron::api::WebContents;
using electron::api::WebFrameMain;
gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) {
WebContents* contents = WebContents::FromID(id);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromFrame(v8::Isolate* isolate,
WebFrameMain* web_frame) {
content::RenderFrameHost* rfh = web_frame->render_frame_host();
content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh);
WebContents* contents = WebContents::From(source);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromDevToolsTargetID(
v8::Isolate* isolate,
std::string target_id) {
auto agent_host = content::DevToolsAgentHost::GetForId(target_id);
WebContents* contents =
agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr;
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8(
v8::Isolate* isolate) {
std::vector<gin::Handle<WebContents>> list;
for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
!iter.IsAtEnd(); iter.Advance()) {
list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue()));
}
return list;
}
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("WebContents", WebContents::GetConstructor(context));
dict.SetMethod("fromId", &WebContentsFromID);
dict.SetMethod("fromFrame", &WebContentsFromFrame);
dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID);
dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8);
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,342 |
[Bug]: Navigator.keyboard.lock() icw requestFullscreen does not change behavior to 'Press and Hold Escape'
|
### 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
27.0.2
### What operating system are you using?
Windows
### Operating System Version
Windows 10 Pro version 22H2
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
When an element is brought to fullscreen with:
[elem.requestFullscreen()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen)
and an event listener exists like:
```
document.addEventListener('fullscreenchange', async () => {
const nav: any = navigator;
const elem = document.getElementById('app');
if (elem) {
await nav.keyboard.lock(['Escape']);
return;
}
nav.keyboard.unlock();
});
```
I would expect that the behavior of the Esc key changes, where I would now need to press and hold Esc for a few seconds before fullscreen is actually exited. As described here: [https://developer.chrome.com/blog/better-full-screen-mode/](https://developer.chrome.com/blog/better-full-screen-mode/)
I imagine the same behavior change should hold for when [requestPointerLock()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestPointerLock) is used.
### Actual Behavior
When the Esc key is pressed after bringing an element to fullscreen, it ALWAYS exits fullscreen immediately, even when used in combination with [keyboard.lock() API](https://developer.mozilla.org/en-US/docs/Web/API/Keyboard/lock).
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/40342
|
https://github.com/electron/electron/pull/40365
|
4b1c31e4dbd00cd58e159cbc2ab41de3b1ce3a86
|
fcdd5cba71b82c13c4f64a3e529dea91ed72d23c
| 2023-10-26T09:51:51Z |
c++
| 2023-10-31T15:59:39Z |
shell/browser/api/electron_api_web_contents_mac.mm
|
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "content/public/browser/render_widget_host_view.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/ui/cocoa/event_dispatching_window.h"
#include "shell/browser/web_contents_preferences.h"
#include "ui/base/cocoa/command_dispatcher.h"
#include "ui/base/cocoa/nsmenu_additions.h"
#include "ui/base/cocoa/nsmenuitem_additions.h"
#include "ui/events/keycodes/keyboard_codes.h"
#import <Cocoa/Cocoa.h>
@interface NSWindow (EventDispatchingWindow)
- (void)redispatchKeyEvent:(NSEvent*)event;
@end
namespace electron::api {
bool WebContents::IsFocused() const {
auto* view = web_contents()->GetRenderWidgetHostView();
if (!view)
return false;
if (GetType() != Type::kBackgroundPage) {
auto window = [web_contents()->GetNativeView().GetNativeNSView() window];
// On Mac the render widget host view does not lose focus when the window
// loses focus so check if the top level window is the key window.
if (window && ![window isKeyWindow])
return false;
}
return view->HasFocus();
}
bool WebContents::PlatformHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (event.skip_if_unhandled ||
event.GetType() == content::NativeWebKeyboardEvent::Type::kChar)
return false;
// Escape exits tabbed fullscreen mode.
if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) {
ExitFullscreenModeForTab(source);
return true;
}
// Check if the webContents has preferences and to ignore shortcuts
auto* web_preferences = WebContentsPreferences::From(source);
if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts())
return false;
NSEvent* ns_event = event.os_event.Get();
// Send the event to the menu before sending it to the window
if (ns_event.type == NSEventTypeKeyDown) {
// If the keyboard event is a system shortcut, it's already sent to the
// NSMenu instance in
// content/app_shim_remote_cocoa/render_widget_host_view_cocoa.mm via
// keyEvent:(NSEvent*)theEvent wasKeyEquivalent:(BOOL)equiv. If we let the
// NSMenu handle it here as well, it'll be sent twice with unexpected side
// effects.
bool is_a_keyboard_shortcut_event =
[[NSApp mainMenu] cr_menuItemForKeyEquivalentEvent:ns_event] != nil;
bool is_a_system_shortcut_event =
is_a_keyboard_shortcut_event &&
(ui::cocoa::ModifierMaskForKeyEvent(ns_event) &
NSEventModifierFlagFunction) != 0;
if (is_a_system_shortcut_event)
return false;
if ([[NSApp mainMenu] performKeyEquivalent:ns_event])
return true;
}
// Let the window redispatch the OS event
if (ns_event.window &&
[ns_event.window isKindOfClass:[EventDispatchingWindow class]]) {
[ns_event.window redispatchKeyEvent:ns_event];
// FIXME(nornagon): this isn't the right return value; we should implement
// devtools windows as Widgets in order to take advantage of the
// preexisting redispatch code in bridged_native_widget.
return false;
} else if (ns_event.window &&
[ns_event.window
conformsToProtocol:@protocol(CommandDispatchingWindow)]) {
NSObject<CommandDispatchingWindow>* window =
static_cast<NSObject<CommandDispatchingWindow>*>(ns_event.window);
[[window commandDispatcher] redispatchKeyEvent:ns_event];
// FIXME(clavin): Not exactly sure what to return here, likely the same
// situation as the branch above. If a future refactor removes
// |EventDispatchingWindow| then only this branch will need to remain.
return false;
}
return false;
}
} // namespace electron::api
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,342 |
[Bug]: Navigator.keyboard.lock() icw requestFullscreen does not change behavior to 'Press and Hold Escape'
|
### 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
27.0.2
### What operating system are you using?
Windows
### Operating System Version
Windows 10 Pro version 22H2
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
When an element is brought to fullscreen with:
[elem.requestFullscreen()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen)
and an event listener exists like:
```
document.addEventListener('fullscreenchange', async () => {
const nav: any = navigator;
const elem = document.getElementById('app');
if (elem) {
await nav.keyboard.lock(['Escape']);
return;
}
nav.keyboard.unlock();
});
```
I would expect that the behavior of the Esc key changes, where I would now need to press and hold Esc for a few seconds before fullscreen is actually exited. As described here: [https://developer.chrome.com/blog/better-full-screen-mode/](https://developer.chrome.com/blog/better-full-screen-mode/)
I imagine the same behavior change should hold for when [requestPointerLock()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestPointerLock) is used.
### Actual Behavior
When the Esc key is pressed after bringing an element to fullscreen, it ALWAYS exits fullscreen immediately, even when used in combination with [keyboard.lock() API](https://developer.mozilla.org/en-US/docs/Web/API/Keyboard/lock).
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/40342
|
https://github.com/electron/electron/pull/40365
|
4b1c31e4dbd00cd58e159cbc2ab41de3b1ce3a86
|
fcdd5cba71b82c13c4f64a3e529dea91ed72d23c
| 2023-10-26T09:51:51Z |
c++
| 2023-10-31T15:59:39Z |
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';
import { AddressInfo } from 'node:net';
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 listen(server);
const bw = new BrowserWindow({ show: false });
try {
const reportGenerated = once(reporting, 'report');
await bw.loadURL(`https://localhost:${(server.address() as AddressInfo).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.replaceAll('\\', '/'),
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.replaceAll(/(\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();
});
for (const isSandboxEnabled of [true, false]) {
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.replaceAll('\\', '/')}/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__');
});
it('works when used in conjunction with the vm module', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
await w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const { contextObject } = await w.webContents.executeJavaScript(`(async () => {
const vm = require('node:vm');
const contextObject = { count: 1, type: 'gecko' };
window.open('');
vm.runInNewContext('count += 1; type = "chameleon";', contextObject);
return { contextObject };
})()`);
expect(contextObject).to.deep.equal({ count: 2, type: 'chameleon' });
});
// 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":"object","exports":"object","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('IdleDetection', () => {
afterEach(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setPermissionRequestHandler(null);
});
it('can grant a permission request', async () => {
session.defaultSession.setPermissionRequestHandler(
(_wc, permission, callback) => {
callback(permission === 'idle-detection');
}
);
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'button.html'));
const permission = await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const button = document.getElementById('button');
button.addEventListener("click", async () => {
const permission = await IdleDetector.requestPermission();
resolve(permission);
});
button.click();
});
`, true);
expect(permission).to.eq('granted');
});
it('can deny a permission request', async () => {
session.defaultSession.setPermissionRequestHandler(
(_wc, permission, callback) => {
callback(permission !== 'idle-detection');
}
);
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'button.html'));
const permission = await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const button = document.getElementById('button');
button.addEventListener("click", async () => {
const permission = await IdleDetector.requestPermission();
resolve(permission);
});
button.click();
});
`, true);
expect(permission).to.eq('denied');
});
it('can allow the IdleDetector to start', async () => {
session.defaultSession.setPermissionCheckHandler((wc, permission) => {
return permission === 'idle-detection';
});
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const result = await w.webContents.executeJavaScript(`
const detector = new IdleDetector({ threshold: 60000 });
detector.start().then(() => {
return 'success';
}).catch(e => e.message);
`, true);
expect(result).to.eq('success');
});
it('can prevent the IdleDetector from starting', async () => {
session.defaultSession.setPermissionCheckHandler((wc, permission) => {
return permission !== 'idle-detection';
});
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const result = await w.webContents.executeJavaScript(`
const detector = new IdleDetector({ threshold: 60000 });
detector.start().then(() => {
console.log('success')
}).catch(e => e.message);
`, true);
expect(result).to.eq('Idle detection permission denied');
});
});
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', () => {
for (const storageName of ['localStorage', 'sessionStorage']) {
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').replaceAll('\\', '/'),
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.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.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.once('navigation-entry-committed' as any, () => {
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.getActiveIndex()).to.equal(1);
});
});
});
describe('chrome:// pages', () => {
const urls = [
'chrome://accessibility',
'chrome://gpu',
'chrome://media-internals',
'chrome://tracing',
'chrome://webrtc-internals'
];
for (const url of urls) {
describe(url, () => {
it('loads the page successfully', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(url);
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
| 40,342 |
[Bug]: Navigator.keyboard.lock() icw requestFullscreen does not change behavior to 'Press and Hold Escape'
|
### 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
27.0.2
### What operating system are you using?
Windows
### Operating System Version
Windows 10 Pro version 22H2
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
When an element is brought to fullscreen with:
[elem.requestFullscreen()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen)
and an event listener exists like:
```
document.addEventListener('fullscreenchange', async () => {
const nav: any = navigator;
const elem = document.getElementById('app');
if (elem) {
await nav.keyboard.lock(['Escape']);
return;
}
nav.keyboard.unlock();
});
```
I would expect that the behavior of the Esc key changes, where I would now need to press and hold Esc for a few seconds before fullscreen is actually exited. As described here: [https://developer.chrome.com/blog/better-full-screen-mode/](https://developer.chrome.com/blog/better-full-screen-mode/)
I imagine the same behavior change should hold for when [requestPointerLock()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestPointerLock) is used.
### Actual Behavior
When the Esc key is pressed after bringing an element to fullscreen, it ALWAYS exits fullscreen immediately, even when used in combination with [keyboard.lock() API](https://developer.mozilla.org/en-US/docs/Web/API/Keyboard/lock).
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/40342
|
https://github.com/electron/electron/pull/40365
|
4b1c31e4dbd00cd58e159cbc2ab41de3b1ce3a86
|
fcdd5cba71b82c13c4f64a3e529dea91ed72d23c
| 2023-10-26T09:51:51Z |
c++
| 2023-10-31T15:59:39Z |
spec/fixtures/pages/modal.html
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,342 |
[Bug]: Navigator.keyboard.lock() icw requestFullscreen does not change behavior to 'Press and Hold Escape'
|
### 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
27.0.2
### What operating system are you using?
Windows
### Operating System Version
Windows 10 Pro version 22H2
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
When an element is brought to fullscreen with:
[elem.requestFullscreen()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen)
and an event listener exists like:
```
document.addEventListener('fullscreenchange', async () => {
const nav: any = navigator;
const elem = document.getElementById('app');
if (elem) {
await nav.keyboard.lock(['Escape']);
return;
}
nav.keyboard.unlock();
});
```
I would expect that the behavior of the Esc key changes, where I would now need to press and hold Esc for a few seconds before fullscreen is actually exited. As described here: [https://developer.chrome.com/blog/better-full-screen-mode/](https://developer.chrome.com/blog/better-full-screen-mode/)
I imagine the same behavior change should hold for when [requestPointerLock()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestPointerLock) is used.
### Actual Behavior
When the Esc key is pressed after bringing an element to fullscreen, it ALWAYS exits fullscreen immediately, even when used in combination with [keyboard.lock() API](https://developer.mozilla.org/en-US/docs/Web/API/Keyboard/lock).
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/40342
|
https://github.com/electron/electron/pull/40365
|
4b1c31e4dbd00cd58e159cbc2ab41de3b1ce3a86
|
fcdd5cba71b82c13c4f64a3e529dea91ed72d23c
| 2023-10-26T09:51:51Z |
c++
| 2023-10-31T15:59:39Z |
spec/webview-spec.ts
|
import * as path from 'node:path';
import * as url from 'node:url';
import { BrowserWindow, session, ipcMain, app, WebContents } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import { emittedUntil } from './lib/events-helpers';
import { ifit, ifdescribe, defer, itremote, useRemoteContext, listen } from './lib/spec-helpers';
import { expect } from 'chai';
import * as http from 'node:http';
import * as auth from 'basic-auth';
import { once } from 'node:events';
import { setTimeout } from 'node:timers/promises';
declare let WebView: any;
const features = process._linkedBinding('electron_common_features');
async function loadWebView (w: WebContents, attributes: Record<string, string>, opts?: {openDevTools?: boolean}): Promise<void> {
const { openDevTools } = {
openDevTools: false,
...opts
};
await w.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView()
webview.id = 'webview'
for (const [k, v] of Object.entries(${JSON.stringify(attributes)})) {
webview.setAttribute(k, v)
}
document.body.appendChild(webview)
webview.addEventListener('dom-ready', () => {
if (${openDevTools}) {
webview.openDevTools()
}
})
webview.addEventListener('did-finish-load', () => {
resolve()
})
})
`);
}
async function loadWebViewAndWaitForEvent (w: WebContents, attributes: Record<string, string>, eventName: string): Promise<any> {
return await w.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.id = 'webview'
for (const [k, v] of Object.entries(${JSON.stringify(attributes)})) {
webview.setAttribute(k, v)
}
webview.addEventListener(${JSON.stringify(eventName)}, (e) => resolve({...e}), {once: true})
document.body.appendChild(webview)
})`);
};
async function loadWebViewAndWaitForMessage (w: WebContents, attributes: Record<string, string>): Promise<string> {
const { message } = await loadWebViewAndWaitForEvent(w, attributes, 'console-message');
return message;
};
describe('<webview> tag', function () {
const fixtures = path.join(__dirname, 'fixtures');
const blankPageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'blank.html')).toString();
function hideChildWindows (e: any, wc: WebContents) {
wc.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
show: false
}
}));
}
before(() => {
app.on('web-contents-created', hideChildWindows);
});
after(() => {
app.off('web-contents-created', hideChildWindows);
});
describe('behavior', () => {
afterEach(closeAllWindows);
it('works without script tag in page', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html'));
await once(ipcMain, 'pong');
});
it('works with sandbox', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
sandbox: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html'));
await once(ipcMain, 'pong');
});
it('works with contextIsolation', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html'));
await once(ipcMain, 'pong');
});
it('works with contextIsolation + sandbox', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true,
sandbox: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html'));
await once(ipcMain, 'pong');
});
it('works with Trusted Types', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-trusted-types.html'));
await once(ipcMain, 'pong');
});
it('is disabled by default', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
preload: path.join(fixtures, 'module', 'preload-webview.js'),
nodeIntegration: true
}
});
const webview = once(ipcMain, 'webview');
w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html'));
const [, type] = await webview;
expect(type).to.equal('undefined', 'WebView still exists');
});
});
// FIXME(deepak1556): Ch69 follow up.
xdescribe('document.visibilityState/hidden', () => {
afterEach(() => {
ipcMain.removeAllListeners('pong');
});
afterEach(closeAllWindows);
it('updates when the window is shown after the ready-to-show event', async () => {
const w = new BrowserWindow({ show: false });
const readyToShowSignal = once(w, 'ready-to-show');
const pongSignal1 = once(ipcMain, 'pong');
w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html'));
await pongSignal1;
const pongSignal2 = once(ipcMain, 'pong');
await readyToShowSignal;
w.show();
const [, visibilityState, hidden] = await pongSignal2;
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false();
});
it('inherits the parent window visibility state and receives visibilitychange events', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html'));
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true();
// We have to start waiting for the event
// before we ask the webContents to resize.
const getResponse = once(ipcMain, 'pong');
w.webContents.emit('-window-visibility-change', 'visible');
return getResponse.then(([, visibilityState, hidden]) => {
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false();
});
});
});
describe('did-attach-webview event', () => {
afterEach(closeAllWindows);
it('is emitted when a webview has been attached', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: 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('did-attach event', () => {
afterEach(closeAllWindows);
it('is emitted when a webview has been attached', async () => {
const w = new BrowserWindow({
webPreferences: {
webviewTag: true
}
});
await w.loadURL('about:blank');
const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', 'about:blank')
webview.addEventListener('did-attach', (e) => {
resolve('ok')
})
document.body.appendChild(webview)
})`);
expect(message).to.equal('ok');
});
});
describe('did-change-theme-color event', () => {
afterEach(closeAllWindows);
it('emits when theme color changes', async () => {
const w = new BrowserWindow({
webPreferences: {
webviewTag: true
}
});
await w.loadURL('about:blank');
const src = url.format({
pathname: `${fixtures.replaceAll('\\', '/')}/pages/theme-color.html`,
protocol: 'file',
slashes: true
});
const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', '${src}')
webview.addEventListener('did-change-theme-color', (e) => {
resolve('ok')
})
document.body.appendChild(webview)
})`);
expect(message).to.equal('ok');
});
});
describe('devtools', () => {
afterEach(closeAllWindows);
// FIXME: This test is flaky on WOA, so skip it there.
ifit(process.platform !== 'win32' || process.arch !== 'arm64')('loads devtools extensions registered on the parent window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
w.webContents.session.removeExtension('foo');
const extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo');
await w.webContents.session.loadExtension(extensionPath, {
allowFileAccess: true
});
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'webview-devtools.html'));
loadWebView(w.webContents, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(__dirname, 'fixtures', 'blank.html')}`
}, { openDevTools: true });
let childWebContentsId = 0;
app.once('web-contents-created', (e, webContents) => {
childWebContentsId = webContents.id;
webContents.on('devtools-opened', function () {
const showPanelIntervalId = setInterval(function () {
if (!webContents.isDestroyed() && webContents.devToolsWebContents) {
webContents.devToolsWebContents.executeJavaScript('(' + function () {
const { EUI } = (window as any);
const instance = EUI.InspectorView.InspectorView.instance();
const tabs = instance.tabbedPane.tabs;
const lastPanelId: any = tabs[tabs.length - 1].id;
instance.showPanel(lastPanelId);
}.toString() + ')()');
} else {
clearInterval(showPanelIntervalId);
}
}, 100);
});
});
const [, { runtimeId, tabId }] = await once(ipcMain, 'answer');
expect(runtimeId).to.match(/^[a-z]{32}$/);
expect(tabId).to.equal(childWebContentsId);
await w.webContents.executeJavaScript('webview.closeDevTools()');
});
});
describe('zoom behavior', () => {
const zoomScheme = standardScheme;
const webviewSession = session.fromPartition('webview-temp');
afterEach(closeAllWindows);
before(() => {
const protocol = webviewSession.protocol;
protocol.registerStringProtocol(zoomScheme, (request, callback) => {
callback('hello');
});
});
after(() => {
const protocol = webviewSession.protocol;
protocol.unregisterProtocol(zoomScheme);
});
it('inherits the zoomFactor of the parent window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
});
const zoomEventPromise = once(ipcMain, 'webview-parent-zoom-level');
w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-factor.html'));
const [, zoomFactor, zoomLevel] = await zoomEventPromise;
expect(zoomFactor).to.equal(1.2);
expect(zoomLevel).to.equal(1);
});
it('maintains zoom level on navigation', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
});
const promise = new Promise<void>((resolve) => {
ipcMain.on('webview-zoom-level', (event, zoomLevel, zoomFactor, newHost, final) => {
if (!newHost) {
expect(zoomFactor).to.equal(1.44);
expect(zoomLevel).to.equal(2.0);
} else {
expect(zoomFactor).to.equal(1.2);
expect(zoomLevel).to.equal(1);
}
if (final) {
resolve();
}
});
});
w.loadFile(path.join(fixtures, 'pages', 'webview-custom-zoom-level.html'));
await promise;
});
it('maintains zoom level when navigating within same page', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
});
const promise = new Promise<void>((resolve) => {
ipcMain.on('webview-zoom-in-page', (event, zoomLevel, zoomFactor, final) => {
expect(zoomFactor).to.equal(1.44);
expect(zoomLevel).to.equal(2.0);
if (final) {
resolve();
}
});
});
w.loadFile(path.join(fixtures, 'pages', 'webview-in-page-navigate.html'));
await promise;
});
it('inherits zoom level for the origin when available', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-origin-zoom-level.html'));
const [, zoomLevel] = await once(ipcMain, 'webview-origin-zoom-level');
expect(zoomLevel).to.equal(2.0);
});
it('does not crash when navigating with zoom level inherited from parent', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
session: webviewSession,
contextIsolation: false
}
});
const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
const readyPromise = once(ipcMain, 'dom-ready');
w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-inherited.html'));
const [, webview] = await attachPromise;
await readyPromise;
expect(webview.getZoomFactor()).to.equal(1.2);
await w.loadURL(`${zoomScheme}://host1`);
});
it('does not crash when changing zoom level after webview is destroyed', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
session: webviewSession,
contextIsolation: false
}
});
const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
await w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-inherited.html'));
await attachPromise;
await w.webContents.executeJavaScript('view.remove()');
w.webContents.setZoomLevel(0.5);
});
});
describe('requestFullscreen from webview', () => {
afterEach(closeAllWindows);
async function loadWebViewWindow (): Promise<[BrowserWindow, WebContents]> {
const w = new BrowserWindow({
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
const loadPromise = once(w.webContents, 'did-finish-load');
const readyPromise = once(ipcMain, 'webview-ready');
w.loadFile(path.join(__dirname, 'fixtures', 'webview', 'fullscreen', 'main.html'));
const [, webview] = await attachPromise;
await Promise.all([readyPromise, loadPromise]);
return [w, webview];
};
afterEach(async () => {
// The leaving animation is un-observable but can interfere with future tests
// Specifically this is async on macOS but can be on other platforms too
await setTimeout(1000);
closeAllWindows();
});
ifit(process.platform !== 'darwin')('should make parent frame element fullscreen too (non-macOS)', async () => {
const [w, webview] = await loadWebViewWindow();
expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.false();
const parentFullscreen = once(ipcMain, 'fullscreenchange');
await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await parentFullscreen;
expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.true();
const close = once(w, 'closed');
w.close();
await close;
});
ifit(process.platform === 'darwin')('should make parent frame element fullscreen too (macOS)', async () => {
const [w, webview] = await loadWebViewWindow();
expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.false();
const parentFullscreen = once(ipcMain, 'fullscreenchange');
const enterHTMLFS = once(w.webContents, 'enter-html-full-screen');
const leaveHTMLFS = once(w.webContents, 'leave-html-full-screen');
await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.true();
await webview.executeJavaScript('document.exitFullscreen()');
await Promise.all([enterHTMLFS, leaveHTMLFS, parentFullscreen]);
const close = once(w, 'closed');
w.close();
await close;
});
// FIXME(zcbenz): Fullscreen events do not work on Linux.
ifit(process.platform !== 'linux')('exiting fullscreen should unfullscreen window', async () => {
const [w, webview] = await loadWebViewWindow();
const enterFullScreen = once(w, 'enter-full-screen');
await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
const leaveFullScreen = once(w, 'leave-full-screen');
await webview.executeJavaScript('document.exitFullscreen()', true);
await leaveFullScreen;
await setTimeout();
expect(w.isFullScreen()).to.be.false();
const close = once(w, 'closed');
w.close();
await close;
});
// Sending ESC via sendInputEvent only works on Windows.
ifit(process.platform === 'win32')('pressing ESC should unfullscreen window', async () => {
const [w, webview] = await loadWebViewWindow();
const enterFullScreen = once(w, 'enter-full-screen');
await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
const leaveFullScreen = once(w, 'leave-full-screen');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
await leaveFullScreen;
await setTimeout();
expect(w.isFullScreen()).to.be.false();
const close = once(w, 'closed');
w.close();
await close;
});
it('pressing ESC should emit the leave-html-full-screen event', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
const didAttachWebview = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'));
const [, webContents] = await didAttachWebview;
const enterFSWindow = once(w, 'enter-html-full-screen');
const enterFSWebview = once(webContents, 'enter-html-full-screen');
await webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFSWindow;
await enterFSWebview;
const leaveFSWindow = once(w, 'leave-html-full-screen');
const leaveFSWebview = once(webContents, 'leave-html-full-screen');
webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
await leaveFSWebview;
await leaveFSWindow;
const close = once(w, 'closed');
w.close();
await close;
});
it('should support user gesture', async () => {
const [w, webview] = await loadWebViewWindow();
const waitForEnterHtmlFullScreen = once(webview, 'enter-html-full-screen');
const jsScript = "document.querySelector('video').webkitRequestFullscreen()";
webview.executeJavaScript(jsScript, true);
await waitForEnterHtmlFullScreen;
const close = once(w, 'closed');
w.close();
await close;
});
});
describe('child windows', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
it('opens window of about:blank with cross-scripting enabled', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-blank.html')}`
});
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('Hello');
});
it('opens window of same domain with cross-scripting enabled', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-file.html')}`
});
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('Hello');
});
it('returns null from window.open when allowpopups is not set', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-no-allowpopups.html')}`
});
const [, { windowOpenReturnedNull }] = await once(ipcMain, 'answer');
expect(windowOpenReturnedNull).to.be.true();
});
it('blocks accessing cross-origin frames', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-cross-origin.html')}`
});
const [, content] = await once(ipcMain, 'answer');
const expectedContent =
/Failed to read a named property 'toString' from 'Location': Blocked a frame with origin "(.*?)" from accessing a cross-origin frame./;
expect(content).to.match(expectedContent);
});
it('emits a browser-window-created event', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/window-open.html`
});
await once(app, 'browser-window-created');
});
it('emits a web-contents-created event', async () => {
const webContentsCreated = emittedUntil(app, 'web-contents-created',
(event: Electron.Event, contents: Electron.WebContents) => contents.getType() === 'window');
loadWebView(w.webContents, {
allowpopups: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/window-open.html`
});
await webContentsCreated;
});
it('does not crash when creating window with noopener', async () => {
loadWebView(w.webContents, {
allowpopups: 'on',
src: `file://${path.join(fixtures, 'api', 'native-window-open-noopener.html')}`
});
await once(app, 'browser-window-created');
});
});
describe('webpreferences attribute', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true } });
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
it('can enable context isolation', async () => {
loadWebView(w.webContents, {
allowpopups: 'yes',
preload: `file://${fixtures}/api/isolated-preload.js`,
src: `file://${fixtures}/api/isolated.html`,
webpreferences: 'contextIsolation=yes'
});
const [, data] = await once(ipcMain, 'isolated-world');
expect(data).to.deep.equal({
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'
}
});
});
});
describe('permission request handlers', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
const partition = 'permissionTest';
function setUpRequestHandler (webContentsId: number, requestedPermission: string) {
return new Promise<void>((resolve, reject) => {
session.fromPartition(partition).setPermissionRequestHandler(function (webContents, permission, callback) {
if (webContents.id === webContentsId) {
// requestMIDIAccess with sysex requests both midi and midiSysex so
// grant the first midi one and then reject the midiSysex one
if (requestedPermission === 'midiSysex' && permission === 'midi') {
return callback(true);
}
try {
expect(permission).to.equal(requestedPermission);
} catch (e) {
return reject(e);
}
callback(false);
resolve();
}
});
});
}
afterEach(() => {
session.fromPartition(partition).setPermissionRequestHandler(null);
});
// This is disabled because CI machines don't have cameras or microphones,
// so Chrome responds with "NotFoundError" instead of
// "PermissionDeniedError". It should be re-enabled if we find a way to mock
// the presence of a microphone & camera.
xit('emits when using navigator.getUserMedia api', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/media.html`,
partition,
nodeintegration: 'on'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
setUpRequestHandler(webViewContents.id, 'media');
const [, errorName] = await errorFromRenderer;
expect(errorName).to.equal('PermissionDeniedError');
});
it('emits when using navigator.geolocation api', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/geolocation.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
setUpRequestHandler(webViewContents.id, 'geolocation');
const [, error] = await errorFromRenderer;
expect(error).to.equal('User denied Geolocation');
});
it('emits when using navigator.requestMIDIAccess without sysex api', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/midi.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
setUpRequestHandler(webViewContents.id, 'midi');
const [, error] = await errorFromRenderer;
expect(error).to.equal('SecurityError');
});
it('emits when using navigator.requestMIDIAccess with sysex api', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/midi-sysex.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
setUpRequestHandler(webViewContents.id, 'midiSysex');
const [, error] = await errorFromRenderer;
expect(error).to.equal('SecurityError');
});
it('emits when accessing external protocol', async () => {
loadWebView(w.webContents, {
src: 'magnet:test',
partition
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
await setUpRequestHandler(webViewContents.id, 'openExternal');
});
it('emits when using Notification.requestPermission', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/notification.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
await setUpRequestHandler(webViewContents.id, 'notifications');
const [, error] = await errorFromRenderer;
expect(error).to.equal('denied');
});
});
describe('DOM events', () => {
afterEach(closeAllWindows);
it('receives extra properties on DOM events when contextIsolation is enabled', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true
}
});
await w.loadURL('about:blank');
const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', 'data:text/html,<script>console.log("hi")</script>')
webview.addEventListener('console-message', (e) => {
resolve(e.message)
})
document.body.appendChild(webview)
})`);
expect(message).to.equal('hi');
});
it('emits focus event when contextIsolation is enabled', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true
}
});
await w.loadURL('about:blank');
await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', 'about:blank')
webview.addEventListener('dom-ready', () => {
webview.focus()
})
webview.addEventListener('focus', () => {
resolve();
})
document.body.appendChild(webview)
})`);
});
});
describe('attributes', () => {
let w: WebContents;
before(async () => {
const window = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
await window.loadURL(`file://${fixtures}/pages/blank.html`);
w = window.webContents;
});
afterEach(async () => {
await w.executeJavaScript(`{
for (const el of document.querySelectorAll('webview')) el.remove();
}`);
});
after(closeAllWindows);
describe('src attribute', () => {
it('specifies the page to load', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/a.html`
});
expect(message).to.equal('a');
});
it('navigates to new page when changed', async () => {
await loadWebView(w, {
src: `file://${fixtures}/pages/a.html`
});
const { message } = await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('console-message', e => resolve({message: e.message}))
webview.src = ${JSON.stringify(`file://${fixtures}/pages/b.html`)}
})`);
expect(message).to.equal('b');
});
it('resolves relative URLs', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
src: './e.html'
});
expect(message).to.equal('Window script is loaded before preload script');
});
it('ignores empty values', async () => {
loadWebView(w, {});
for (const emptyValue of ['""', 'null', 'undefined']) {
const src = await w.executeJavaScript(`webview.src = ${emptyValue}, webview.src`);
expect(src).to.equal('');
}
});
it('does not wait until loadURL is resolved', async () => {
await loadWebView(w, { src: 'about:blank' });
const delay = await w.executeJavaScript(`new Promise(resolve => {
const before = Date.now();
webview.src = 'file://${fixtures}/pages/blank.html';
const now = Date.now();
resolve(now - before);
})`);
// Setting src is essentially sending a sync IPC message, which should
// not exceed more than a few ms.
//
// This is for testing #18638.
expect(delay).to.be.below(100);
});
});
describe('nodeintegration attribute', () => {
it('inserts no node symbols when not set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/c.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'undefined',
module: 'undefined',
process: 'undefined',
global: 'undefined'
});
});
it('inserts node symbols when set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/d.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('loads node symbols after POST navigation when set', async function () {
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/post.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('disables node integration on child windows when it is disabled on the webview', async () => {
const src = url.format({
pathname: `${fixtures}/pages/webview-opener-no-node-integration.html`,
protocol: 'file',
query: {
p: `${fixtures}/pages/window-opener-node.html`
},
slashes: true
});
const message = await loadWebViewAndWaitForMessage(w, {
allowpopups: 'on',
webpreferences: 'contextIsolation=no',
src
});
expect(JSON.parse(message).isProcessGlobalUndefined).to.be.true();
});
ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native modules when navigation happens', async function () {
await loadWebView(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/native-module.html`
});
const message = await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('console-message', e => resolve(e.message))
webview.reload();
})`);
expect(message).to.equal('function');
});
});
describe('preload attribute', () => {
useRemoteContext({ webPreferences: { webviewTag: true } });
it('loads the script before other scripts in window', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload.js`,
src: `file://${fixtures}/pages/e.html`
});
expect(message).to.be.a('string');
expect(message).to.be.not.equal('Window script is loaded before preload script');
});
it('preload script can still use "process" and "Buffer" when nodeintegration is off', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload-node-off.js`,
src: `file://${fixtures}/api/blank.html`
});
const types = JSON.parse(message);
expect(types).to.include({
process: 'object',
Buffer: 'function'
});
});
it('runs in the correct scope when sandboxed', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload-context.js`,
src: `file://${fixtures}/api/blank.html`,
webpreferences: 'sandbox=yes'
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function', // arguments passed to it should be available
electron: 'undefined', // objects from the scope it is called from should not be available
window: 'object', // the window object should be available
localVar: 'undefined' // but local variables should not be exposed to the window
});
});
it('preload script can require modules that still use "process" and "Buffer" when nodeintegration is off', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload-node-off-wrapper.js`,
webpreferences: 'sandbox=no',
src: `file://${fixtures}/api/blank.html`
});
const types = JSON.parse(message);
expect(types).to.include({
process: 'object',
Buffer: 'function'
});
});
it('receives ipc message in preload script', async () => {
await loadWebView(w, {
preload: `${fixtures}/module/preload-ipc.js`,
src: `file://${fixtures}/pages/e.html`
});
const message = 'boom!';
const { channel, args } = await w.executeJavaScript(`new Promise(resolve => {
webview.send('ping', ${JSON.stringify(message)})
webview.addEventListener('ipc-message', ({channel, args}) => resolve({channel, args}))
})`);
expect(channel).to.equal('pong');
expect(args).to.deep.equal([message]);
});
itremote('<webview>.sendToFrame()', async (fixtures: string) => {
const w = new WebView();
w.setAttribute('nodeintegration', 'on');
w.setAttribute('webpreferences', 'contextIsolation=no');
w.setAttribute('preload', `file://${fixtures}/module/preload-ipc.js`);
w.setAttribute('src', `file://${fixtures}/pages/ipc-message.html`);
document.body.appendChild(w);
const { frameId } = await new Promise<any>(resolve => w.addEventListener('ipc-message', resolve, { once: true }));
const message = 'boom!';
w.sendToFrame(frameId, 'ping', message);
const { channel, args } = await new Promise<any>(resolve => w.addEventListener('ipc-message', resolve, { once: true }));
expect(channel).to.equal('pong');
expect(args).to.deep.equal([message]);
}, [fixtures]);
it('works without script tag in page', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload.js`,
webpreferences: 'sandbox=no',
src: `file://${fixtures}/pages/base-page.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object',
Buffer: 'function'
});
});
it('resolves relative URLs', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: '../module/preload.js',
webpreferences: 'sandbox=no',
src: `file://${fixtures}/pages/e.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object',
Buffer: 'function'
});
});
itremote('ignores empty values', async () => {
const webview = new WebView();
for (const emptyValue of ['', null, undefined]) {
webview.preload = emptyValue;
expect(webview.preload).to.equal('');
}
});
});
describe('httpreferrer attribute', () => {
it('sets the referrer url', async () => {
const referrer = 'http://github.com/';
const received = await new Promise<string | undefined>((resolve, reject) => {
const server = http.createServer((req, res) => {
try {
resolve(req.headers.referer);
} catch (e) {
reject(e);
} finally {
res.end();
server.close();
}
});
listen(server).then(({ url }) => {
loadWebView(w, {
httpreferrer: referrer,
src: url
});
});
});
expect(received).to.equal(referrer);
});
});
describe('useragent attribute', () => {
it('sets the user agent', async () => {
const referrer = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko';
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/useragent.html`,
useragent: referrer
});
expect(message).to.equal(referrer);
});
});
describe('disablewebsecurity attribute', () => {
it('does not disable web security when not set', async () => {
await loadWebView(w, { src: 'about:blank' });
const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`);
expect(result).to.equal('failed');
});
it('disables web security when set', async () => {
await loadWebView(w, { src: 'about:blank', disablewebsecurity: '' });
const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`);
expect(result).to.equal('ok');
});
it('does not break node integration', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
disablewebsecurity: '',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/d.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('does not break preload script', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
disablewebsecurity: '',
preload: `${fixtures}/module/preload.js`,
webpreferences: 'sandbox=no',
src: `file://${fixtures}/pages/e.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object',
Buffer: 'function'
});
});
});
describe('partition attribute', () => {
it('inserts no node symbols when not set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
partition: 'test1',
src: `file://${fixtures}/pages/c.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'undefined',
module: 'undefined',
process: 'undefined',
global: 'undefined'
});
});
it('inserts node symbols when set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'on',
partition: 'test2',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/d.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('isolates storage for different id', async () => {
await w.executeJavaScript('localStorage.setItem(\'test\', \'one\')');
const message = await loadWebViewAndWaitForMessage(w, {
partition: 'test3',
src: `file://${fixtures}/pages/partition/one.html`
});
const parsedMessage = JSON.parse(message);
expect(parsedMessage).to.include({
numberOfEntries: 0,
testValue: null
});
});
it('uses current session storage when no id is provided', async () => {
await w.executeJavaScript('localStorage.setItem(\'test\', \'two\')');
const testValue = 'two';
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/partition/one.html`
});
const parsedMessage = JSON.parse(message);
expect(parsedMessage).to.include({
testValue
});
});
});
describe('allowpopups attribute', () => {
const generateSpecs = (description: string, webpreferences = '') => {
describe(description, () => {
it('can not open new window when not set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
webpreferences,
src: `file://${fixtures}/pages/window-open-hide.html`
});
expect(message).to.equal('null');
});
it('can open new window when set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
webpreferences,
allowpopups: 'on',
src: `file://${fixtures}/pages/window-open-hide.html`
});
expect(message).to.equal('window');
});
});
};
generateSpecs('without sandbox');
generateSpecs('with sandbox', 'sandbox=yes');
});
describe('webpreferences attribute', () => {
it('can enable nodeintegration', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/d.html`,
webpreferences: 'nodeIntegration,contextIsolation=no'
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('can disable web security and enable nodeintegration', async () => {
await loadWebView(w, { src: 'about:blank', webpreferences: 'webSecurity=no, nodeIntegration=yes, contextIsolation=no' });
const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`);
expect(result).to.equal('ok');
const type = await w.executeJavaScript('webview.executeJavaScript("typeof require")');
expect(type).to.equal('function');
});
});
});
describe('events', () => {
useRemoteContext({ webPreferences: { webviewTag: true } });
let w: WebContents;
before(async () => {
const window = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
await window.loadURL(`file://${fixtures}/pages/blank.html`);
w = window.webContents;
});
afterEach(async () => {
await w.executeJavaScript(`{
for (const el of document.querySelectorAll('webview')) el.remove();
}`);
});
after(closeAllWindows);
describe('ipc-message event', () => {
it('emits when guest sends an ipc message to browser', async () => {
const { frameId, channel, args } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/ipc-message.html`,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
}, 'ipc-message');
expect(frameId).to.be.an('array').that.has.lengthOf(2);
expect(channel).to.equal('channel');
expect(args).to.deep.equal(['arg1', 'arg2']);
});
});
describe('page-title-updated event', () => {
it('emits when title is set', async () => {
const { title, explicitSet } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/a.html`
}, 'page-title-updated');
expect(title).to.equal('test');
expect(explicitSet).to.be.true();
});
});
describe('page-favicon-updated event', () => {
it('emits when favicon urls are received', async () => {
const { favicons } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/a.html`
}, 'page-favicon-updated');
expect(favicons).to.be.an('array').of.length(2);
if (process.platform === 'win32') {
expect(favicons[0]).to.match(/^file:\/\/\/[A-Z]:\/favicon.png$/i);
} else {
expect(favicons[0]).to.equal('file:///favicon.png');
}
});
});
describe('did-redirect-navigation event', () => {
it('is emitted on redirects', async () => {
const server = http.createServer((req, res) => {
if (req.url === '/302') {
res.setHeader('Location', '/200');
res.statusCode = 302;
res.end();
} else {
res.end();
}
});
const { url } = await listen(server);
defer(() => { server.close(); });
const event = await loadWebViewAndWaitForEvent(w, {
src: `${url}/302`
}, 'did-redirect-navigation');
expect(event.url).to.equal(`${url}/200`);
expect(event.isInPlace).to.be.false();
expect(event.isMainFrame).to.be.true();
expect(event.frameProcessId).to.be.a('number');
expect(event.frameRoutingId).to.be.a('number');
});
});
describe('will-navigate event', () => {
it('emits when a url that leads to outside of the page is loaded', async () => {
const { url } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/webview-will-navigate.html`
}, 'will-navigate');
expect(url).to.equal('http://host/');
});
});
describe('will-frame-navigate event', () => {
it('emits when a link that leads to outside of the page is loaded', async () => {
const { url, isMainFrame } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/webview-will-navigate.html`
}, 'will-frame-navigate');
expect(url).to.equal('http://host/');
expect(isMainFrame).to.be.true();
});
it('emits when a link within an iframe, which leads to outside of the page, is loaded', async () => {
await loadWebView(w, {
src: `file://${fixtures}/pages/webview-will-navigate-in-frame.html`,
nodeIntegration: ''
});
const { url, frameProcessId, frameRoutingId } = await w.executeJavaScript(`
new Promise((resolve, reject) => {
let hasFrameNavigatedOnce = false;
const webview = document.getElementById('webview');
webview.addEventListener('will-frame-navigate', ({url, isMainFrame, frameProcessId, frameRoutingId}) => {
if (isMainFrame) return;
if (hasFrameNavigatedOnce) resolve({
url,
isMainFrame,
frameProcessId,
frameRoutingId,
});
// First navigation is the initial iframe load within the <webview>
hasFrameNavigatedOnce = true;
});
webview.executeJavaScript('loadSubframe()');
});
`);
expect(url).to.equal('http://host/');
expect(frameProcessId).to.be.a('number');
expect(frameRoutingId).to.be.a('number');
});
});
describe('did-navigate event', () => {
it('emits when a url that leads to outside of the page is clicked', async () => {
const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-will-navigate.html')).toString();
const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate');
expect(event.url).to.equal(pageUrl);
});
});
describe('did-navigate-in-page event', () => {
it('emits when an anchor link is clicked', async () => {
const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-did-navigate-in-page.html')).toString();
const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate-in-page');
expect(event.url).to.equal(`${pageUrl}#test_content`);
});
it('emits when window.history.replaceState is called', async () => {
const { url } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/webview-did-navigate-in-page-with-history.html`
}, 'did-navigate-in-page');
expect(url).to.equal('http://host/');
});
it('emits when window.location.hash is changed', async () => {
const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-did-navigate-in-page-with-hash.html')).toString();
const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate-in-page');
expect(event.url).to.equal(`${pageUrl}#test`);
});
});
describe('close event', () => {
it('should fire when interior page calls window.close', async () => {
await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/close.html` }, 'close');
});
});
describe('devtools-opened event', () => {
it('should fire when webview.openDevTools() is called', async () => {
await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/base-page.html`
}, 'dom-ready');
await w.executeJavaScript(`new Promise((resolve) => {
webview.openDevTools()
webview.addEventListener('devtools-opened', () => resolve(), {once: true})
})`);
await w.executeJavaScript('webview.closeDevTools()');
});
});
describe('devtools-closed event', () => {
itremote('should fire when webview.closeDevTools() is called', async (fixtures: string) => {
const webview = new WebView();
webview.src = `file://${fixtures}/pages/base-page.html`;
document.body.appendChild(webview);
await new Promise(resolve => webview.addEventListener('dom-ready', resolve, { once: true }));
webview.openDevTools();
await new Promise(resolve => webview.addEventListener('devtools-opened', resolve, { once: true }));
webview.closeDevTools();
await new Promise(resolve => webview.addEventListener('devtools-closed', resolve, { once: true }));
}, [fixtures]);
});
describe('devtools-focused event', () => {
itremote('should fire when webview.openDevTools() is called', async (fixtures: string) => {
const webview = new WebView();
webview.src = `file://${fixtures}/pages/base-page.html`;
document.body.appendChild(webview);
const waitForDevToolsFocused = new Promise(resolve => webview.addEventListener('devtools-focused', resolve, { once: true }));
await new Promise(resolve => webview.addEventListener('dom-ready', resolve, { once: true }));
webview.openDevTools();
await waitForDevToolsFocused;
webview.closeDevTools();
}, [fixtures]);
});
describe('dom-ready event', () => {
it('emits when document is loaded', async () => {
const server = http.createServer(() => {});
const { port } = await listen(server);
await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/dom-ready.html?port=${port}`
}, 'dom-ready');
});
itremote('throws a custom error when an API method is called before the event is emitted', () => {
const expectedErrorMessage =
'The WebView must be attached to the DOM ' +
'and the dom-ready event emitted before this method can be called.';
const webview = new WebView();
expect(() => { webview.stop(); }).to.throw(expectedErrorMessage);
});
});
describe('context-menu event', () => {
it('emits when right-clicked in page', async () => {
await loadWebView(w, { src: 'about:blank' });
const { params, url } = await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('context-menu', (e) => resolve({...e, url: webview.getURL() }), {once: true})
// Simulate right-click to create context-menu event.
const opts = { x: 0, y: 0, button: 'right' };
webview.sendInputEvent({ ...opts, type: 'mouseDown' });
webview.sendInputEvent({ ...opts, type: 'mouseUp' });
})`);
expect(params.pageURL).to.equal(url);
expect(params.frame).to.be.undefined();
expect(params.x).to.be.a('number');
expect(params.y).to.be.a('number');
});
});
describe('found-in-page event', () => {
itremote('emits when a request is made', async (fixtures: string) => {
const webview = new WebView();
const didFinishLoad = new Promise(resolve => webview.addEventListener('did-finish-load', resolve, { once: true }));
webview.src = `file://${fixtures}/pages/content.html`;
document.body.appendChild(webview);
// TODO(deepak1556): With https://codereview.chromium.org/2836973002
// focus of the webContents is required when triggering the api.
// Remove this workaround after determining the cause for
// incorrect focus.
webview.focus();
await didFinishLoad;
const activeMatchOrdinal = [];
for (;;) {
const foundInPage = new Promise<any>(resolve => webview.addEventListener('found-in-page', resolve, { once: true }));
const requestId = webview.findInPage('virtual');
const event = await foundInPage;
expect(event.result.requestId).to.equal(requestId);
expect(event.result.matches).to.equal(3);
activeMatchOrdinal.push(event.result.activeMatchOrdinal);
if (event.result.activeMatchOrdinal === event.result.matches) {
break;
}
}
expect(activeMatchOrdinal).to.deep.equal([1, 2, 3]);
webview.stopFindInPage('clearSelection');
}, [fixtures]);
});
describe('will-attach-webview event', () => {
itremote('does not emit when src is not changed', async () => {
const webview = new WebView();
document.body.appendChild(webview);
await setTimeout();
const expectedErrorMessage = 'The WebView must be attached to the DOM and the dom-ready event emitted before this method can be called.';
expect(() => { webview.stop(); }).to.throw(expectedErrorMessage);
});
it('supports changing the web preferences', async () => {
w.once('will-attach-webview', (event, webPreferences, params) => {
params.src = `file://${path.join(fixtures, 'pages', 'c.html')}`;
webPreferences.nodeIntegration = false;
});
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'yes',
src: `file://${fixtures}/pages/a.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'undefined',
module: 'undefined',
process: 'undefined',
global: 'undefined'
});
});
it('handler modifying params.instanceId does not break <webview>', async () => {
w.once('will-attach-webview', (event, webPreferences, params) => {
params.instanceId = null as any;
});
await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/a.html`
});
});
it('supports preventing a webview from being created', async () => {
w.once('will-attach-webview', event => event.preventDefault());
await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/c.html`
}, 'destroyed');
});
it('supports removing the preload script', async () => {
w.once('will-attach-webview', (event, webPreferences, params) => {
params.src = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-stripped-preload.html')).toString();
delete webPreferences.preload;
});
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'yes',
preload: path.join(fixtures, 'module', 'preload-set-global.js'),
src: `file://${fixtures}/pages/a.html`
});
expect(message).to.equal('undefined');
});
});
describe('media-started-playing and media-paused events', () => {
it('emits when audio starts and stops playing', async function () {
if (!await w.executeJavaScript('document.createElement(\'audio\').canPlayType(\'audio/wav\')')) {
return this.skip();
}
await loadWebView(w, { src: blankPageUrl });
// With the new autoplay policy, audio elements must be unmuted
// see https://goo.gl/xX8pDD.
await w.executeJavaScript(`new Promise(resolve => {
webview.executeJavaScript(\`
const audio = document.createElement("audio")
audio.src = "../assets/tone.wav"
document.body.appendChild(audio);
audio.play()
\`, true)
webview.addEventListener('media-started-playing', () => resolve(), {once: true})
})`);
await w.executeJavaScript(`new Promise(resolve => {
webview.executeJavaScript(\`
document.querySelector("audio").pause()
\`, true)
webview.addEventListener('media-paused', () => resolve(), {once: true})
})`);
});
});
});
describe('methods', () => {
let w: WebContents;
before(async () => {
const window = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
await window.loadURL(`file://${fixtures}/pages/blank.html`);
w = window.webContents;
});
afterEach(async () => {
await w.executeJavaScript(`{
for (const el of document.querySelectorAll('webview')) el.remove();
}`);
});
after(closeAllWindows);
describe('<webview>.reload()', () => {
it('should emit beforeunload handler', async () => {
await loadWebView(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/beforeunload-false.html`
});
// Event handler has to be added before reload.
const channel = await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('ipc-message', e => resolve(e.channel))
webview.reload();
})`);
expect(channel).to.equal('onbeforeunload');
});
});
describe('<webview>.goForward()', () => {
useRemoteContext({ webPreferences: { webviewTag: true } });
itremote('should work after a replaced history entry', async (fixtures: string) => {
function waitForEvent (target: EventTarget, event: string) {
return new Promise<any>(resolve => target.addEventListener(event, resolve, { once: true }));
}
function waitForEvents (target: EventTarget, ...events: string[]) {
return Promise.all(events.map(event => waitForEvent(webview, event)));
}
const webview = new WebView();
webview.setAttribute('nodeintegration', 'on');
webview.setAttribute('webpreferences', 'contextIsolation=no');
webview.src = `file://${fixtures}/pages/history-replace.html`;
document.body.appendChild(webview);
{
const [e] = await waitForEvents(webview, 'ipc-message', 'did-stop-loading');
expect(e.channel).to.equal('history');
expect(e.args[0]).to.equal(1);
expect(webview.canGoBack()).to.be.false();
expect(webview.canGoForward()).to.be.false();
}
webview.src = `file://${fixtures}/pages/base-page.html`;
await new Promise<void>(resolve => webview.addEventListener('did-stop-loading', resolve, { once: true }));
expect(webview.canGoBack()).to.be.true();
expect(webview.canGoForward()).to.be.false();
webview.goBack();
{
const [e] = await waitForEvents(webview, 'ipc-message', 'did-stop-loading');
expect(e.channel).to.equal('history');
expect(e.args[0]).to.equal(2);
expect(webview.canGoBack()).to.be.false();
expect(webview.canGoForward()).to.be.true();
}
webview.goForward();
await new Promise<void>(resolve => webview.addEventListener('did-stop-loading', resolve, { once: true }));
expect(webview.canGoBack()).to.be.true();
expect(webview.canGoForward()).to.be.false();
}, [fixtures]);
});
describe('<webview>.clearHistory()', () => {
it('should clear the navigation history', async () => {
await loadWebView(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: blankPageUrl
});
// Navigation must be triggered by a user gesture to make canGoBack() return true
await w.executeJavaScript('webview.executeJavaScript(`history.pushState(null, "", "foo.html")`, true)');
expect(await w.executeJavaScript('webview.canGoBack()')).to.be.true();
await w.executeJavaScript('webview.clearHistory()');
expect(await w.executeJavaScript('webview.canGoBack()')).to.be.false();
});
});
describe('executeJavaScript', () => {
it('can return the result of the executed script', async () => {
await loadWebView(w, {
src: 'about:blank'
});
const jsScript = "'4'+2";
const expectedResult = '42';
const result = await w.executeJavaScript(`webview.executeJavaScript(${JSON.stringify(jsScript)})`);
expect(result).to.equal(expectedResult);
});
});
it('supports inserting CSS', async () => {
await loadWebView(w, { src: `file://${fixtures}/pages/base-page.html` });
await w.executeJavaScript('webview.insertCSS(\'body { background-repeat: round; }\')');
const result = await w.executeJavaScript('webview.executeJavaScript(\'window.getComputedStyle(document.body).getPropertyValue("background-repeat")\')');
expect(result).to.equal('round');
});
it('supports removing inserted CSS', async () => {
await loadWebView(w, { src: `file://${fixtures}/pages/base-page.html` });
const key = await w.executeJavaScript('webview.insertCSS(\'body { background-repeat: round; }\')');
await w.executeJavaScript(`webview.removeInsertedCSS(${JSON.stringify(key)})`);
const result = await w.executeJavaScript('webview.executeJavaScript(\'window.getComputedStyle(document.body).getPropertyValue("background-repeat")\')');
expect(result).to.equal('repeat');
});
describe('sendInputEvent', () => {
it('can send keyboard event', async () => {
await loadWebViewAndWaitForEvent(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/onkeyup.html`
}, 'dom-ready');
const waitForIpcMessage = w.executeJavaScript('new Promise(resolve => webview.addEventListener("ipc-message", e => resolve({...e})), {once: true})');
w.executeJavaScript(`webview.sendInputEvent({
type: 'keyup',
keyCode: 'c',
modifiers: ['shift']
})`);
const { channel, args } = await waitForIpcMessage;
expect(channel).to.equal('keyup');
expect(args).to.deep.equal(['C', 'KeyC', 67, true, false]);
});
it('can send mouse event', async () => {
await loadWebViewAndWaitForEvent(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/onmouseup.html`
}, 'dom-ready');
const waitForIpcMessage = w.executeJavaScript('new Promise(resolve => webview.addEventListener("ipc-message", e => resolve({...e})), {once: true})');
w.executeJavaScript(`webview.sendInputEvent({
type: 'mouseup',
modifiers: ['ctrl'],
x: 10,
y: 20
})`);
const { channel, args } = await waitForIpcMessage;
expect(channel).to.equal('mouseup');
expect(args).to.deep.equal([10, 20, false, true]);
});
});
describe('<webview>.getWebContentsId', () => {
it('can return the WebContents ID', async () => {
await loadWebView(w, { src: 'about:blank' });
expect(await w.executeJavaScript('webview.getWebContentsId()')).to.be.a('number');
});
});
ifdescribe(features.isPrintingEnabled())('<webview>.printToPDF()', () => {
it('rejects on incorrectly typed parameters', async () => {
const badTypes = {
landscape: [],
displayHeaderFooter: '123',
printBackground: 2,
scale: 'not-a-number',
pageSize: 'IAmAPageSize',
margins: 'terrible',
pageRanges: { oops: 'im-not-the-right-key' },
headerTemplate: [1, 2, 3],
footerTemplate: [4, 5, 6],
preferCSSPageSize: 'no'
};
// These will hard crash in Chromium unless we type-check
for (const [key, value] of Object.entries(badTypes)) {
const param = { [key]: value };
const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
await loadWebView(w, { src });
await expect(w.executeJavaScript(`webview.printToPDF(${JSON.stringify(param)})`)).to.eventually.be.rejected();
}
});
it('can print to PDF', async () => {
const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
await loadWebView(w, { src });
const data = await w.executeJavaScript('webview.printToPDF({})');
expect(data).to.be.an.instanceof(Uint8Array).that.is.not.empty();
});
});
describe('DOM events', () => {
for (const [description, sandbox] of [
['without sandbox', false] as const,
['with sandbox', true] as const
]) {
describe(description, () => {
it('emits focus event', async () => {
await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/a.html`,
webpreferences: `sandbox=${sandbox ? 'yes' : 'no'}`
}, 'dom-ready');
// If this test fails, check if webview.focus() still works.
await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('focus', () => resolve(), {once: true});
webview.focus();
})`);
});
});
}
});
// TODO(miniak): figure out why this is failing on windows
ifdescribe(process.platform !== 'win32')('<webview>.capturePage()', () => {
it('returns a Promise with a NativeImage', async function () {
this.retries(5);
const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
await loadWebViewAndWaitForEvent(w, { src }, 'did-stop-loading');
const image = await w.executeJavaScript('webview.capturePage()');
expect(image.isEmpty()).to.be.false();
// Check the 25th byte in the PNG.
// Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
const imgBuffer = image.toPNG();
expect(imgBuffer[25]).to.equal(6);
});
it('returns a Promise with a NativeImage in the renderer', async function () {
this.retries(5);
const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
await loadWebViewAndWaitForEvent(w, { src }, 'did-stop-loading');
const byte = await w.executeJavaScript(`new Promise(resolve => {
webview.capturePage().then(image => {
resolve(image.toPNG()[25])
});
})`);
expect(byte).to.equal(6);
});
});
// FIXME(zcbenz): Disabled because of moving to OOPIF webview.
xdescribe('setDevToolsWebContents() API', () => {
/*
it('sets webContents of webview as devtools', async () => {
const webview2 = new WebView();
loadWebView(webview2);
// Setup an event handler for further usage.
const waitForDomReady = waitForEvent(webview2, 'dom-ready');
loadWebView(webview, { src: 'about:blank' });
await waitForEvent(webview, 'dom-ready');
webview.getWebContents().setDevToolsWebContents(webview2.getWebContents());
webview.getWebContents().openDevTools();
await waitForDomReady;
// Its WebContents should be a DevTools.
const devtools = webview2.getWebContents();
expect(devtools.getURL().startsWith('devtools://devtools')).to.be.true();
const name = await devtools.executeJavaScript('InspectorFrontendHost.constructor.name');
document.body.removeChild(webview2);
expect(name).to.be.equal('InspectorFrontendHostImpl');
});
*/
});
});
describe('basic auth', () => {
let w: WebContents;
before(async () => {
const window = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
await window.loadURL(`file://${fixtures}/pages/blank.html`);
w = window.webContents;
});
afterEach(async () => {
await w.executeJavaScript(`{
for (const el of document.querySelectorAll('webview')) el.remove();
}`);
});
after(closeAllWindows);
it('should authenticate with correct credentials', async () => {
const message = 'Authenticated';
const server = http.createServer((req, res) => {
const credentials = auth(req)!;
if (credentials.name === 'test' && credentials.pass === 'test') {
res.end(message);
} else {
res.end('failed');
}
});
defer(() => {
server.close();
});
const { port } = await listen(server);
const e = await loadWebViewAndWaitForEvent(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/basic-auth.html?port=${port}`
}, 'ipc-message');
expect(e.channel).to.equal(message);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,342 |
[Bug]: Navigator.keyboard.lock() icw requestFullscreen does not change behavior to 'Press and Hold Escape'
|
### 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
27.0.2
### What operating system are you using?
Windows
### Operating System Version
Windows 10 Pro version 22H2
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
When an element is brought to fullscreen with:
[elem.requestFullscreen()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen)
and an event listener exists like:
```
document.addEventListener('fullscreenchange', async () => {
const nav: any = navigator;
const elem = document.getElementById('app');
if (elem) {
await nav.keyboard.lock(['Escape']);
return;
}
nav.keyboard.unlock();
});
```
I would expect that the behavior of the Esc key changes, where I would now need to press and hold Esc for a few seconds before fullscreen is actually exited. As described here: [https://developer.chrome.com/blog/better-full-screen-mode/](https://developer.chrome.com/blog/better-full-screen-mode/)
I imagine the same behavior change should hold for when [requestPointerLock()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestPointerLock) is used.
### Actual Behavior
When the Esc key is pressed after bringing an element to fullscreen, it ALWAYS exits fullscreen immediately, even when used in combination with [keyboard.lock() API](https://developer.mozilla.org/en-US/docs/Web/API/Keyboard/lock).
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/40342
|
https://github.com/electron/electron/pull/40365
|
4b1c31e4dbd00cd58e159cbc2ab41de3b1ce3a86
|
fcdd5cba71b82c13c4f64a3e529dea91ed72d23c
| 2023-10-26T09:51:51Z |
c++
| 2023-10-31T15:59:39Z |
shell/browser/api/electron_api_web_contents.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_web_contents.h"
#include <limits>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/containers/contains.h"
#include "base/containers/fixed_flat_map.h"
#include "base/containers/id_map.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/current_thread.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
#include "chrome/browser/ui/views/eye_dropper/eye_dropper.h"
#include "chrome/common/pref_names.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/security_state/content/content_utils.h"
#include "components/security_state/core/security_state.h"
#include "content/browser/renderer_host/frame_tree_node.h" // nogncheck
#include "content/browser/renderer_host/navigation_controller_impl.h" // nogncheck
#include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/desktop_media_id.h"
#include "content/public/browser/desktop_streams_registry.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/service_worker_context.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/input/native_web_keyboard_event.h"
#include "content/public/common/referrer_type_converters.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/webplugininfo.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "gin/arguments.h"
#include "gin/data_object_builder.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "media/base/mime_util.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "ppapi/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "printing/print_job_constants.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/browser/api/electron_api_browser_window.h"
#include "shell/browser/api/electron_api_debugger.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/api/electron_api_web_frame_main.h"
#include "shell/browser/api/message_port.h"
#include "shell/browser/browser.h"
#include "shell/browser/child_web_contents_tracker.h"
#include "shell/browser/electron_autofill_driver_factory.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/electron_javascript_dialog_manager.h"
#include "shell/browser/electron_navigation_throttle.h"
#include "shell/browser/file_select_helper.h"
#include "shell/browser/native_window.h"
#include "shell/browser/osr/osr_render_widget_host_view.h"
#include "shell/browser/osr/osr_web_contents_view.h"
#include "shell/browser/session_preferences.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/file_dialog.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/browser/web_contents_zoom_controller.h"
#include "shell/browser/web_view_guest_delegate.h"
#include "shell/browser/web_view_manager.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/color_util.h"
#include "shell/common/electron_constants.h"
#include "shell/common/gin_converters/base_converter.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/content_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/frame_converter.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/optional_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/language_util.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "shell/common/thread_restrictions.h"
#include "shell/common/v8_value_serializer.h"
#include "storage/browser/file_system/isolated_context.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/mojom/frame/find_in_page.mojom.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h"
#include "third_party/blink/public/mojom/renderer_preferences.mojom.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
#if BUILDFLAG(IS_WIN)
#include "shell/browser/native_window_views.h"
#endif
#if !BUILDFLAG(IS_MAC)
#include "ui/aura/window.h"
#else
#include "ui/base/cocoa/defaults_utils.h"
#endif
#if BUILDFLAG(IS_LINUX)
#include "ui/linux/linux_ui.h"
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
#include "ui/gfx/font_render_params.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/script_executor.h"
#include "extensions/browser/view_type_utils.h"
#include "extensions/common/mojom/view_type.mojom.h"
#include "shell/browser/extensions/electron_extension_web_contents_observer.h"
#endif
#if BUILDFLAG(ENABLE_PRINTING)
#include "chrome/browser/printing/print_view_manager_base.h"
#include "components/printing/browser/print_manager_utils.h"
#include "components/printing/browser/print_to_pdf/pdf_print_result.h"
#include "components/printing/browser/print_to_pdf/pdf_print_utils.h"
#include "printing/backend/print_backend.h" // nogncheck
#include "printing/mojom/print.mojom.h" // nogncheck
#include "printing/page_range.h"
#include "shell/browser/printing/print_view_manager_electron.h"
#if BUILDFLAG(IS_WIN)
#include "printing/backend/win_helper.h"
#endif
#endif // BUILDFLAG(ENABLE_PRINTING)
#if BUILDFLAG(ENABLE_PDF_VIEWER)
#include "components/pdf/browser/pdf_document_helper.h" // nogncheck
#include "shell/browser/electron_pdf_document_helper_client.h"
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/public/browser/plugin_service.h"
#endif
#if !IS_MAS_BUILD()
#include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck
#endif
namespace gin {
#if BUILDFLAG(ENABLE_PRINTING)
template <>
struct Converter<printing::mojom::MarginType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::MarginType* out) {
using Val = printing::mojom::MarginType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"custom", Val::kCustomMargins},
{"default", Val::kDefaultMargins},
{"none", Val::kNoMargins},
{"printableArea", Val::kPrintableAreaMargins},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<printing::mojom::DuplexMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::DuplexMode* out) {
using Val = printing::mojom::DuplexMode;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"longEdge", Val::kLongEdge},
{"shortEdge", Val::kShortEdge},
{"simplex", Val::kSimplex},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
#endif
template <>
struct Converter<WindowOpenDisposition> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
WindowOpenDisposition val) {
std::string disposition = "other";
switch (val) {
case WindowOpenDisposition::CURRENT_TAB:
disposition = "default";
break;
case WindowOpenDisposition::NEW_FOREGROUND_TAB:
disposition = "foreground-tab";
break;
case WindowOpenDisposition::NEW_BACKGROUND_TAB:
disposition = "background-tab";
break;
case WindowOpenDisposition::NEW_POPUP:
case WindowOpenDisposition::NEW_WINDOW:
disposition = "new-window";
break;
case WindowOpenDisposition::SAVE_TO_DISK:
disposition = "save-to-disk";
break;
default:
break;
}
return gin::ConvertToV8(isolate, disposition);
}
};
template <>
struct Converter<content::SavePageType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
content::SavePageType* out) {
using Val = content::SavePageType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"htmlcomplete", Val::SAVE_PAGE_TYPE_AS_COMPLETE_HTML},
{"htmlonly", Val::SAVE_PAGE_TYPE_AS_ONLY_HTML},
{"mhtml", Val::SAVE_PAGE_TYPE_AS_MHTML},
});
return FromV8WithLowerLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<electron::api::WebContents::Type> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
electron::api::WebContents::Type val) {
using Type = electron::api::WebContents::Type;
std::string type;
switch (val) {
case Type::kBackgroundPage:
type = "backgroundPage";
break;
case Type::kBrowserWindow:
type = "window";
break;
case Type::kBrowserView:
type = "browserView";
break;
case Type::kRemote:
type = "remote";
break;
case Type::kWebView:
type = "webview";
break;
case Type::kOffScreen:
type = "offscreen";
break;
default:
break;
}
return gin::ConvertToV8(isolate, type);
}
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::api::WebContents::Type* out) {
using Val = electron::api::WebContents::Type;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"backgroundPage", Val::kBackgroundPage},
{"browserView", Val::kBrowserView},
{"offscreen", Val::kOffScreen},
{"webview", Val::kWebView},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<scoped_refptr<content::DevToolsAgentHost>> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const scoped_refptr<content::DevToolsAgentHost>& val) {
gin_helper::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("id", val->GetId());
dict.Set("url", val->GetURL().spec());
return dict.GetHandle();
}
};
} // namespace gin
namespace electron::api {
namespace {
constexpr base::StringPiece CursorTypeToString(
ui::mojom::CursorType cursor_type) {
switch (cursor_type) {
case ui::mojom::CursorType::kPointer:
return "pointer";
case ui::mojom::CursorType::kCross:
return "crosshair";
case ui::mojom::CursorType::kHand:
return "hand";
case ui::mojom::CursorType::kIBeam:
return "text";
case ui::mojom::CursorType::kWait:
return "wait";
case ui::mojom::CursorType::kHelp:
return "help";
case ui::mojom::CursorType::kEastResize:
return "e-resize";
case ui::mojom::CursorType::kNorthResize:
return "n-resize";
case ui::mojom::CursorType::kNorthEastResize:
return "ne-resize";
case ui::mojom::CursorType::kNorthWestResize:
return "nw-resize";
case ui::mojom::CursorType::kSouthResize:
return "s-resize";
case ui::mojom::CursorType::kSouthEastResize:
return "se-resize";
case ui::mojom::CursorType::kSouthWestResize:
return "sw-resize";
case ui::mojom::CursorType::kWestResize:
return "w-resize";
case ui::mojom::CursorType::kNorthSouthResize:
return "ns-resize";
case ui::mojom::CursorType::kEastWestResize:
return "ew-resize";
case ui::mojom::CursorType::kNorthEastSouthWestResize:
return "nesw-resize";
case ui::mojom::CursorType::kNorthWestSouthEastResize:
return "nwse-resize";
case ui::mojom::CursorType::kColumnResize:
return "col-resize";
case ui::mojom::CursorType::kRowResize:
return "row-resize";
case ui::mojom::CursorType::kMiddlePanning:
return "m-panning";
case ui::mojom::CursorType::kMiddlePanningVertical:
return "m-panning-vertical";
case ui::mojom::CursorType::kMiddlePanningHorizontal:
return "m-panning-horizontal";
case ui::mojom::CursorType::kEastPanning:
return "e-panning";
case ui::mojom::CursorType::kNorthPanning:
return "n-panning";
case ui::mojom::CursorType::kNorthEastPanning:
return "ne-panning";
case ui::mojom::CursorType::kNorthWestPanning:
return "nw-panning";
case ui::mojom::CursorType::kSouthPanning:
return "s-panning";
case ui::mojom::CursorType::kSouthEastPanning:
return "se-panning";
case ui::mojom::CursorType::kSouthWestPanning:
return "sw-panning";
case ui::mojom::CursorType::kWestPanning:
return "w-panning";
case ui::mojom::CursorType::kMove:
return "move";
case ui::mojom::CursorType::kVerticalText:
return "vertical-text";
case ui::mojom::CursorType::kCell:
return "cell";
case ui::mojom::CursorType::kContextMenu:
return "context-menu";
case ui::mojom::CursorType::kAlias:
return "alias";
case ui::mojom::CursorType::kProgress:
return "progress";
case ui::mojom::CursorType::kNoDrop:
return "nodrop";
case ui::mojom::CursorType::kCopy:
return "copy";
case ui::mojom::CursorType::kNone:
return "none";
case ui::mojom::CursorType::kNotAllowed:
return "not-allowed";
case ui::mojom::CursorType::kZoomIn:
return "zoom-in";
case ui::mojom::CursorType::kZoomOut:
return "zoom-out";
case ui::mojom::CursorType::kGrab:
return "grab";
case ui::mojom::CursorType::kGrabbing:
return "grabbing";
case ui::mojom::CursorType::kCustom:
return "custom";
case ui::mojom::CursorType::kNull:
return "null";
case ui::mojom::CursorType::kDndNone:
return "drag-drop-none";
case ui::mojom::CursorType::kDndMove:
return "drag-drop-move";
case ui::mojom::CursorType::kDndCopy:
return "drag-drop-copy";
case ui::mojom::CursorType::kDndLink:
return "drag-drop-link";
case ui::mojom::CursorType::kNorthSouthNoResize:
return "ns-no-resize";
case ui::mojom::CursorType::kEastWestNoResize:
return "ew-no-resize";
case ui::mojom::CursorType::kNorthEastSouthWestNoResize:
return "nesw-no-resize";
case ui::mojom::CursorType::kNorthWestSouthEastNoResize:
return "nwse-no-resize";
default:
return "default";
}
}
base::IDMap<WebContents*>& GetAllWebContents() {
static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents;
return *s_all_web_contents;
}
void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise,
base::ScopedClosureRunner capture_handle,
const SkBitmap& bitmap) {
auto ui_task_runner = content::GetUIThreadTaskRunner({});
if (!ui_task_runner->RunsTasksInCurrentSequence()) {
ui_task_runner->PostTask(
FROM_HERE, base::BindOnce(&OnCapturePageDone, std::move(promise),
std::move(capture_handle), bitmap));
return;
}
// Hack to enable transparency in captured image
promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap));
capture_handle.RunAndReset();
}
absl::optional<base::TimeDelta> GetCursorBlinkInterval() {
#if BUILDFLAG(IS_MAC)
absl::optional<base::TimeDelta> system_value(
ui::TextInsertionCaretBlinkPeriodFromDefaults());
if (system_value)
return *system_value;
#elif BUILDFLAG(IS_LINUX)
if (auto* linux_ui = ui::LinuxUi::instance())
return linux_ui->GetCursorBlinkInterval();
#elif BUILDFLAG(IS_WIN)
const auto system_msec = ::GetCaretBlinkTime();
if (system_msec != 0) {
return (system_msec == INFINITE) ? base::TimeDelta()
: base::Milliseconds(system_msec);
}
#endif
return absl::nullopt;
}
#if BUILDFLAG(ENABLE_PRINTING)
// This will return false if no printer with the provided device_name can be
// found on the network. We need to check this because Chromium does not do
// sanity checking of device_name validity and so will crash on invalid names.
bool IsDeviceNameValid(const std::u16string& device_name) {
#if BUILDFLAG(IS_MAC)
base::apple::ScopedCFTypeRef<CFStringRef> new_printer_id(
base::SysUTF16ToCFStringRef(device_name));
PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get());
bool printer_exists = new_printer != nullptr;
PMRelease(new_printer);
return printer_exists;
#else
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name));
#endif
}
// This function returns a validated device name.
// If the user passed one to webContents.print(), we check that it's valid and
// return it or fail if the network doesn't recognize it. If the user didn't
// pass a device name, we first try to return the system default printer. If one
// isn't set, then pull all the printers and use the first one or fail if none
// exist.
std::pair<std::string, std::u16string> GetDeviceNameToUse(
const std::u16string& device_name) {
#if BUILDFLAG(IS_WIN)
// Blocking is needed here because Windows printer drivers are oftentimes
// not thread-safe and have to be accessed on the UI thread.
ScopedAllowBlockingForElectron allow_blocking;
#endif
if (!device_name.empty()) {
if (!IsDeviceNameValid(device_name))
return std::make_pair("Invalid deviceName provided", std::u16string());
return std::make_pair(std::string(), device_name);
}
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
std::string printer_name;
printing::mojom::ResultCode code =
print_backend->GetDefaultPrinterName(printer_name);
// We don't want to return if this fails since some devices won't have a
// default printer.
if (code != printing::mojom::ResultCode::kSuccess)
LOG(ERROR) << "Failed to get default printer name";
if (printer_name.empty()) {
printing::PrinterList printers;
if (print_backend->EnumeratePrinters(printers) !=
printing::mojom::ResultCode::kSuccess)
return std::make_pair("Failed to enumerate printers", std::u16string());
if (printers.empty())
return std::make_pair("No printers available on the network",
std::u16string());
printer_name = printers.front().printer_name;
}
return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name));
}
// Copied from
// chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54
scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() {
// USER_VISIBLE because the result is displayed in the print preview dialog.
#if !BUILDFLAG(IS_WIN)
static constexpr base::TaskTraits kTraits = {
base::MayBlock(), base::TaskPriority::USER_VISIBLE};
#endif
#if defined(USE_CUPS)
// CUPS is thread safe.
return base::ThreadPool::CreateTaskRunner(kTraits);
#elif BUILDFLAG(IS_WIN)
// Windows drivers are likely not thread-safe and need to be accessed on the
// UI thread.
return content::GetUIThreadTaskRunner({base::TaskPriority::USER_VISIBLE});
#else
// Be conservative on unsupported platforms.
return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits);
#endif
}
#endif
struct UserDataLink : public base::SupportsUserData::Data {
explicit UserDataLink(base::WeakPtr<WebContents> contents)
: web_contents(contents) {}
base::WeakPtr<WebContents> web_contents;
};
const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey;
const char kRootName[] = "<root>";
struct FileSystem {
FileSystem() = default;
FileSystem(const std::string& type,
const std::string& file_system_name,
const std::string& root_url,
const std::string& file_system_path)
: type(type),
file_system_name(file_system_name),
root_url(root_url),
file_system_path(file_system_path) {}
std::string type;
std::string file_system_name;
std::string root_url;
std::string file_system_path;
};
std::string RegisterFileSystem(content::WebContents* web_contents,
const base::FilePath& path) {
auto* isolated_context = storage::IsolatedContext::GetInstance();
std::string root_name(kRootName);
storage::IsolatedContext::ScopedFSHandle file_system =
isolated_context->RegisterFileSystemForPath(
storage::kFileSystemTypeLocal, std::string(), path, &root_name);
content::ChildProcessSecurityPolicy* policy =
content::ChildProcessSecurityPolicy::GetInstance();
content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
int renderer_id = render_view_host->GetProcess()->GetID();
policy->GrantReadFileSystem(renderer_id, file_system.id());
policy->GrantWriteFileSystem(renderer_id, file_system.id());
policy->GrantCreateFileForFileSystem(renderer_id, file_system.id());
policy->GrantDeleteFromFileSystem(renderer_id, file_system.id());
if (!policy->CanReadFile(renderer_id, path))
policy->GrantReadFile(renderer_id, path);
return file_system.id();
}
FileSystem CreateFileSystemStruct(content::WebContents* web_contents,
const std::string& file_system_id,
const std::string& file_system_path,
const std::string& type) {
const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL();
std::string file_system_name =
storage::GetIsolatedFileSystemName(origin, file_system_id);
std::string root_url = storage::GetIsolatedFileSystemRootURIString(
origin, file_system_id, kRootName);
return FileSystem(type, file_system_name, root_url, file_system_path);
}
base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) {
base::Value::Dict value;
value.Set("type", file_system.type);
value.Set("fileSystemName", file_system.file_system_name);
value.Set("rootURL", file_system.root_url);
value.Set("fileSystemPath", file_system.file_system_path);
return value;
}
void WriteToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::WriteFile(path, content.data(), content.size());
}
void AppendToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::AppendToFile(path, content);
}
PrefService* GetPrefService(content::WebContents* web_contents) {
auto* context = web_contents->GetBrowserContext();
return static_cast<electron::ElectronBrowserContext*>(context)->prefs();
}
std::map<std::string, std::string> GetAddedFileSystemPaths(
content::WebContents* web_contents) {
auto* pref_service = GetPrefService(web_contents);
const base::Value::Dict& file_system_paths =
pref_service->GetDict(prefs::kDevToolsFileSystemPaths);
std::map<std::string, std::string> result;
for (auto it : file_system_paths) {
std::string type =
it.second.is_string() ? it.second.GetString() : std::string();
result[it.first] = type;
}
return result;
}
bool IsDevToolsFileSystemAdded(content::WebContents* web_contents,
const std::string& file_system_path) {
return base::Contains(GetAddedFileSystemPaths(web_contents),
file_system_path);
}
void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) {
rwhv->SetBackgroundColor(color);
static_cast<content::RenderWidgetHostViewBase*>(rwhv)
->SetContentBackgroundColor(color);
}
content::RenderFrameHost* GetRenderFrameHost(
content::NavigationHandle* navigation_handle) {
int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId();
content::FrameTreeNode* frame_tree_node =
content::FrameTreeNode::GloballyFindByID(frame_tree_node_id);
content::RenderFrameHostManager* render_manager =
frame_tree_node->render_manager();
content::RenderFrameHost* frame_host = nullptr;
if (render_manager) {
frame_host = render_manager->speculative_frame_host();
if (!frame_host)
frame_host = render_manager->current_frame_host();
}
return frame_host;
}
} // namespace
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) {
switch (view_type) {
case extensions::mojom::ViewType::kExtensionBackgroundPage:
return WebContents::Type::kBackgroundPage;
case extensions::mojom::ViewType::kAppWindow:
case extensions::mojom::ViewType::kComponent:
case extensions::mojom::ViewType::kExtensionPopup:
case extensions::mojom::ViewType::kBackgroundContents:
case extensions::mojom::ViewType::kExtensionGuest:
case extensions::mojom::ViewType::kTabContents:
case extensions::mojom::ViewType::kOffscreenDocument:
case extensions::mojom::ViewType::kExtensionSidePanel:
case extensions::mojom::ViewType::kInvalid:
return WebContents::Type::kRemote;
}
}
#endif
WebContents::WebContents(v8::Isolate* isolate,
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
type_(Type::kRemote),
id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// WebContents created by extension host will have valid ViewType set.
extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents);
if (view_type != extensions::mojom::ViewType::kInvalid) {
InitWithExtensionView(isolate, web_contents, view_type);
}
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents);
script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents);
#endif
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
SetUserAgent(GetBrowserContext()->GetUserAgent());
web_contents->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type)
: content::WebContentsObserver(web_contents.get()),
type_(type),
id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
DCHECK(type != Type::kRemote)
<< "Can't take ownership of a remote WebContents";
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
InitWithSessionAndOptions(isolate, std::move(web_contents), session,
gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
const gin_helper::Dictionary& options)
: id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
// Read options.
options.Get("backgroundThrottling", &background_throttling_);
// Get type
options.Get("type", &type_);
bool b = false;
if (options.Get(options::kOffscreen, &b) && b)
type_ = Type::kOffScreen;
// Init embedder earlier
options.Get("embedder", &embedder_);
// Whether to enable DevTools.
options.Get("devTools", &enable_devtools_);
// BrowserViews are not attached to a window initially so they should start
// off as hidden. This is also important for compositor recycling. See:
// https://github.com/electron/electron/pull/21372
bool initially_shown = type_ != Type::kBrowserView;
options.Get(options::kShow, &initially_shown);
// Obtain the session.
std::string partition;
gin::Handle<api::Session> session;
if (options.Get("session", &session) && !session.IsEmpty()) {
} else if (options.Get("partition", &partition)) {
session = Session::FromPartition(isolate, partition);
} else {
// Use the default session if not specified.
session = Session::FromPartition(isolate, "");
}
session_.Reset(isolate, session.ToV8());
std::unique_ptr<content::WebContents> web_contents;
if (IsGuest()) {
scoped_refptr<content::SiteInstance> site_instance =
content::SiteInstance::CreateForURL(session->browser_context(),
GURL("chrome-guest://fake-host"));
content::WebContents::CreateParams params(session->browser_context(),
site_instance);
guest_delegate_ =
std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this);
params.guest_delegate = guest_delegate_.get();
if (embedder_ && embedder_->IsOffScreen()) {
auto* view = new OffScreenWebContentsView(
false,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
web_contents = content::WebContents::Create(params);
}
} else if (IsOffScreen()) {
// webPreferences does not have a transparent option, so if the window needs
// to be transparent, that will be set at electron_api_browser_window.cc#L57
// and we then need to pull it back out and check it here.
std::string background_color;
options.GetHidden(options::kBackgroundColor, &background_color);
bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT;
content::WebContents::CreateParams params(session->browser_context());
auto* view = new OffScreenWebContentsView(
transparent,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
content::WebContents::CreateParams params(session->browser_context());
params.initially_hidden = !initially_shown;
web_contents = content::WebContents::Create(params);
}
InitWithSessionAndOptions(isolate, std::move(web_contents), session, options);
}
void WebContents::InitZoomController(content::WebContents* web_contents,
const gin_helper::Dictionary& options) {
WebContentsZoomController::CreateForWebContents(web_contents);
zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
double zoom_factor;
if (options.Get(options::kZoomFactor, &zoom_factor))
zoom_controller_->SetDefaultZoomFactor(zoom_factor);
// Nothing to do with ZoomController, but this function gets called in all
// init cases!
content::RenderViewHost* host = web_contents->GetRenderViewHost();
if (host)
host->GetWidget()->AddInputEventObserver(this);
}
void WebContents::InitWithSessionAndOptions(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> owned_web_contents,
gin::Handle<api::Session> session,
const gin_helper::Dictionary& options) {
Observe(owned_web_contents.get());
InitWithWebContents(std::move(owned_web_contents), session->browser_context(),
IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
auto* prefs = web_contents()->GetMutableRendererPrefs();
// Collect preferred languages from OS and browser process. accept_languages
// effects HTTP header, navigator.languages, and CJK fallback font selection.
//
// Note that an application locale set to the browser process might be
// different with the one set to the preference list.
// (e.g. overridden with --lang)
std::string accept_languages =
g_browser_process->GetApplicationLocale() + ",";
for (auto const& language : electron::GetPreferredLanguages()) {
if (language == g_browser_process->GetApplicationLocale())
continue;
accept_languages += language + ",";
}
accept_languages.pop_back();
prefs->accept_languages = accept_languages;
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
// Update font settings.
static const gfx::FontRenderParams params(
gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr));
prefs->should_antialias_text = params.antialiasing;
prefs->use_subpixel_positioning = params.subpixel_positioning;
prefs->hinting = params.hinting;
prefs->use_autohinter = params.autohinter;
prefs->use_bitmaps = params.use_bitmaps;
prefs->subpixel_rendering = params.subpixel_rendering;
#endif
// Honor the system's cursor blink rate settings
if (auto interval = GetCursorBlinkInterval())
prefs->caret_blink_interval = *interval;
// Save the preferences in C++.
// If there's already a WebContentsPreferences object, we created it as part
// of the webContents.setWindowOpenHandler path, so don't overwrite it.
if (!WebContentsPreferences::From(web_contents())) {
new WebContentsPreferences(web_contents(), options);
}
// Trigger re-calculation of webkit prefs.
web_contents()->NotifyPreferencesChanged();
WebContentsPermissionHelper::CreateForWebContents(web_contents());
InitZoomController(web_contents(), options);
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents());
script_executor_ =
std::make_unique<extensions::ScriptExecutor>(web_contents());
#endif
AutofillDriverFactory::CreateForWebContents(web_contents());
SetUserAgent(GetBrowserContext()->GetUserAgent());
if (IsGuest()) {
NativeWindow* owner_window = nullptr;
if (embedder_) {
// New WebContents's owner_window is the embedder's owner_window.
auto* relay =
NativeWindowRelay::FromWebContents(embedder_->web_contents());
if (relay)
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
}
web_contents()->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
void WebContents::InitWithExtensionView(v8::Isolate* isolate,
content::WebContents* web_contents,
extensions::mojom::ViewType view_type) {
// Must reassign type prior to calling `Init`.
type_ = GetTypeFromViewType(view_type);
if (type_ == Type::kRemote)
return;
if (type_ == Type::kBackgroundPage)
// non-background-page WebContents are retained by other classes. We need
// to pin here to prevent background-page WebContents from being GC'd.
// The background page api::WebContents will live until the underlying
// content::WebContents is destroyed.
Pin(isolate);
// Allow toggling DevTools for background pages
Observe(web_contents);
InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents),
GetBrowserContext(), IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
}
#endif
void WebContents::InitWithWebContents(
std::unique_ptr<content::WebContents> web_contents,
ElectronBrowserContext* browser_context,
bool is_guest) {
browser_context_ = browser_context;
web_contents->SetDelegate(this);
#if BUILDFLAG(ENABLE_PRINTING)
PrintViewManagerElectron::CreateForWebContents(web_contents.get());
#endif
// Determine whether the WebContents is offscreen.
auto* web_preferences = WebContentsPreferences::From(web_contents.get());
offscreen_ = web_preferences && web_preferences->IsOffscreen();
// Create InspectableWebContents.
inspectable_web_contents_ = std::make_unique<InspectableWebContents>(
std::move(web_contents), browser_context->prefs(), is_guest);
inspectable_web_contents_->SetDelegate(this);
}
WebContents::~WebContents() {
if (owner_window_) {
owner_window_->RemoveBackgroundThrottlingSource(this);
}
if (web_contents()) {
content::RenderViewHost* host = web_contents()->GetRenderViewHost();
if (host)
host->GetWidget()->RemoveInputEventObserver(this);
}
if (!inspectable_web_contents_) {
WebContentsDestroyed();
return;
}
inspectable_web_contents_->GetView()->SetDelegate(nullptr);
// This event is only for internal use, which is emitted when WebContents is
// being destroyed.
Emit("will-destroy");
// For guest view based on OOPIF, the WebContents is released by the embedder
// frame, and we need to clear the reference to the memory.
bool not_owned_by_this = IsGuest() && attached_;
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// And background pages are owned by extensions::ExtensionHost.
if (type_ == Type::kBackgroundPage)
not_owned_by_this = true;
#endif
if (not_owned_by_this) {
inspectable_web_contents_->ReleaseWebContents();
WebContentsDestroyed();
}
// InspectableWebContents will be automatically destroyed.
}
void WebContents::DeleteThisIfAlive() {
// It is possible that the FirstWeakCallback has been called but the
// SecondWeakCallback has not, in this case the garbage collection of
// WebContents has already started and we should not |delete this|.
// Calling |GetWrapper| can detect this corner case.
auto* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
delete this;
}
void WebContents::Destroy() {
// The content::WebContents should be destroyed asynchronously when possible
// as user may choose to destroy WebContents during an event of it.
if (Browser::Get()->is_shutting_down() || IsGuest()) {
DeleteThisIfAlive();
} else {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&WebContents::DeleteThisIfAlive, GetWeakPtr()));
}
}
void WebContents::Close(absl::optional<gin_helper::Dictionary> options) {
bool dispatch_beforeunload = false;
if (options)
options->Get("waitForBeforeUnload", &dispatch_beforeunload);
if (dispatch_beforeunload &&
web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) {
NotifyUserActivation();
web_contents()->DispatchBeforeUnload(false /* auto_cancel */);
} else {
web_contents()->Close();
}
}
bool WebContents::DidAddMessageToConsole(
content::WebContents* source,
blink::mojom::ConsoleMessageLevel level,
const std::u16string& message,
int32_t line_no,
const std::u16string& source_id) {
return Emit("console-message", static_cast<int32_t>(level), message, line_no,
source_id);
}
void WebContents::OnCreateWindow(
const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const std::string& features,
const scoped_refptr<network::ResourceRequestBody>& body) {
Emit("-new-window", target_url, frame_name, disposition, features, referrer,
body);
}
void WebContents::WebContentsCreatedWithFullParams(
content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const content::mojom::CreateNewWindowParams& params,
content::WebContents* new_contents) {
ChildWebContentsTracker::CreateForWebContents(new_contents);
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents);
tracker->url = params.target_url;
tracker->frame_name = params.frame_name;
tracker->referrer = params.referrer.To<content::Referrer>();
tracker->raw_features = params.raw_features;
tracker->body = params.body;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary dict;
gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate),
&dict);
pending_child_web_preferences_.Reset();
// Associate the preferences passed in via `setWindowOpenHandler` with the
// content::WebContents that was just created for the child window. These
// preferences will be picked up by the RenderWidgetHost via its call to the
// delegate's OverrideWebkitPrefs.
new WebContentsPreferences(new_contents, dict);
}
bool WebContents::IsWebContentsCreationOverridden(
content::SiteInstance* source_site_instance,
content::mojom::WindowContainerType window_container_type,
const GURL& opener_url,
const content::mojom::CreateNewWindowParams& params) {
bool default_prevented = Emit(
"-will-add-new-contents", params.target_url, params.frame_name,
params.raw_features, params.disposition, *params.referrer, params.body);
// If the app prevented the default, redirect to CreateCustomWebContents,
// which always returns nullptr, which will result in the window open being
// prevented (window.open() will return null in the renderer).
return default_prevented;
}
void WebContents::SetNextChildWebPreferences(
const gin_helper::Dictionary preferences) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
// Store these prefs for when Chrome calls WebContentsCreatedWithFullParams
// with the new child contents.
pending_child_web_preferences_.Reset(isolate, preferences.GetHandle());
}
content::WebContents* WebContents::CreateCustomWebContents(
content::RenderFrameHost* opener,
content::SiteInstance* source_site_instance,
bool is_new_browsing_instance,
const GURL& opener_url,
const std::string& frame_name,
const GURL& target_url,
const content::StoragePartitionConfig& partition_config,
content::SessionStorageNamespace* session_storage_namespace) {
return nullptr;
}
void WebContents::AddNewContents(
content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) {
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get());
DCHECK(tracker);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto api_web_contents =
CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow);
// We call RenderFrameCreated here as at this point the empty "about:blank"
// render frame has already been created. If the window never navigates again
// RenderFrameCreated won't be called and certain prefs like
// "kBackgroundColor" will not be applied.
auto* frame = api_web_contents->MainFrame();
if (frame) {
api_web_contents->HandleNewRenderFrame(frame);
}
if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
window_features.bounds.x(), window_features.bounds.y(),
window_features.bounds.width(), window_features.bounds.height(),
tracker->url, tracker->frame_name, tracker->referrer,
tracker->raw_features, tracker->body)) {
api_web_contents->Destroy();
}
}
content::WebContents* WebContents::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
auto weak_this = GetWeakPtr();
if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {
Emit("-new-window", params.url, "", params.disposition, "", params.referrer,
params.post_data);
return nullptr;
}
if (!weak_this || !web_contents())
return nullptr;
content::NavigationController::LoadURLParams load_url_params(params.url);
load_url_params.referrer = params.referrer;
load_url_params.transition_type = params.transition;
load_url_params.extra_headers = params.extra_headers;
load_url_params.should_replace_current_entry =
params.should_replace_current_entry;
load_url_params.is_renderer_initiated = params.is_renderer_initiated;
load_url_params.started_from_context_menu = params.started_from_context_menu;
load_url_params.initiator_origin = params.initiator_origin;
load_url_params.source_site_instance = params.source_site_instance;
load_url_params.frame_tree_node_id = params.frame_tree_node_id;
load_url_params.redirect_chain = params.redirect_chain;
load_url_params.has_user_gesture = params.user_gesture;
load_url_params.blob_url_loader_factory = params.blob_url_loader_factory;
load_url_params.href_translate = params.href_translate;
load_url_params.reload_type = params.reload_type;
if (params.post_data) {
load_url_params.load_type =
content::NavigationController::LOAD_TYPE_HTTP_POST;
load_url_params.post_data = params.post_data;
}
source->GetController().LoadURLWithParams(load_url_params);
return source;
}
void WebContents::BeforeUnloadFired(content::WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) {
if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen ||
type_ == Type::kBrowserView)
*proceed_to_fire_unload = proceed;
else
*proceed_to_fire_unload = true;
// Note that Chromium does not emit this for navigations.
Emit("before-unload-fired", proceed);
}
void WebContents::SetContentsBounds(content::WebContents* source,
const gfx::Rect& rect) {
if (!Emit("content-bounds-updated", rect))
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnSetContentBounds(rect);
}
void WebContents::CloseContents(content::WebContents* source) {
Emit("close");
auto* autofill_driver_factory =
AutofillDriverFactory::FromWebContents(web_contents());
if (autofill_driver_factory) {
autofill_driver_factory->CloseAllPopups();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnCloseContents();
// This is handled by the embedder frame.
if (!IsGuest())
Destroy();
}
void WebContents::ActivateContents(content::WebContents* source) {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnActivateContents();
}
void WebContents::UpdateTargetURL(content::WebContents* source,
const GURL& url) {
Emit("update-target-url", url);
}
bool WebContents::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (type_ == Type::kWebView && embedder_) {
// Send the unhandled keyboard events back to the embedder.
return embedder_->HandleKeyboardEvent(source, event);
} else {
return PlatformHandleKeyboardEvent(source, event);
}
}
#if !BUILDFLAG(IS_MAC)
// NOTE: The macOS version of this function is found in
// electron_api_web_contents_mac.mm, as it requires calling into objective-C
// code.
bool WebContents::PlatformHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
// Escape exits tabbed fullscreen mode.
if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) {
ExitFullscreenModeForTab(source);
return true;
}
// Check if the webContents has preferences and to ignore shortcuts
auto* web_preferences = WebContentsPreferences::From(source);
if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts())
return false;
// Let the NativeWindow handle other parts.
if (owner_window()) {
owner_window()->HandleKeyboardEvent(source, event);
return true;
}
return false;
}
#endif
content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (exclusive_access_manager_.HandleUserKeyEvent(event))
return content::KeyboardEventProcessingResult::HANDLED;
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown ||
event.GetType() == blink::WebInputEvent::Type::kKeyUp) {
// For backwards compatibility, pretend that `kRawKeyDown` events are
// actually `kKeyDown`.
content::NativeWebKeyboardEvent tweaked_event(event);
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown)
tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown);
bool prevent_default = Emit("before-input-event", tweaked_event);
if (prevent_default) {
return content::KeyboardEventProcessingResult::HANDLED;
}
}
return content::KeyboardEventProcessingResult::NOT_HANDLED;
}
void WebContents::ContentsZoomChange(bool zoom_in) {
Emit("zoom-changed", zoom_in ? "in" : "out");
}
Profile* WebContents::GetProfile() {
return nullptr;
}
bool WebContents::IsFullscreen() const {
if (!owner_window())
return false;
return owner_window()->IsFullscreen() || is_html_fullscreen();
}
void WebContents::EnterFullscreen(const GURL& url,
ExclusiveAccessBubbleType bubble_type,
const int64_t display_id) {}
void WebContents::ExitFullscreen() {}
void WebContents::UpdateExclusiveAccessExitBubbleContent(
const GURL& url,
ExclusiveAccessBubbleType bubble_type,
ExclusiveAccessBubbleHideCallback bubble_first_hide_callback,
bool notify_download,
bool force_update) {}
void WebContents::OnExclusiveAccessUserInput() {}
content::WebContents* WebContents::GetActiveWebContents() {
return web_contents();
}
bool WebContents::CanUserExitFullscreen() const {
return true;
}
bool WebContents::IsExclusiveAccessBubbleDisplayed() const {
return false;
}
void WebContents::EnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options) {
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(source);
auto callback =
base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab,
base::Unretained(this), requesting_frame, options);
permission_helper->RequestFullscreenPermission(requesting_frame, callback);
}
void WebContents::OnEnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options,
bool allowed) {
if (!allowed || !owner_window())
return;
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
if (IsFullscreenForTabOrPending(source)) {
DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame());
return;
}
owner_window()->set_fullscreen_transition_type(
NativeWindow::FullScreenTransitionType::kHTML);
exclusive_access_manager_.fullscreen_controller()->EnterFullscreenModeForTab(
requesting_frame, options.display_id);
SetHtmlApiFullscreen(true);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
if (!owner_window())
return;
// This needs to be called before we exit fullscreen on the native window,
// or the controller will incorrectly think we weren't fullscreen and bail.
exclusive_access_manager_.fullscreen_controller()->ExitFullscreenModeForTab(
source);
SetHtmlApiFullscreen(false);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too. Chrome does this indirectly from
// `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::RendererUnresponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host,
base::RepeatingClosure hang_monitor_restarter) {
Emit("unresponsive");
}
void WebContents::RendererResponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host) {
Emit("responsive");
}
bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) {
Emit("context-menu", std::make_pair(params, &render_frame_host));
return true;
}
void WebContents::FindReply(content::WebContents* web_contents,
int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update) {
if (!final_update)
return;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto result = gin_helper::Dictionary::CreateEmpty(isolate);
result.Set("requestId", request_id);
result.Set("matches", number_of_matches);
result.Set("selectionArea", selection_rect);
result.Set("activeMatchOrdinal", active_match_ordinal);
result.Set("finalUpdate", final_update); // Deprecate after 2.0
Emit("found-in-page", result.GetHandle());
}
void WebContents::RequestExclusivePointerAccess(
content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target,
bool allowed) {
if (allowed) {
exclusive_access_manager_.mouse_lock_controller()->RequestToLockMouse(
web_contents, user_gesture, last_unlocked_by_target);
} else {
web_contents->GotResponseToLockMouseRequest(
blink::mojom::PointerLockResult::kPermissionDenied);
}
}
void WebContents::RequestToLockMouse(content::WebContents* web_contents,
bool user_gesture,
bool last_unlocked_by_target) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestPointerLockPermission(
user_gesture, last_unlocked_by_target,
base::BindOnce(&WebContents::RequestExclusivePointerAccess,
base::Unretained(this)));
}
void WebContents::LostMouseLock() {
exclusive_access_manager_.mouse_lock_controller()->LostMouseLock();
}
void WebContents::RequestKeyboardLock(content::WebContents* web_contents,
bool esc_key_locked) {
exclusive_access_manager_.keyboard_lock_controller()->RequestKeyboardLock(
web_contents, esc_key_locked);
}
void WebContents::CancelKeyboardLockRequest(
content::WebContents* web_contents) {
exclusive_access_manager_.keyboard_lock_controller()
->CancelKeyboardLockRequest(web_contents);
}
bool WebContents::CheckMediaAccessPermission(
content::RenderFrameHost* render_frame_host,
const GURL& security_origin,
blink::mojom::MediaStreamType type) {
auto* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
return permission_helper->CheckMediaAccessPermission(security_origin, type);
}
void WebContents::RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
content::MediaResponseCallback callback) {
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(web_contents);
permission_helper->RequestMediaAccessPermission(request, std::move(callback));
}
content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager(
content::WebContents* source) {
if (!dialog_manager_)
dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>();
return dialog_manager_.get();
}
void WebContents::OnAudioStateChanged(bool audible) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
gin::Dictionary dict(isolate, event_object);
dict.Set("audible", audible);
EmitWithoutEvent("audio-state-changed", event);
}
void WebContents::BeforeUnloadFired(bool proceed) {
// Do nothing, we override this method just to avoid compilation error since
// there are two virtual functions named BeforeUnloadFired.
}
void WebContents::HandleNewRenderFrame(
content::RenderFrameHost* render_frame_host) {
auto* rwhv = render_frame_host->GetView();
if (!rwhv)
return;
// Set the background color of RenderWidgetHostView.
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences) {
auto maybe_color = web_preferences->GetBackgroundColor();
bool guest = IsGuest() || type_ == Type::kBrowserView;
// If webPreferences has no color stored we need to explicitly set guest
// webContents background color to transparent.
auto bg_color =
maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE);
web_contents()->SetPageBaseBackgroundColor(bg_color);
SetBackgroundColor(rwhv, bg_color);
}
if (!background_throttling_)
render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false);
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (rwh_impl)
rwh_impl->disable_hidden_ = !background_throttling_;
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->MaybeSetupMojoConnection();
}
void WebContents::OnBackgroundColorChanged() {
absl::optional<SkColor> color = web_contents()->GetBackgroundColor();
if (color.has_value()) {
auto* const view = web_contents()->GetRenderWidgetHostView();
static_cast<content::RenderWidgetHostViewBase*>(view)
->SetContentBackgroundColor(color.value());
}
}
void WebContents::RenderFrameCreated(
content::RenderFrameHost* render_frame_host) {
HandleNewRenderFrame(render_frame_host);
// RenderFrameCreated is called for speculative frames which may not be
// used in certain cross-origin navigations. Invoking
// RenderFrameHost::GetLifecycleState currently crashes when called for
// speculative frames so we need to filter it out for now. Check
// https://crbug.com/1183639 for details on when this can be removed.
auto* rfh_impl =
static_cast<content::RenderFrameHostImpl*>(render_frame_host);
if (rfh_impl->lifecycle_state() ==
content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) {
return;
}
content::RenderFrameHost::LifecycleState lifecycle_state =
render_frame_host->GetLifecycleState();
if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.SetGetter("frame", render_frame_host);
Emit("frame-created", details);
}
}
void WebContents::RenderFrameDeleted(
content::RenderFrameHost* render_frame_host) {
// A RenderFrameHost can be deleted when:
// - A WebContents is removed and its containing frames are disposed.
// - An <iframe> is removed from the DOM.
// - Cross-origin navigation creates a new RFH in a separate process which
// is swapped by content::RenderFrameHostManager.
//
// WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID
// to find an existing instance of WebFrameMain. During a cross-origin
// navigation, the deleted RFH will be the old host which was swapped out. In
// this special case, we need to also ensure that WebFrameMain's internal RFH
// matches before marking it as disposed.
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame && web_frame->render_frame_host() == render_frame_host)
web_frame->MarkRenderFrameDisposed();
}
void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) {
if (new_host->IsInPrimaryMainFrame()) {
if (old_host)
old_host->GetRenderWidgetHost()->RemoveInputEventObserver(this);
if (new_host)
new_host->GetRenderWidgetHost()->AddInputEventObserver(this);
}
// During cross-origin navigation, a FrameTreeNode will swap out its RFH.
// If an instance of WebFrameMain exists, it will need to have its RFH
// swapped as well.
//
// |old_host| can be a nullptr so we use |new_host| for looking up the
// WebFrameMain instance.
auto* web_frame = WebFrameMain::FromRenderFrameHost(new_host);
if (web_frame) {
web_frame->UpdateRenderFrameHost(new_host);
}
}
void WebContents::FrameDeleted(int frame_tree_node_id) {
auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id);
if (web_frame)
web_frame->Destroyed();
}
void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
// This event is necessary for tracking any states with respect to
// intermediate render view hosts aka speculative render view hosts. Currently
// used by object-registry.js to ref count remote objects.
Emit("render-view-deleted", render_view_host->GetProcess()->GetID());
if (web_contents()->GetRenderViewHost() == render_view_host) {
// When the RVH that has been deleted is the current RVH it means that the
// the web contents are being closed. This is communicated by this event.
// Currently tracked by guest-window-manager.ts to destroy the
// BrowserWindow.
Emit("current-render-view-deleted",
render_view_host->GetProcess()->GetID());
}
}
void WebContents::PrimaryMainFrameRenderProcessGone(
base::TerminationStatus status) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("reason", status);
details.Set("exitCode", web_contents()->GetCrashedErrorCode());
Emit("render-process-gone", details);
}
void WebContents::PluginCrashed(const base::FilePath& plugin_path,
base::ProcessId plugin_pid) {
#if BUILDFLAG(ENABLE_PLUGINS)
content::WebPluginInfo info;
auto* plugin_service = content::PluginService::GetInstance();
plugin_service->GetPluginInfoByPath(plugin_path, &info);
Emit("plugin-crashed", info.name, info.version);
#endif // BUILDFLAG(ENABLE_PLUGINS)
}
void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id) {
Emit("media-started-playing");
}
void WebContents::MediaStoppedPlaying(
const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id,
content::WebContentsObserver::MediaStoppedReason reason) {
Emit("media-paused");
}
void WebContents::DidChangeThemeColor() {
auto theme_color = web_contents()->GetThemeColor();
if (theme_color) {
Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value()));
} else {
Emit("did-change-theme-color", nullptr);
}
}
void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) {
set_fullscreen_frame(rfh);
}
void WebContents::OnWebContentsFocused(
content::RenderWidgetHost* render_widget_host) {
Emit("focus");
}
void WebContents::OnWebContentsLostFocus(
content::RenderWidgetHost* render_widget_host) {
Emit("blur");
}
void WebContents::DOMContentLoaded(
content::RenderFrameHost* render_frame_host) {
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->DOMContentLoaded();
if (!render_frame_host->GetParent())
Emit("dom-ready");
}
void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url) {
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
auto weak_this = GetWeakPtr();
Emit("did-frame-finish-load", is_main_frame, frame_process_id,
frame_routing_id);
// β οΈWARNING!β οΈ
// Emit() triggers JS which can call destroy() on |this|. It's not safe to
// assume that |this| points to valid memory at this point.
if (is_main_frame && weak_this && web_contents())
Emit("did-finish-load");
}
void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
const GURL& url,
int error_code) {
// See DocumentLoader::StartLoadingResponse() - when we navigate to a media
// resource the original request for the media resource, which resulted in a
// committed navigation, is simply discarded. The media element created
// inside the MediaDocument then makes *another new* request for the same
// media resource.
bool is_media_document =
media::IsSupportedMediaMimeType(web_contents()->GetContentsMimeType());
if (error_code == net::ERR_ABORTED && is_media_document)
return;
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id,
frame_routing_id);
}
void WebContents::DidStartLoading() {
Emit("did-start-loading");
}
void WebContents::DidStopLoading() {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences && web_preferences->ShouldUsePreferredSizeMode())
web_contents()->GetRenderViewHost()->EnablePreferredSizeMode();
Emit("did-stop-loading");
}
bool WebContents::EmitNavigationEvent(
const std::string& event_name,
content::NavigationHandle* navigation_handle) {
bool is_main_frame = navigation_handle->IsInMainFrame();
int frame_process_id = -1, frame_routing_id = -1;
content::RenderFrameHost* frame_host = GetRenderFrameHost(navigation_handle);
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
bool is_same_document = navigation_handle->IsSameDocument();
auto url = navigation_handle->GetURL();
content::RenderFrameHost* initiator_frame_host =
navigation_handle->GetInitiatorFrameToken().has_value()
? content::RenderFrameHost::FromFrameToken(
navigation_handle->GetInitiatorProcessId(),
navigation_handle->GetInitiatorFrameToken().value())
: nullptr;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
gin_helper::Dictionary dict(isolate, event_object);
dict.Set("url", url);
dict.Set("isSameDocument", is_same_document);
dict.Set("isMainFrame", is_main_frame);
dict.SetGetter("frame", frame_host);
dict.SetGetter("initiator", initiator_frame_host);
EmitWithoutEvent(event_name, event, url, is_same_document, is_main_frame,
frame_process_id, frame_routing_id);
return event->GetDefaultPrevented();
}
void WebContents::Message(bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Message", "channel", channel);
// webContents.emit('-ipc-message', new Event(), internal, channel,
// arguments);
EmitWithSender("-ipc-message", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), internal,
channel, std::move(arguments));
}
void WebContents::Invoke(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::InvokeCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel);
// webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments);
EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::OnFirstNonEmptyLayout(
content::RenderFrameHost* render_frame_host) {
if (render_frame_host == web_contents()->GetPrimaryMainFrame()) {
Emit("ready-to-show");
}
}
// This object wraps the InvokeCallback so that if it gets GC'd by V8, we can
// still call the callback and send an error. Not doing so causes a Mojo DCHECK,
// since Mojo requires callbacks to be called before they are destroyed.
class ReplyChannel : public gin::Wrappable<ReplyChannel> {
public:
using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback;
static gin::Handle<ReplyChannel> Create(v8::Isolate* isolate,
InvokeCallback callback) {
return gin::CreateHandle(isolate, new ReplyChannel(std::move(callback)));
}
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override {
return gin::Wrappable<ReplyChannel>::GetObjectTemplateBuilder(isolate)
.SetMethod("sendReply", &ReplyChannel::SendReply);
}
const char* GetTypeName() override { return "ReplyChannel"; }
void SendError(const std::string& msg) {
v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
// If there's no current context, it means we're shutting down, so we
// don't need to send an event.
if (!isolate->GetCurrentContext().IsEmpty()) {
v8::HandleScope scope(isolate);
auto message = gin::DataObjectBuilder(isolate).Set("error", msg).Build();
SendReply(isolate, message);
}
}
private:
explicit ReplyChannel(InvokeCallback callback)
: callback_(std::move(callback)) {}
~ReplyChannel() override {
if (callback_)
SendError("reply was never sent");
}
bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> arg) {
if (!callback_)
return false;
blink::CloneableMessage message;
if (!gin::ConvertFromV8(isolate, arg, &message)) {
return false;
}
std::move(callback_).Run(std::move(message));
return true;
}
InvokeCallback callback_;
};
gin::WrapperInfo ReplyChannel::kWrapperInfo = {gin::kEmbedderNativeGin};
gin::Handle<gin_helper::internal::Event> WebContents::MakeEventWithSender(
v8::Isolate* isolate,
content::RenderFrameHost* frame,
electron::mojom::ElectronApiIPC::InvokeCallback callback) {
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper)) {
if (callback) {
// We must always invoke the callback if present.
ReplyChannel::Create(isolate, std::move(callback))
->SendError("WebContents was destroyed");
}
return gin::Handle<gin_helper::internal::Event>();
}
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
gin_helper::Dictionary dict(isolate, event.ToV8().As<v8::Object>());
if (callback)
dict.Set("_replyChannel",
ReplyChannel::Create(isolate, std::move(callback)));
if (frame) {
dict.Set("frameId", frame->GetRoutingID());
dict.Set("processId", frame->GetProcess()->GetID());
}
return event;
}
void WebContents::ReceivePostMessage(
const std::string& channel,
blink::TransferableMessage message,
content::RenderFrameHost* render_frame_host) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto wrapped_ports =
MessagePort::EntanglePorts(isolate, std::move(message.ports));
v8::Local<v8::Value> message_value =
electron::DeserializeV8Value(isolate, message);
EmitWithSender("-ipc-ports", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), false,
channel, message_value, std::move(wrapped_ports));
}
void WebContents::MessageSync(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::MessageSyncCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel);
// webContents.emit('-ipc-message-sync', new Event(sender, message), internal,
// channel, arguments);
EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::MessageHost(const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel);
// webContents.emit('ipc-message-host', new Event(), channel, args);
EmitWithSender("ipc-message-host", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), channel,
std::move(arguments));
}
void WebContents::UpdateDraggableRegions(
std::vector<mojom::DraggableRegionPtr> regions) {
if (owner_window() && owner_window()->has_frame())
return;
draggable_region_ = DraggableRegionsToSkRegion(regions);
}
void WebContents::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-start-navigation", navigation_handle);
}
void WebContents::DidRedirectNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-redirect-navigation", navigation_handle);
}
void WebContents::ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) {
// Don't focus content in an inactive window.
if (!owner_window())
return;
#if BUILDFLAG(IS_MAC)
if (!owner_window()->IsActive())
return;
#else
if (!owner_window()->widget()->IsActive())
return;
#endif
// Don't focus content after subframe navigations.
if (!navigation_handle->IsInMainFrame())
return;
// Only focus for top-level contents.
if (type_ != Type::kBrowserWindow)
return;
web_contents()->SetInitialFocus();
}
void WebContents::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (owner_window_) {
owner_window_->NotifyLayoutWindowControlsOverlay();
}
if (!navigation_handle->HasCommitted())
return;
bool is_main_frame = navigation_handle->IsInMainFrame();
content::RenderFrameHost* frame_host =
navigation_handle->GetRenderFrameHost();
int frame_process_id = -1, frame_routing_id = -1;
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
if (!navigation_handle->IsErrorPage()) {
// FIXME: All the Emit() calls below could potentially result in |this|
// being destroyed (by JS listening for the event and calling
// webContents.destroy()).
auto url = navigation_handle->GetURL();
bool is_same_document = navigation_handle->IsSameDocument();
if (is_same_document) {
Emit("did-navigate-in-page", url, is_main_frame, frame_process_id,
frame_routing_id);
} else {
const net::HttpResponseHeaders* http_response =
navigation_handle->GetResponseHeaders();
std::string http_status_text;
int http_response_code = -1;
if (http_response) {
http_status_text = http_response->GetStatusText();
http_response_code = http_response->response_code();
}
Emit("did-frame-navigate", url, http_response_code, http_status_text,
is_main_frame, frame_process_id, frame_routing_id);
if (is_main_frame) {
Emit("did-navigate", url, http_response_code, http_status_text);
}
}
if (IsGuest())
Emit("load-commit", url, is_main_frame);
} else {
auto url = navigation_handle->GetURL();
int code = navigation_handle->GetNetErrorCode();
auto description = net::ErrorToShortString(code);
Emit("did-fail-provisional-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
// Do not emit "did-fail-load" for canceled requests.
if (code != net::ERR_ABORTED) {
EmitWarning(
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()),
"Failed to load URL: " + url.possibly_invalid_spec() +
" with error: " + description,
"electron");
Emit("did-fail-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
}
}
content::NavigationEntry* entry = navigation_handle->GetNavigationEntry();
// This check is needed due to an issue in Chromium
// Check the Chromium issue to keep updated:
// https://bugs.chromium.org/p/chromium/issues/detail?id=1178663
// If a history entry has been made and the forward/back call has been made,
// proceed with setting the new title
if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK))
WebContents::TitleWasSet(entry);
}
void WebContents::TitleWasSet(content::NavigationEntry* entry) {
std::u16string final_title;
bool explicit_set = true;
if (entry) {
auto title = entry->GetTitle();
auto url = entry->GetURL();
if (url.SchemeIsFile() && title.empty()) {
final_title = base::UTF8ToUTF16(url.ExtractFileName());
explicit_set = false;
} else {
final_title = title;
}
} else {
final_title = web_contents()->GetTitle();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnPageTitleUpdated(final_title, explicit_set);
Emit("page-title-updated", final_title, explicit_set);
}
void WebContents::DidUpdateFaviconURL(
content::RenderFrameHost* render_frame_host,
const std::vector<blink::mojom::FaviconURLPtr>& urls) {
std::set<GURL> unique_urls;
for (const auto& iter : urls) {
if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon)
continue;
const GURL& url = iter->icon_url;
if (url.is_valid())
unique_urls.insert(url);
}
Emit("page-favicon-updated", unique_urls);
}
void WebContents::DevToolsReloadPage() {
Emit("devtools-reload-page");
}
void WebContents::DevToolsFocused() {
Emit("devtools-focused");
}
void WebContents::DevToolsOpened() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
DCHECK(inspectable_web_contents_);
DCHECK(inspectable_web_contents_->GetDevToolsWebContents());
auto handle = FromOrCreate(
isolate, inspectable_web_contents_->GetDevToolsWebContents());
devtools_web_contents_.Reset(isolate, handle.ToV8());
// Set inspected tabID.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "setInspectedTabId", base::Value(ID()));
// Inherit owner window in devtools when it doesn't have one.
auto* devtools = inspectable_web_contents_->GetDevToolsWebContents();
bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey());
if (owner_window() && !has_window)
handle->SetOwnerWindow(devtools, owner_window());
Emit("devtools-opened");
}
void WebContents::DevToolsClosed() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
devtools_web_contents_.Reset();
Emit("devtools-closed");
}
void WebContents::DevToolsResized() {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnDevToolsResized();
}
void WebContents::SetOwnerWindow(NativeWindow* owner_window) {
SetOwnerWindow(GetWebContents(), owner_window);
}
void WebContents::SetOwnerWindow(content::WebContents* web_contents,
NativeWindow* owner_window) {
if (owner_window_) {
owner_window_->RemoveBackgroundThrottlingSource(this);
}
if (owner_window) {
owner_window_ = owner_window->GetWeakPtr();
NativeWindowRelay::CreateForWebContents(web_contents,
owner_window->GetWeakPtr());
owner_window_->AddBackgroundThrottlingSource(this);
} else {
owner_window_ = nullptr;
web_contents->RemoveUserData(NativeWindowRelay::UserDataKey());
}
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetNativeWindow(owner_window);
}
content::WebContents* WebContents::GetWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetWebContents();
}
content::WebContents* WebContents::GetDevToolsWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetDevToolsWebContents();
}
void WebContents::WebContentsDestroyed() {
// Clear the pointer stored in wrapper.
if (GetAllWebContents().Lookup(id_))
GetAllWebContents().Remove(id_);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
wrapper->SetAlignedPointerInInternalField(0, nullptr);
// Tell WebViewGuestDelegate that the WebContents has been destroyed.
if (guest_delegate_)
guest_delegate_->WillDestroy();
Observe(nullptr);
Emit("destroyed");
}
void WebContents::NavigationEntryCommitted(
const content::LoadCommittedDetails& details) {
Emit("navigation-entry-committed", details.entry->GetURL(),
details.is_same_document, details.did_replace_entry);
}
bool WebContents::GetBackgroundThrottling() const {
return background_throttling_;
}
void WebContents::SetBackgroundThrottling(bool allowed) {
background_throttling_ = allowed;
if (owner_window_) {
owner_window_->UpdateBackgroundThrottlingState();
}
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (!rfh)
return;
auto* rwhv = rfh->GetView();
if (!rwhv)
return;
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (!rwh_impl)
return;
rwh_impl->disable_hidden_ = !background_throttling_;
web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed);
if (rwh_impl->is_hidden()) {
rwh_impl->WasShown({});
}
}
int WebContents::GetProcessID() const {
return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
}
base::ProcessId WebContents::GetOSProcessID() const {
base::ProcessHandle process_handle = web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->GetProcess()
.Handle();
return base::GetProcId(process_handle);
}
WebContents::Type WebContents::GetType() const {
return type_;
}
bool WebContents::Equal(const WebContents* web_contents) const {
return ID() == web_contents->ID();
}
GURL WebContents::GetURL() const {
return web_contents()->GetLastCommittedURL();
}
void WebContents::LoadURL(const GURL& url,
const gin_helper::Dictionary& options) {
if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL),
net::ErrorToShortString(net::ERR_INVALID_URL),
url.possibly_invalid_spec(), true);
return;
}
content::NavigationController::LoadURLParams params(url);
if (!options.Get("httpReferrer", ¶ms.referrer)) {
GURL http_referrer;
if (options.Get("httpReferrer", &http_referrer))
params.referrer =
content::Referrer(http_referrer.GetAsReferrer(),
network::mojom::ReferrerPolicy::kDefault);
}
std::string user_agent;
if (options.Get("userAgent", &user_agent))
SetUserAgent(user_agent);
std::string extra_headers;
if (options.Get("extraHeaders", &extra_headers))
params.extra_headers = extra_headers;
scoped_refptr<network::ResourceRequestBody> body;
if (options.Get("postData", &body)) {
params.post_data = body;
params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
}
GURL base_url_for_data_url;
if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
params.base_url_for_data_url = base_url_for_data_url;
params.load_type = content::NavigationController::LOAD_TYPE_DATA;
}
bool reload_ignoring_cache = false;
if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) &&
reload_ignoring_cache) {
params.reload_type = content::ReloadType::BYPASSING_CACHE;
}
// Calling LoadURLWithParams() can trigger JS which destroys |this|.
auto weak_this = GetWeakPtr();
params.transition_type = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
// It's not safe to start a new navigation or otherwise discard the current
// one while the call that started it is still on the stack. See
// http://crbug.com/347742.
auto& ctrl_impl = static_cast<content::NavigationControllerImpl&>(
web_contents()->GetController());
if (ctrl_impl.in_navigate_to_pending_entry()) {
Emit("did-fail-load", static_cast<int>(net::ERR_FAILED),
net::ErrorToShortString(net::ERR_FAILED), url.possibly_invalid_spec(),
true);
return;
}
// Discard non-committed entries to ensure we don't re-use a pending entry.
web_contents()->GetController().DiscardNonCommittedEntries();
web_contents()->GetController().LoadURLWithParams(params);
// β οΈWARNING!β οΈ
// LoadURLWithParams() triggers JS events which can call destroy() on |this|.
// It's not safe to assume that |this| points to valid memory at this point.
if (!weak_this || !web_contents())
return;
// Required to make beforeunload handler work.
NotifyUserActivation();
}
// TODO(MarshallOfSound): Figure out what we need to do with post data here, I
// believe the default behavior when we pass "true" is to phone out to the
// delegate and then the controller expects this method to be called again with
// "false" if the user approves the reload. For now this would result in
// ".reload()" calls on POST data domains failing silently. Passing false would
// result in them succeeding, but reposting which although more correct could be
// considering a breaking change.
void WebContents::Reload() {
web_contents()->GetController().Reload(content::ReloadType::NORMAL,
/* check_for_repost */ true);
}
void WebContents::ReloadIgnoringCache() {
web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE,
/* check_for_repost */ true);
}
void WebContents::DownloadURL(const GURL& url, gin::Arguments* args) {
std::map<std::string, std::string> headers;
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
if (options.Has("headers") && !options.Get("headers", &headers)) {
args->ThrowTypeError("Invalid value for headers - must be an object");
return;
}
}
std::unique_ptr<download::DownloadUrlParameters> download_params(
content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
web_contents(), url, MISSING_TRAFFIC_ANNOTATION));
for (const auto& [name, value] : headers) {
download_params->add_request_header(name, value);
}
auto* download_manager =
web_contents()->GetBrowserContext()->GetDownloadManager();
download_manager->DownloadUrl(std::move(download_params));
}
std::u16string WebContents::GetTitle() const {
return web_contents()->GetTitle();
}
bool WebContents::IsLoading() const {
return web_contents()->IsLoading();
}
bool WebContents::IsLoadingMainFrame() const {
return web_contents()->ShouldShowLoadingUI();
}
bool WebContents::IsWaitingForResponse() const {
return web_contents()->IsWaitingForResponse();
}
void WebContents::Stop() {
web_contents()->Stop();
}
bool WebContents::CanGoBack() const {
return web_contents()->GetController().CanGoBack();
}
void WebContents::GoBack() {
if (CanGoBack())
web_contents()->GetController().GoBack();
}
bool WebContents::CanGoForward() const {
return web_contents()->GetController().CanGoForward();
}
void WebContents::GoForward() {
if (CanGoForward())
web_contents()->GetController().GoForward();
}
bool WebContents::CanGoToOffset(int offset) const {
return web_contents()->GetController().CanGoToOffset(offset);
}
void WebContents::GoToOffset(int offset) {
if (CanGoToOffset(offset))
web_contents()->GetController().GoToOffset(offset);
}
bool WebContents::CanGoToIndex(int index) const {
return index >= 0 && index < GetHistoryLength();
}
void WebContents::GoToIndex(int index) {
if (CanGoToIndex(index))
web_contents()->GetController().GoToIndex(index);
}
int WebContents::GetActiveIndex() const {
return web_contents()->GetController().GetCurrentEntryIndex();
}
void WebContents::ClearHistory() {
// In some rare cases (normally while there is no real history) we are in a
// state where we can't prune navigation entries
if (web_contents()->GetController().CanPruneAllButLastCommitted()) {
web_contents()->GetController().PruneAllButLastCommitted();
}
}
int WebContents::GetHistoryLength() const {
return web_contents()->GetController().GetEntryCount();
}
const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy;
}
void WebContents::SetWebRTCIPHandlingPolicy(
const std::string& webrtc_ip_handling_policy) {
if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
return;
web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
webrtc_ip_handling_policy;
web_contents()->SyncRendererPrefs();
}
v8::Local<v8::Value> WebContents::GetWebRTCUDPPortRange(
v8::Isolate* isolate) const {
auto* prefs = web_contents()->GetMutableRendererPrefs();
auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
dict.Set("min", static_cast<uint32_t>(prefs->webrtc_udp_min_port));
dict.Set("max", static_cast<uint32_t>(prefs->webrtc_udp_max_port));
return dict.GetHandle();
}
void WebContents::SetWebRTCUDPPortRange(gin::Arguments* args) {
uint32_t min = 0, max = 0;
gin_helper::Dictionary range;
if (!args->GetNext(&range) || !range.Get("min", &min) ||
!range.Get("max", &max)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'min' and 'max' are both required");
return;
}
if ((0 == min && 0 != max) || max > UINT16_MAX) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError(
"'min' and 'max' must be in the (0, 65535] range or [0, 0]");
return;
}
if (min > max) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'max' must be greater than or equal to 'min'");
return;
}
auto* prefs = web_contents()->GetMutableRendererPrefs();
if (prefs->webrtc_udp_min_port == static_cast<uint16_t>(min) &&
prefs->webrtc_udp_max_port == static_cast<uint16_t>(max)) {
return;
}
prefs->webrtc_udp_min_port = min;
prefs->webrtc_udp_max_port = max;
web_contents()->SyncRendererPrefs();
}
std::string WebContents::GetMediaSourceID(
content::WebContents* request_web_contents) {
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host)
return std::string();
content::DesktopMediaID media_id(
content::DesktopMediaID::TYPE_WEB_CONTENTS,
content::DesktopMediaID::kNullId,
content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(),
frame_host->GetRoutingID()));
auto* request_frame_host = request_web_contents->GetPrimaryMainFrame();
if (!request_frame_host)
return std::string();
std::string id =
content::DesktopStreamsRegistry::GetInstance()->RegisterStream(
request_frame_host->GetProcess()->GetID(),
request_frame_host->GetRoutingID(),
url::Origin::Create(request_frame_host->GetLastCommittedURL()
.DeprecatedGetOriginAsURL()),
media_id, content::kRegistryStreamTypeTab);
return id;
}
bool WebContents::IsCrashed() const {
return web_contents()->IsCrashed();
}
void WebContents::ForcefullyCrashRenderer() {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
if (!rwh)
return;
content::RenderProcessHost* rph = rwh->GetProcess();
if (rph) {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// A generic |CrashDumpHungChildProcess()| is not implemented for Linux.
// Instead we send an explicit IPC to crash on the renderer's IO thread.
rph->ForceCrash();
#else
// Try to generate a crash report for the hung process.
#if !IS_MAS_BUILD()
CrashDumpHungChildProcess(rph->GetProcess().Handle());
#endif
rph->Shutdown(content::RESULT_CODE_HUNG);
#endif
}
}
void WebContents::SetUserAgent(const std::string& user_agent) {
blink::UserAgentOverride ua_override;
ua_override.ua_string_override = user_agent;
if (!user_agent.empty())
ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata();
web_contents()->SetUserAgentOverride(ua_override, false);
}
std::string WebContents::GetUserAgent() {
return web_contents()->GetUserAgentOverride().ua_string_override;
}
v8::Local<v8::Promise> WebContents::SavePage(
const base::FilePath& full_file_path,
const content::SavePageType& save_type) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!full_file_path.IsAbsolute()) {
promise.RejectWithErrorMessage("Path must be absolute");
return handle;
}
auto* handler = new SavePageHandler(web_contents(), std::move(promise));
handler->Handle(full_file_path, save_type);
return handle;
}
void WebContents::OpenDevTools(gin::Arguments* args) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
std::string state;
if (type_ == Type::kWebView || type_ == Type::kBackgroundPage ||
!owner_window()) {
state = "detach";
}
bool activate = true;
std::string title;
if (args && args->Length() == 1) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("mode", &state);
options.Get("activate", &activate);
options.Get("title", &title);
}
}
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->SetDockState(state);
inspectable_web_contents_->SetDevToolsTitle(base::UTF8ToUTF16(title));
inspectable_web_contents_->ShowDevTools(activate);
}
void WebContents::CloseDevTools() {
if (type_ == Type::kRemote)
return;
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->CloseDevTools();
}
bool WebContents::IsDevToolsOpened() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->IsDevToolsViewShowing();
}
std::u16string WebContents::GetDevToolsTitle() {
if (type_ == Type::kRemote)
return std::u16string();
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->GetDevToolsTitle();
}
void WebContents::SetDevToolsTitle(const std::u16string& title) {
inspectable_web_contents_->SetDevToolsTitle(title);
}
bool WebContents::IsDevToolsFocused() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->GetView()->IsDevToolsViewFocused();
}
void WebContents::EnableDeviceEmulation(
const blink::DeviceEmulationParams& params) {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->EnableDeviceEmulation(params);
}
}
}
void WebContents::DisableDeviceEmulation() {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->DisableDeviceEmulation();
}
}
}
void WebContents::ToggleDevTools() {
if (IsDevToolsOpened())
CloseDevTools();
else
OpenDevTools(nullptr);
}
void WebContents::InspectElement(int x, int y) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
DCHECK(inspectable_web_contents_);
if (!inspectable_web_contents_->GetDevToolsWebContents())
OpenDevTools(nullptr);
inspectable_web_contents_->InspectElement(x, y);
}
void WebContents::InspectSharedWorkerById(const std::string& workerId) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
if (agent_host->GetId() == workerId) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
}
std::vector<scoped_refptr<content::DevToolsAgentHost>>
WebContents::GetAllSharedWorkers() {
std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers;
if (type_ == Type::kRemote)
return shared_workers;
if (!enable_devtools_)
return shared_workers;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
shared_workers.push_back(agent_host);
}
}
return shared_workers;
}
void WebContents::InspectSharedWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::InspectServiceWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeServiceWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::SetIgnoreMenuShortcuts(bool ignore) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
DCHECK(web_preferences);
web_preferences->SetIgnoreMenuShortcuts(ignore);
}
void WebContents::SetAudioMuted(bool muted) {
web_contents()->SetAudioMuted(muted);
}
bool WebContents::IsAudioMuted() {
return web_contents()->IsAudioMuted();
}
bool WebContents::IsCurrentlyAudible() {
return web_contents()->IsCurrentlyAudible();
}
#if BUILDFLAG(ENABLE_PRINTING)
void WebContents::OnGetDeviceNameToUse(
base::Value::Dict print_settings,
printing::CompletionCallback print_callback,
bool silent,
// <error, device_name>
std::pair<std::string, std::u16string> info) {
// The content::WebContents might be already deleted at this point, and the
// PrintViewManagerElectron class does not do null check.
if (!web_contents()) {
if (print_callback)
std::move(print_callback).Run(false, "failed");
return;
}
if (!info.first.empty()) {
if (print_callback)
std::move(print_callback).Run(false, info.first);
return;
}
// If the user has passed a deviceName use it, otherwise use default printer.
print_settings.Set(printing::kSettingDeviceName, info.second);
auto* print_view_manager =
PrintViewManagerElectron::FromWebContents(web_contents());
if (!print_view_manager)
return;
auto* focused_frame = web_contents()->GetFocusedFrame();
auto* rfh = focused_frame && focused_frame->HasSelection()
? focused_frame
: web_contents()->GetPrimaryMainFrame();
print_view_manager->PrintNow(rfh, silent, std::move(print_settings),
std::move(print_callback));
}
void WebContents::Print(gin::Arguments* args) {
auto options = gin_helper::Dictionary::CreateEmpty(args->isolate());
base::Value::Dict settings;
if (args->Length() >= 1 && !args->GetNext(&options)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid print settings specified.");
return;
}
printing::CompletionCallback callback;
if (args->Length() == 2 && !args->GetNext(&callback)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid optional callback provided.");
return;
}
// Set optional silent printing
bool silent = false;
options.Get("silent", &silent);
bool print_background = false;
options.Get("printBackground", &print_background);
settings.Set(printing::kSettingShouldPrintBackgrounds, print_background);
// Set custom margin settings
auto margins = gin_helper::Dictionary::CreateEmpty(args->isolate());
if (options.Get("margins", &margins)) {
printing::mojom::MarginType margin_type =
printing::mojom::MarginType::kDefaultMargins;
margins.Get("marginType", &margin_type);
settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type));
if (margin_type == printing::mojom::MarginType::kCustomMargins) {
base::Value::Dict custom_margins;
int top = 0;
margins.Get("top", &top);
custom_margins.Set(printing::kSettingMarginTop, top);
int bottom = 0;
margins.Get("bottom", &bottom);
custom_margins.Set(printing::kSettingMarginBottom, bottom);
int left = 0;
margins.Get("left", &left);
custom_margins.Set(printing::kSettingMarginLeft, left);
int right = 0;
margins.Get("right", &right);
custom_margins.Set(printing::kSettingMarginRight, right);
settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins));
}
} else {
settings.Set(
printing::kSettingMarginsType,
static_cast<int>(printing::mojom::MarginType::kDefaultMargins));
}
// Set whether to print color or greyscale
bool print_color = true;
options.Get("color", &print_color);
auto const color_model = print_color ? printing::mojom::ColorModel::kColor
: printing::mojom::ColorModel::kGray;
settings.Set(printing::kSettingColor, static_cast<int>(color_model));
// Is the orientation landscape or portrait.
bool landscape = false;
options.Get("landscape", &landscape);
settings.Set(printing::kSettingLandscape, landscape);
// We set the default to the system's default printer and only update
// if at the Chromium level if the user overrides.
// Printer device name as opened by the OS.
std::u16string device_name;
options.Get("deviceName", &device_name);
int scale_factor = 100;
options.Get("scaleFactor", &scale_factor);
settings.Set(printing::kSettingScaleFactor, scale_factor);
int pages_per_sheet = 1;
options.Get("pagesPerSheet", &pages_per_sheet);
settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet);
// True if the user wants to print with collate.
bool collate = true;
options.Get("collate", &collate);
settings.Set(printing::kSettingCollate, collate);
// The number of individual copies to print
int copies = 1;
options.Get("copies", &copies);
settings.Set(printing::kSettingCopies, copies);
// Strings to be printed as headers and footers if requested by the user.
std::string header;
options.Get("header", &header);
std::string footer;
options.Get("footer", &footer);
if (!(header.empty() && footer.empty())) {
settings.Set(printing::kSettingHeaderFooterEnabled, true);
settings.Set(printing::kSettingHeaderFooterTitle, header);
settings.Set(printing::kSettingHeaderFooterURL, footer);
} else {
settings.Set(printing::kSettingHeaderFooterEnabled, false);
}
// We don't want to allow the user to enable these settings
// but we need to set them or a CHECK is hit.
settings.Set(printing::kSettingPrinterType,
static_cast<int>(printing::mojom::PrinterType::kLocal));
settings.Set(printing::kSettingShouldPrintSelectionOnly, false);
settings.Set(printing::kSettingRasterizePdf, false);
// Set custom page ranges to print
std::vector<gin_helper::Dictionary> page_ranges;
if (options.Get("pageRanges", &page_ranges)) {
base::Value::List page_range_list;
for (auto& range : page_ranges) {
int from, to;
if (range.Get("from", &from) && range.Get("to", &to)) {
base::Value::Dict range_dict;
// Chromium uses 1-based page ranges, so increment each by 1.
range_dict.Set(printing::kSettingPageRangeFrom, from + 1);
range_dict.Set(printing::kSettingPageRangeTo, to + 1);
page_range_list.Append(std::move(range_dict));
} else {
continue;
}
}
if (!page_range_list.empty())
settings.Set(printing::kSettingPageRange, std::move(page_range_list));
}
// Duplex type user wants to use.
printing::mojom::DuplexMode duplex_mode =
printing::mojom::DuplexMode::kSimplex;
options.Get("duplexMode", &duplex_mode);
settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode));
// We've already done necessary parameter sanitization at the
// JS level, so we can simply pass this through.
base::Value media_size(base::Value::Type::DICT);
if (options.Get("mediaSize", &media_size))
settings.Set(printing::kSettingMediaSize, std::move(media_size));
// Set custom dots per inch (dpi)
gin_helper::Dictionary dpi_settings;
int dpi = 72;
if (options.Get("dpi", &dpi_settings)) {
int horizontal = 72;
dpi_settings.Get("horizontal", &horizontal);
settings.Set(printing::kSettingDpiHorizontal, horizontal);
int vertical = 72;
dpi_settings.Get("vertical", &vertical);
settings.Set(printing::kSettingDpiVertical, vertical);
} else {
settings.Set(printing::kSettingDpiHorizontal, dpi);
settings.Set(printing::kSettingDpiVertical, dpi);
}
print_task_runner_->PostTaskAndReplyWithResult(
FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name),
base::BindOnce(&WebContents::OnGetDeviceNameToUse,
weak_factory_.GetWeakPtr(), std::move(settings),
std::move(callback), silent));
}
// Partially duplicated and modified from
// headless/lib/browser/protocol/page_handler.cc;l=41
v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
// This allows us to track headless printing calls.
auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID);
auto landscape = settings.GetDict().FindBool("landscape");
auto display_header_footer =
settings.GetDict().FindBool("displayHeaderFooter");
auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds");
auto scale = settings.GetDict().FindDouble("scale");
auto paper_width = settings.GetDict().FindDouble("paperWidth");
auto paper_height = settings.GetDict().FindDouble("paperHeight");
auto margin_top = settings.GetDict().FindDouble("marginTop");
auto margin_bottom = settings.GetDict().FindDouble("marginBottom");
auto margin_left = settings.GetDict().FindDouble("marginLeft");
auto margin_right = settings.GetDict().FindDouble("marginRight");
auto page_ranges = *settings.GetDict().FindString("pageRanges");
auto header_template = *settings.GetDict().FindString("headerTemplate");
auto footer_template = *settings.GetDict().FindString("footerTemplate");
auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize");
auto generate_tagged_pdf = settings.GetDict().FindBool("generateTaggedPDF");
absl::variant<printing::mojom::PrintPagesParamsPtr, std::string>
print_pages_params = print_to_pdf::GetPrintPagesParams(
web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(),
landscape, display_header_footer, print_background, scale,
paper_width, paper_height, margin_top, margin_bottom, margin_left,
margin_right, absl::make_optional(header_template),
absl::make_optional(footer_template), prefer_css_page_size,
generate_tagged_pdf);
if (absl::holds_alternative<std::string>(print_pages_params)) {
auto error = absl::get<std::string>(print_pages_params);
promise.RejectWithErrorMessage("Invalid print parameters: " + error);
return handle;
}
auto* manager = PrintViewManagerElectron::FromWebContents(web_contents());
if (!manager) {
promise.RejectWithErrorMessage("Failed to find print manager");
return handle;
}
auto params = std::move(
absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params));
params->params->document_cookie = unique_id.value_or(0);
manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges,
std::move(params),
base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(),
std::move(promise)));
return handle;
}
void WebContents::OnPDFCreated(
gin_helper::Promise<v8::Local<v8::Value>> promise,
print_to_pdf::PdfPrintResult print_result,
scoped_refptr<base::RefCountedMemory> data) {
if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) {
promise.RejectWithErrorMessage(
"Failed to generate PDF: " +
print_to_pdf::PdfPrintResultToString(print_result));
return;
}
v8::Isolate* isolate = promise.isolate();
gin_helper::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate, promise.GetContext()));
v8::Local<v8::Value> buffer =
node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()),
data->size())
.ToLocalChecked();
promise.Resolve(buffer);
}
#endif
void WebContents::AddWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsAddFileSystem(std::string(), path);
}
void WebContents::RemoveWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsRemoveFileSystem(path);
}
void WebContents::Undo() {
web_contents()->Undo();
}
void WebContents::Redo() {
web_contents()->Redo();
}
void WebContents::Cut() {
web_contents()->Cut();
}
void WebContents::Copy() {
web_contents()->Copy();
}
void WebContents::CenterSelection() {
web_contents()->CenterSelection();
}
void WebContents::Paste() {
web_contents()->Paste();
}
void WebContents::PasteAndMatchStyle() {
web_contents()->PasteAndMatchStyle();
}
void WebContents::Delete() {
web_contents()->Delete();
}
void WebContents::SelectAll() {
web_contents()->SelectAll();
}
void WebContents::Unselect() {
web_contents()->CollapseSelection();
}
void WebContents::ScrollToTopOfDocument() {
web_contents()->ScrollToTopOfDocument();
}
void WebContents::ScrollToBottomOfDocument() {
web_contents()->ScrollToBottomOfDocument();
}
void WebContents::AdjustSelectionByCharacterOffset(gin::Arguments* args) {
int start_adjust = 0;
int end_adjust = 0;
gin_helper::Dictionary dict;
if (args->GetNext(&dict)) {
dict.Get("start", &start_adjust);
dict.Get("matchCase", &end_adjust);
}
// The selection menu is a Chrome-specific piece of UI.
// TODO(codebytere): maybe surface as an event in the future?
web_contents()->AdjustSelectionByCharacterOffset(
start_adjust, end_adjust, false /* show_selection_menu */);
}
void WebContents::Replace(const std::u16string& word) {
web_contents()->Replace(word);
}
void WebContents::ReplaceMisspelling(const std::u16string& word) {
web_contents()->ReplaceMisspelling(word);
}
uint32_t WebContents::FindInPage(gin::Arguments* args) {
std::u16string search_text;
if (!args->GetNext(&search_text) || search_text.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must provide a non-empty search content");
return 0;
}
uint32_t request_id = ++find_in_page_request_id_;
gin_helper::Dictionary dict;
auto options = blink::mojom::FindOptions::New();
if (args->GetNext(&dict)) {
dict.Get("forward", &options->forward);
dict.Get("matchCase", &options->match_case);
dict.Get("findNext", &options->new_session);
}
web_contents()->Find(request_id, search_text, std::move(options));
return request_id;
}
void WebContents::StopFindInPage(content::StopFindAction action) {
web_contents()->StopFinding(action);
}
void WebContents::ShowDefinitionForSelection() {
#if BUILDFLAG(IS_MAC)
auto* const view = web_contents()->GetRenderWidgetHostView();
if (view)
view->ShowDefinitionForSelection();
#endif
}
void WebContents::CopyImageAt(int x, int y) {
auto* const host = web_contents()->GetPrimaryMainFrame();
if (host)
host->CopyImageAt(x, y);
}
void WebContents::Focus() {
// Focusing on WebContents does not automatically focus the window on macOS
// and Linux, do it manually to match the behavior on Windows.
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
if (owner_window())
owner_window()->Focus(true);
#endif
web_contents()->Focus();
}
#if !BUILDFLAG(IS_MAC)
bool WebContents::IsFocused() const {
auto* view = web_contents()->GetRenderWidgetHostView();
if (!view)
return false;
if (GetType() != Type::kBackgroundPage) {
auto* window = web_contents()->GetNativeView()->GetToplevelWindow();
if (window && !window->IsVisible())
return false;
}
return view->HasFocus();
}
#endif
void WebContents::SendInputEvent(v8::Isolate* isolate,
v8::Local<v8::Value> input_event) {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
blink::WebInputEvent::Type type =
gin::GetWebInputEventType(isolate, input_event);
if (blink::WebInputEvent::IsMouseEventType(type)) {
blink::WebMouseEvent mouse_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) {
if (IsOffScreen()) {
GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event);
} else {
rwh->ForwardMouseEvent(mouse_event);
}
return;
}
} else if (blink::WebInputEvent::IsKeyboardEventType(type)) {
content::NativeWebKeyboardEvent keyboard_event(
blink::WebKeyboardEvent::Type::kRawKeyDown,
blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow());
if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) {
// For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`.
if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown)
keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown);
rwh->ForwardKeyboardEvent(keyboard_event);
return;
}
} else if (type == blink::WebInputEvent::Type::kMouseWheel) {
blink::WebMouseWheelEvent mouse_wheel_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
if (IsOffScreen()) {
GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent(
mouse_wheel_event);
} else {
// Chromium expects phase info in wheel events (and applies a
// DCHECK to verify it). See: https://crbug.com/756524.
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
// Send a synthetic wheel event with phaseEnded to finish scrolling.
mouse_wheel_event.has_synthetic_phase = true;
mouse_wheel_event.delta_x = 0;
mouse_wheel_event.delta_y = 0;
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kEventNonBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
}
return;
}
}
isolate->ThrowException(
v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object")));
}
void WebContents::BeginFrameSubscription(gin::Arguments* args) {
bool only_dirty = false;
FrameSubscriber::FrameCaptureCallback callback;
if (args->Length() > 1) {
if (!args->GetNext(&only_dirty)) {
args->ThrowError();
return;
}
}
if (!args->GetNext(&callback)) {
args->ThrowError();
return;
}
frame_subscriber_ =
std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty);
}
void WebContents::EndFrameSubscription() {
frame_subscriber_.reset();
}
void WebContents::StartDrag(const gin_helper::Dictionary& item,
gin::Arguments* args) {
base::FilePath file;
std::vector<base::FilePath> files;
if (!item.Get("files", &files) && item.Get("file", &file)) {
files.push_back(file);
}
v8::Local<v8::Value> icon_value;
if (!item.Get("icon", &icon_value)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'icon' parameter is required");
return;
}
NativeImage* icon = nullptr;
if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) ||
icon->image().IsEmpty()) {
return;
}
// Start dragging.
if (!files.empty()) {
base::CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop allow;
DragFileItems(files, icon->image(), web_contents()->GetNativeView());
} else {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must specify either 'file' or 'files' option");
}
}
v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) {
gin_helper::Promise<gfx::Image> promise(args->isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
gfx::Rect rect;
args->GetNext(&rect);
bool stay_hidden = false;
bool stay_awake = false;
if (args && args->Length() == 2) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("stayHidden", &stay_hidden);
options.Get("stayAwake", &stay_awake);
}
}
auto* const view = web_contents()->GetRenderWidgetHostView();
if (!view || view->GetViewBounds().size().IsEmpty()) {
promise.Resolve(gfx::Image());
return handle;
}
if (!view->IsSurfaceAvailableForCopy()) {
promise.RejectWithErrorMessage(
"Current display surface not available for capture");
return handle;
}
auto capture_handle = web_contents()->IncrementCapturerCount(
rect.size(), stay_hidden, stay_awake);
// Capture full page if user doesn't specify a |rect|.
const gfx::Size view_size =
rect.IsEmpty() ? view->GetViewBounds().size() : rect.size();
// By default, the requested bitmap size is the view size in screen
// coordinates. However, if there's more pixel detail available on the
// current system, increase the requested bitmap size to capture it all.
gfx::Size bitmap_size = view_size;
const gfx::NativeView native_view = view->GetNativeView();
const float scale = display::Screen::GetScreen()
->GetDisplayNearestView(native_view)
.device_scale_factor();
if (scale > 1.0f)
bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size,
base::BindOnce(&OnCapturePageDone, std::move(promise),
std::move(capture_handle)));
return handle;
}
bool WebContents::IsBeingCaptured() {
return web_contents()->IsBeingCaptured();
}
void WebContents::OnCursorChanged(const ui::Cursor& cursor) {
if (cursor.type() == ui::mojom::CursorType::kCustom) {
Emit("cursor-changed", CursorTypeToString(cursor.type()),
gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()),
cursor.image_scale_factor(),
gfx::Size(cursor.custom_bitmap().width(),
cursor.custom_bitmap().height()),
cursor.custom_hotspot());
} else {
Emit("cursor-changed", CursorTypeToString(cursor.type()));
}
}
bool WebContents::IsGuest() const {
return type_ == Type::kWebView;
}
void WebContents::AttachToIframe(content::WebContents* embedder_web_contents,
int embedder_frame_id) {
attached_ = true;
if (guest_delegate_)
guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id);
}
bool WebContents::IsOffScreen() const {
return type_ == Type::kOffScreen;
}
void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap));
}
void WebContents::StartPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(true);
}
void WebContents::StopPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(false);
}
bool WebContents::IsPainting() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv && osr_wcv->IsPainting();
}
void WebContents::SetFrameRate(int frame_rate) {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetFrameRate(frame_rate);
}
int WebContents::GetFrameRate() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv ? osr_wcv->GetFrameRate() : 0;
}
void WebContents::Invalidate() {
if (IsOffScreen()) {
auto* osr_rwhv = GetOffScreenRenderWidgetHostView();
if (osr_rwhv)
osr_rwhv->Invalidate();
} else {
auto* const window = owner_window();
if (window)
window->Invalidate();
}
}
gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) {
if (IsOffScreen() && wc == web_contents()) {
auto* relay = NativeWindowRelay::FromWebContents(web_contents());
if (relay) {
auto* owner_window = relay->GetNativeWindow();
return owner_window ? owner_window->GetSize() : gfx::Size();
}
}
return gfx::Size();
}
void WebContents::SetZoomLevel(double level) {
zoom_controller_->SetZoomLevel(level);
}
double WebContents::GetZoomLevel() const {
return zoom_controller_->GetZoomLevel();
}
void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower,
double factor) {
if (factor < std::numeric_limits<double>::epsilon()) {
thrower.ThrowError("'zoomFactor' must be a double greater than 0.0");
return;
}
auto level = blink::PageZoomFactorToZoomLevel(factor);
SetZoomLevel(level);
}
double WebContents::GetZoomFactor() const {
auto level = GetZoomLevel();
return blink::PageZoomLevelToZoomFactor(level);
}
void WebContents::SetTemporaryZoomLevel(double level) {
zoom_controller_->SetTemporaryZoomLevel(level);
}
void WebContents::DoGetZoomLevel(
electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback
callback) {
std::move(callback).Run(GetZoomLevel());
}
std::vector<base::FilePath> WebContents::GetPreloadPaths() const {
auto result = SessionPreferences::GetValidPreloads(GetBrowserContext());
if (auto* web_preferences = WebContentsPreferences::From(web_contents())) {
base::FilePath preload;
if (web_preferences->GetPreloadPath(&preload)) {
result.emplace_back(preload);
}
}
return result;
}
v8::Local<v8::Value> WebContents::GetLastWebPreferences(
v8::Isolate* isolate) const {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (!web_preferences)
return v8::Null(isolate);
return gin::ConvertToV8(isolate, *web_preferences->last_preference());
}
v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow(
v8::Isolate* isolate) const {
if (owner_window())
return BrowserWindow::From(isolate, owner_window());
else
return v8::Null(isolate);
}
v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
return v8::Local<v8::Value>::New(isolate, session_);
}
content::WebContents* WebContents::HostWebContents() const {
if (!embedder_)
return nullptr;
return embedder_->web_contents();
}
void WebContents::SetEmbedder(const WebContents* embedder) {
if (embedder) {
NativeWindow* owner_window = nullptr;
auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
if (relay) {
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
content::RenderWidgetHostView* rwhv =
web_contents()->GetRenderWidgetHostView();
if (rwhv) {
rwhv->Hide();
rwhv->Show();
}
}
}
void WebContents::SetDevToolsWebContents(const WebContents* devtools) {
if (inspectable_web_contents_)
inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents());
}
v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const {
gfx::NativeView ptr = web_contents()->GetNativeView();
auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr),
sizeof(gfx::NativeView));
if (buffer.IsEmpty())
return v8::Null(isolate);
else
return buffer.ToLocalChecked();
}
v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
if (devtools_web_contents_.IsEmpty())
return v8::Null(isolate);
else
return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
}
v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
if (debugger_.IsEmpty()) {
auto handle = electron::api::Debugger::Create(isolate, web_contents());
debugger_.Reset(isolate, handle.ToV8());
}
return v8::Local<v8::Value>::New(isolate, debugger_);
}
content::RenderFrameHost* WebContents::MainFrame() {
return web_contents()->GetPrimaryMainFrame();
}
content::RenderFrameHost* WebContents::Opener() {
return web_contents()->GetOpener();
}
void WebContents::NotifyUserActivation() {
content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame();
if (frame)
frame->NotifyUserActivation(
blink::mojom::UserActivationNotificationType::kInteraction);
}
void WebContents::SetImageAnimationPolicy(const std::string& new_policy) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
web_preferences->SetImageAnimationPolicy(new_policy);
web_contents()->OnWebPreferencesChanged();
}
void WebContents::OnInputEvent(const blink::WebInputEvent& event) {
Emit("input-event", event);
}
v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage("Failed to create memory dump");
return handle;
}
auto pid = frame_host->GetProcess()->GetProcess().Pid();
v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext());
memory_instrumentation::MemoryInstrumentation::GetInstance()
->RequestGlobalDumpForPid(
pid, std::vector<std::string>(),
base::BindOnce(&ElectronBindings::DidReceiveMemoryDump,
std::move(context), std::move(promise), pid));
return handle;
}
v8::Local<v8::Promise> WebContents::TakeHeapSnapshot(
v8::Isolate* isolate,
const base::FilePath& file_path) {
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
ScopedAllowBlockingForElectron allow_blocking;
uint32_t flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE;
// The snapshot file is passed to an untrusted process.
flags = base::File::AddFlagsForPassingToUntrustedProcess(flags);
base::File file(file_path, flags);
if (!file.IsValid()) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with invalid file path " +
#if BUILDFLAG(IS_WIN)
base::WideToUTF8(file_path.value()));
#else
file_path.value());
#endif
return handle;
}
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with invalid webContents main frame");
return handle;
}
if (!frame_host->IsRenderFrameLive()) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with nonexistent render frame");
return handle;
}
// This dance with `base::Owned` is to ensure that the interface stays alive
// until the callback is called. Otherwise it would be closed at the end of
// this function.
auto electron_renderer =
std::make_unique<mojo::Remote<mojom::ElectronRenderer>>();
frame_host->GetRemoteInterfaces()->GetInterface(
electron_renderer->BindNewPipeAndPassReceiver());
auto* raw_ptr = electron_renderer.get();
(*raw_ptr)->TakeHeapSnapshot(
mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())),
base::BindOnce(
[](mojo::Remote<mojom::ElectronRenderer>* ep,
gin_helper::Promise<void> promise, bool success) {
if (success) {
promise.Resolve();
} else {
promise.RejectWithErrorMessage("Failed to take heap snapshot");
}
},
base::Owned(std::move(electron_renderer)), std::move(promise)));
return handle;
}
void WebContents::UpdatePreferredSize(content::WebContents* web_contents,
const gfx::Size& pref_size) {
Emit("preferred-size-changed", pref_size);
}
bool WebContents::CanOverscrollContent() {
return false;
}
std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper(
content::RenderFrameHost* frame,
content::EyeDropperListener* listener) {
return ShowEyeDropper(frame, listener);
}
void WebContents::RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) {
FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener),
params);
}
void WebContents::EnumerateDirectory(
content::WebContents* web_contents,
scoped_refptr<content::FileSelectListener> listener,
const base::FilePath& path) {
FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path);
}
bool WebContents::IsFullscreenForTabOrPending(
const content::WebContents* source) {
if (!owner_window())
return is_html_fullscreen();
bool in_transition = owner_window()->fullscreen_transition_state() !=
NativeWindow::FullScreenTransitionState::kNone;
bool is_html_transition = owner_window()->fullscreen_transition_type() ==
NativeWindow::FullScreenTransitionType::kHTML;
return is_html_fullscreen() || (in_transition && is_html_transition);
}
content::FullscreenState WebContents::GetFullscreenState(
const content::WebContents* source) const {
// `const_cast` here because EAM does not have const getters
return const_cast<ExclusiveAccessManager*>(&exclusive_access_manager_)
->fullscreen_controller()
->GetFullscreenState(source);
}
bool WebContents::TakeFocus(content::WebContents* source, bool reverse) {
if (source && source->GetOutermostWebContents() == source) {
// If this is the outermost web contents and the user has tabbed or
// shift + tabbed through all the elements, reset the focus back to
// the first or last element so that it doesn't stay in the body.
source->FocusThroughTabTraversal(reverse);
return true;
}
return false;
}
content::PictureInPictureResult WebContents::EnterPictureInPicture(
content::WebContents* web_contents) {
return PictureInPictureWindowManager::GetInstance()
->EnterVideoPictureInPicture(web_contents);
}
void WebContents::ExitPictureInPicture() {
PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture();
}
void WebContents::DevToolsSaveToFile(const std::string& url,
const std::string& content,
bool save_as) {
base::FilePath path;
auto it = saved_files_.find(url);
if (it != saved_files_.end() && !save_as) {
path = it->second;
} else {
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.title = url;
settings.default_path = base::FilePath::FromUTF8Unsafe(url);
if (!file_dialog::ShowSaveDialogSync(settings, &path)) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "canceledSaveURL", base::Value(url));
return;
}
}
saved_files_[url] = path;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "savedURL", base::Value(url),
base::Value(path.AsUTF8Unsafe()));
file_task_runner_->PostTask(FROM_HERE,
base::BindOnce(&WriteToFile, path, content));
}
void WebContents::DevToolsAppendToFile(const std::string& url,
const std::string& content) {
auto it = saved_files_.find(url);
if (it == saved_files_.end())
return;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL",
base::Value(url));
file_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&AppendToFile, it->second, content));
}
void WebContents::DevToolsRequestFileSystems() {
auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents());
if (file_system_paths.empty()) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List()));
return;
}
std::vector<FileSystem> file_systems;
for (const auto& file_system_path : file_system_paths) {
base::FilePath path =
base::FilePath::FromUTF8Unsafe(file_system_path.first);
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
FileSystem file_system =
CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id,
file_system_path.first, file_system_path.second);
file_systems.push_back(file_system);
}
base::Value::List file_system_value;
for (const auto& file_system : file_systems)
file_system_value.Append(CreateFileSystemValue(file_system));
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded",
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsAddFileSystem(
const std::string& type,
const base::FilePath& file_system_path) {
base::FilePath path = file_system_path;
if (path.empty()) {
std::vector<base::FilePath> paths;
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY;
if (!file_dialog::ShowOpenDialogSync(settings, &paths))
return;
path = paths[0];
}
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe()))
return;
FileSystem file_system = CreateFileSystemStruct(
GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type);
base::Value::Dict file_system_value = CreateFileSystemValue(file_system);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Set(path.AsUTF8Unsafe(), type);
std::string error = ""; // No error
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemAdded", base::Value(error),
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsRemoveFileSystem(
const base::FilePath& file_system_path) {
if (!inspectable_web_contents_)
return;
std::string path = file_system_path.AsUTF8Unsafe();
storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath(
file_system_path);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Remove(path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemRemoved", base::Value(path));
}
void WebContents::DevToolsIndexPath(
int request_id,
const std::string& file_system_path,
const std::string& excluded_folders_message) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsIndexingDone(request_id, file_system_path);
return;
}
if (devtools_indexing_jobs_.count(request_id) != 0)
return;
std::vector<std::string> excluded_folders;
absl::optional<base::Value> parsed_excluded_folders =
base::JSONReader::Read(excluded_folders_message);
if (parsed_excluded_folders && parsed_excluded_folders->is_list()) {
for (const base::Value& folder_path : parsed_excluded_folders->GetList()) {
if (folder_path.is_string())
excluded_folders.push_back(folder_path.GetString());
}
}
devtools_indexing_jobs_[request_id] =
scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>(
devtools_file_system_indexer_->IndexPath(
file_system_path, excluded_folders,
base::BindRepeating(
&WebContents::OnDevToolsIndexingWorkCalculated,
weak_factory_.GetWeakPtr(), request_id, file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingWorked,
weak_factory_.GetWeakPtr(), request_id,
file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingDone,
weak_factory_.GetWeakPtr(), request_id,
file_system_path)));
}
void WebContents::DevToolsStopIndexing(int request_id) {
auto it = devtools_indexing_jobs_.find(request_id);
if (it == devtools_indexing_jobs_.end())
return;
it->second->Stop();
devtools_indexing_jobs_.erase(it);
}
void WebContents::DevToolsOpenInNewTab(const std::string& url) {
Emit("devtools-open-url", url);
}
void WebContents::DevToolsSearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsSearchCompleted(request_id, file_system_path,
std::vector<std::string>());
return;
}
devtools_file_system_indexer_->SearchInPath(
file_system_path, query,
base::BindRepeating(&WebContents::OnDevToolsSearchCompleted,
weak_factory_.GetWeakPtr(), request_id,
file_system_path));
}
void WebContents::DevToolsSetEyeDropperActive(bool active) {
auto* web_contents = GetWebContents();
if (!web_contents)
return;
if (active) {
eye_dropper_ = std::make_unique<DevToolsEyeDropper>(
web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper,
base::Unretained(this)));
} else {
eye_dropper_.reset();
}
}
void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) {
base::Value::Dict color;
color.Set("r", r);
color.Set("g", g);
color.Set("b", b);
color.Set("a", a);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color)));
}
#if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
ui::ImageModel WebContents::GetDevToolsWindowIcon() {
return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{};
}
#endif
#if BUILDFLAG(IS_LINUX)
void WebContents::GetDevToolsWindowWMClass(std::string* name,
std::string* class_name) {
*class_name = Browser::Get()->GetName();
*name = base::ToLowerASCII(*class_name);
}
#endif
void WebContents::OnDevToolsIndexingWorkCalculated(
int request_id,
const std::string& file_system_path,
int total_work) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id),
base::Value(file_system_path), base::Value(total_work));
}
void WebContents::OnDevToolsIndexingWorked(int request_id,
const std::string& file_system_path,
int worked) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingWorked", base::Value(request_id),
base::Value(file_system_path), base::Value(worked));
}
void WebContents::OnDevToolsIndexingDone(int request_id,
const std::string& file_system_path) {
devtools_indexing_jobs_.erase(request_id);
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone",
base::Value(request_id),
base::Value(file_system_path));
}
void WebContents::OnDevToolsSearchCompleted(
int request_id,
const std::string& file_system_path,
const std::vector<std::string>& file_paths) {
base::Value::List file_paths_value;
for (const auto& file_path : file_paths)
file_paths_value.Append(file_path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "searchCompleted", base::Value(request_id),
base::Value(file_system_path), base::Value(std::move(file_paths_value)));
}
void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) {
// Window is already in fullscreen mode, save the state.
if (enter_fullscreen && owner_window()->IsFullscreen()) {
native_fullscreen_ = true;
UpdateHtmlApiFullscreen(true);
return;
}
// Exit html fullscreen state but not window's fullscreen mode.
if (!enter_fullscreen && native_fullscreen_) {
UpdateHtmlApiFullscreen(false);
return;
}
// Set fullscreen on window if allowed.
auto* web_preferences = WebContentsPreferences::From(GetWebContents());
bool html_fullscreenable =
web_preferences
? !web_preferences->ShouldDisableHtmlFullscreenWindowResize()
: true;
if (html_fullscreenable)
owner_window_->SetFullScreen(enter_fullscreen);
UpdateHtmlApiFullscreen(enter_fullscreen);
native_fullscreen_ = false;
}
void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) {
if (fullscreen == is_html_fullscreen())
return;
html_fullscreen_ = fullscreen;
// Notify renderer of the html fullscreen change.
web_contents()
->GetRenderViewHost()
->GetWidget()
->SynchronizeVisualProperties();
// The embedder WebContents is separated from the frame tree of webview, so
// we must manually sync their fullscreen states.
if (embedder_)
embedder_->SetHtmlApiFullscreen(fullscreen);
if (fullscreen) {
Emit("enter-html-full-screen");
owner_window_->NotifyWindowEnterHtmlFullScreen();
} else {
Emit("leave-html-full-screen");
owner_window_->NotifyWindowLeaveHtmlFullScreen();
}
// Make sure all child webviews quit html fullscreen.
if (!fullscreen && !IsGuest()) {
auto* manager = WebViewManager::GetWebViewManager(web_contents());
manager->ForEachGuest(
web_contents(), base::BindRepeating([](content::WebContents* guest) {
WebContents* api_web_contents = WebContents::From(guest);
api_web_contents->SetHtmlApiFullscreen(false);
return false;
}));
}
}
// static
void WebContents::FillObjectTemplate(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin::InvokerOptions options;
options.holder_is_first_argument = true;
options.holder_type = GetClassName();
templ->Set(
gin::StringToSymbol(isolate, "isDestroyed"),
gin::CreateFunctionTemplate(
isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed),
options));
// We use gin_helper::ObjectTemplateBuilder instead of
// gin::ObjectTemplateBuilder here to handle the fact that WebContents is
// destroyable.
gin_helper::ObjectTemplateBuilder(isolate, templ)
.SetMethod("destroy", &WebContents::Destroy)
.SetMethod("close", &WebContents::Close)
.SetMethod("getBackgroundThrottling",
&WebContents::GetBackgroundThrottling)
.SetMethod("setBackgroundThrottling",
&WebContents::SetBackgroundThrottling)
.SetMethod("getProcessId", &WebContents::GetProcessID)
.SetMethod("getOSProcessId", &WebContents::GetOSProcessID)
.SetMethod("equal", &WebContents::Equal)
.SetMethod("_loadURL", &WebContents::LoadURL)
.SetMethod("reload", &WebContents::Reload)
.SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache)
.SetMethod("downloadURL", &WebContents::DownloadURL)
.SetMethod("getURL", &WebContents::GetURL)
.SetMethod("getTitle", &WebContents::GetTitle)
.SetMethod("isLoading", &WebContents::IsLoading)
.SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
.SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
.SetMethod("stop", &WebContents::Stop)
.SetMethod("canGoBack", &WebContents::CanGoBack)
.SetMethod("goBack", &WebContents::GoBack)
.SetMethod("canGoForward", &WebContents::CanGoForward)
.SetMethod("goForward", &WebContents::GoForward)
.SetMethod("canGoToOffset", &WebContents::CanGoToOffset)
.SetMethod("goToOffset", &WebContents::GoToOffset)
.SetMethod("canGoToIndex", &WebContents::CanGoToIndex)
.SetMethod("goToIndex", &WebContents::GoToIndex)
.SetMethod("getActiveIndex", &WebContents::GetActiveIndex)
.SetMethod("clearHistory", &WebContents::ClearHistory)
.SetMethod("length", &WebContents::GetHistoryLength)
.SetMethod("isCrashed", &WebContents::IsCrashed)
.SetMethod("forcefullyCrashRenderer",
&WebContents::ForcefullyCrashRenderer)
.SetMethod("setUserAgent", &WebContents::SetUserAgent)
.SetMethod("getUserAgent", &WebContents::GetUserAgent)
.SetMethod("savePage", &WebContents::SavePage)
.SetMethod("openDevTools", &WebContents::OpenDevTools)
.SetMethod("closeDevTools", &WebContents::CloseDevTools)
.SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
.SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
.SetMethod("getDevToolsTitle", &WebContents::GetDevToolsTitle)
.SetMethod("setDevToolsTitle", &WebContents::SetDevToolsTitle)
.SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation)
.SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation)
.SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
.SetMethod("inspectElement", &WebContents::InspectElement)
.SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts)
.SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
.SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
.SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible)
.SetMethod("undo", &WebContents::Undo)
.SetMethod("redo", &WebContents::Redo)
.SetMethod("cut", &WebContents::Cut)
.SetMethod("copy", &WebContents::Copy)
.SetMethod("centerSelection", &WebContents::CenterSelection)
.SetMethod("paste", &WebContents::Paste)
.SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
.SetMethod("delete", &WebContents::Delete)
.SetMethod("selectAll", &WebContents::SelectAll)
.SetMethod("unselect", &WebContents::Unselect)
.SetMethod("scrollToTop", &WebContents::ScrollToTopOfDocument)
.SetMethod("scrollToBottom", &WebContents::ScrollToBottomOfDocument)
.SetMethod("adjustSelection",
&WebContents::AdjustSelectionByCharacterOffset)
.SetMethod("replace", &WebContents::Replace)
.SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
.SetMethod("findInPage", &WebContents::FindInPage)
.SetMethod("stopFindInPage", &WebContents::StopFindInPage)
.SetMethod("focus", &WebContents::Focus)
.SetMethod("isFocused", &WebContents::IsFocused)
.SetMethod("sendInputEvent", &WebContents::SendInputEvent)
.SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription)
.SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
.SetMethod("startDrag", &WebContents::StartDrag)
.SetMethod("attachToIframe", &WebContents::AttachToIframe)
.SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame)
.SetMethod("isOffscreen", &WebContents::IsOffScreen)
.SetMethod("startPainting", &WebContents::StartPainting)
.SetMethod("stopPainting", &WebContents::StopPainting)
.SetMethod("isPainting", &WebContents::IsPainting)
.SetMethod("setFrameRate", &WebContents::SetFrameRate)
.SetMethod("getFrameRate", &WebContents::GetFrameRate)
.SetMethod("invalidate", &WebContents::Invalidate)
.SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
.SetMethod("getZoomLevel", &WebContents::GetZoomLevel)
.SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
.SetMethod("getZoomFactor", &WebContents::GetZoomFactor)
.SetMethod("getType", &WebContents::GetType)
.SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths)
.SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences)
.SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
.SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
.SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker)
.SetMethod("inspectSharedWorkerById",
&WebContents::InspectSharedWorkerById)
.SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers)
#if BUILDFLAG(ENABLE_PRINTING)
.SetMethod("_print", &WebContents::Print)
.SetMethod("_printToPDF", &WebContents::PrintToPDF)
#endif
.SetMethod("_setNextChildWebPreferences",
&WebContents::SetNextChildWebPreferences)
.SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
.SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
.SetMethod("showDefinitionForSelection",
&WebContents::ShowDefinitionForSelection)
.SetMethod("copyImageAt", &WebContents::CopyImageAt)
.SetMethod("capturePage", &WebContents::CapturePage)
.SetMethod("setEmbedder", &WebContents::SetEmbedder)
.SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents)
.SetMethod("getNativeView", &WebContents::GetNativeView)
.SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured)
.SetMethod("setWebRTCIPHandlingPolicy",
&WebContents::SetWebRTCIPHandlingPolicy)
.SetMethod("setWebRTCUDPPortRange", &WebContents::SetWebRTCUDPPortRange)
.SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID)
.SetMethod("getWebRTCIPHandlingPolicy",
&WebContents::GetWebRTCIPHandlingPolicy)
.SetMethod("getWebRTCUDPPortRange", &WebContents::GetWebRTCUDPPortRange)
.SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot)
.SetMethod("setImageAnimationPolicy",
&WebContents::SetImageAnimationPolicy)
.SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo)
.SetProperty("id", &WebContents::ID)
.SetProperty("session", &WebContents::Session)
.SetProperty("hostWebContents", &WebContents::HostWebContents)
.SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
.SetProperty("debugger", &WebContents::Debugger)
.SetProperty("mainFrame", &WebContents::MainFrame)
.SetProperty("opener", &WebContents::Opener)
.Build();
}
const char* WebContents::GetTypeName() {
return GetClassName();
}
ElectronBrowserContext* WebContents::GetBrowserContext() const {
return static_cast<ElectronBrowserContext*>(
web_contents()->GetBrowserContext());
}
// static
gin::Handle<WebContents> WebContents::New(
v8::Isolate* isolate,
const gin_helper::Dictionary& options) {
gin::Handle<WebContents> handle =
gin::CreateHandle(isolate, new WebContents(isolate, options));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
gin::Handle<WebContents> WebContents::CreateAndTake(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type) {
gin::Handle<WebContents> handle = gin::CreateHandle(
isolate, new WebContents(isolate, std::move(web_contents), type));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
WebContents* WebContents::From(content::WebContents* web_contents) {
if (!web_contents)
return nullptr;
auto* data = static_cast<UserDataLink*>(
web_contents->GetUserData(kElectronApiWebContentsKey));
return data ? data->web_contents.get() : nullptr;
}
// static
gin::Handle<WebContents> WebContents::FromOrCreate(
v8::Isolate* isolate,
content::WebContents* web_contents) {
WebContents* api_web_contents = From(web_contents);
if (!api_web_contents) {
api_web_contents = new WebContents(isolate, web_contents);
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, api_web_contents, "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
}
return gin::CreateHandle(isolate, api_web_contents);
}
// static
gin::Handle<WebContents> WebContents::CreateFromWebPreferences(
v8::Isolate* isolate,
const gin_helper::Dictionary& web_preferences) {
// Check if webPreferences has |webContents| option.
gin::Handle<WebContents> web_contents;
if (web_preferences.GetHidden("webContents", &web_contents) &&
!web_contents.IsEmpty()) {
// Set webPreferences from options if using an existing webContents.
// These preferences will be used when the webContent launches new
// render processes.
auto* existing_preferences =
WebContentsPreferences::From(web_contents->web_contents());
gin_helper::Dictionary web_preferences_dict;
if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(),
&web_preferences_dict)) {
existing_preferences->SetFromDictionary(web_preferences_dict);
absl::optional<SkColor> color =
existing_preferences->GetBackgroundColor();
web_contents->web_contents()->SetPageBaseBackgroundColor(color);
// Because web preferences don't recognize transparency,
// only set rwhv background color if a color exists
auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView();
if (rwhv && color.has_value())
SetBackgroundColor(rwhv, color.value());
}
} else {
// Create one if not.
web_contents = WebContents::New(isolate, web_preferences);
}
return web_contents;
}
// static
WebContents* WebContents::FromID(int32_t id) {
return GetAllWebContents().Lookup(id);
}
// static
std::list<WebContents*> WebContents::GetWebContentsList() {
std::list<WebContents*> list;
for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
!iter.IsAtEnd(); iter.Advance()) {
list.push_back(iter.GetCurrentValue());
}
return list;
}
// static
gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin};
} // namespace electron::api
namespace {
using electron::api::GetAllWebContents;
using electron::api::WebContents;
using electron::api::WebFrameMain;
gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) {
WebContents* contents = WebContents::FromID(id);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromFrame(v8::Isolate* isolate,
WebFrameMain* web_frame) {
content::RenderFrameHost* rfh = web_frame->render_frame_host();
content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh);
WebContents* contents = WebContents::From(source);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromDevToolsTargetID(
v8::Isolate* isolate,
std::string target_id) {
auto agent_host = content::DevToolsAgentHost::GetForId(target_id);
WebContents* contents =
agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr;
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8(
v8::Isolate* isolate) {
std::vector<gin::Handle<WebContents>> list;
for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
!iter.IsAtEnd(); iter.Advance()) {
list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue()));
}
return list;
}
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("WebContents", WebContents::GetConstructor(context));
dict.SetMethod("fromId", &WebContentsFromID);
dict.SetMethod("fromFrame", &WebContentsFromFrame);
dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID);
dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8);
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,342 |
[Bug]: Navigator.keyboard.lock() icw requestFullscreen does not change behavior to 'Press and Hold Escape'
|
### 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
27.0.2
### What operating system are you using?
Windows
### Operating System Version
Windows 10 Pro version 22H2
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
When an element is brought to fullscreen with:
[elem.requestFullscreen()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen)
and an event listener exists like:
```
document.addEventListener('fullscreenchange', async () => {
const nav: any = navigator;
const elem = document.getElementById('app');
if (elem) {
await nav.keyboard.lock(['Escape']);
return;
}
nav.keyboard.unlock();
});
```
I would expect that the behavior of the Esc key changes, where I would now need to press and hold Esc for a few seconds before fullscreen is actually exited. As described here: [https://developer.chrome.com/blog/better-full-screen-mode/](https://developer.chrome.com/blog/better-full-screen-mode/)
I imagine the same behavior change should hold for when [requestPointerLock()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestPointerLock) is used.
### Actual Behavior
When the Esc key is pressed after bringing an element to fullscreen, it ALWAYS exits fullscreen immediately, even when used in combination with [keyboard.lock() API](https://developer.mozilla.org/en-US/docs/Web/API/Keyboard/lock).
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/40342
|
https://github.com/electron/electron/pull/40365
|
4b1c31e4dbd00cd58e159cbc2ab41de3b1ce3a86
|
fcdd5cba71b82c13c4f64a3e529dea91ed72d23c
| 2023-10-26T09:51:51Z |
c++
| 2023-10-31T15:59:39Z |
shell/browser/api/electron_api_web_contents_mac.mm
|
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "content/public/browser/render_widget_host_view.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/ui/cocoa/event_dispatching_window.h"
#include "shell/browser/web_contents_preferences.h"
#include "ui/base/cocoa/command_dispatcher.h"
#include "ui/base/cocoa/nsmenu_additions.h"
#include "ui/base/cocoa/nsmenuitem_additions.h"
#include "ui/events/keycodes/keyboard_codes.h"
#import <Cocoa/Cocoa.h>
@interface NSWindow (EventDispatchingWindow)
- (void)redispatchKeyEvent:(NSEvent*)event;
@end
namespace electron::api {
bool WebContents::IsFocused() const {
auto* view = web_contents()->GetRenderWidgetHostView();
if (!view)
return false;
if (GetType() != Type::kBackgroundPage) {
auto window = [web_contents()->GetNativeView().GetNativeNSView() window];
// On Mac the render widget host view does not lose focus when the window
// loses focus so check if the top level window is the key window.
if (window && ![window isKeyWindow])
return false;
}
return view->HasFocus();
}
bool WebContents::PlatformHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (event.skip_if_unhandled ||
event.GetType() == content::NativeWebKeyboardEvent::Type::kChar)
return false;
// Escape exits tabbed fullscreen mode.
if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) {
ExitFullscreenModeForTab(source);
return true;
}
// Check if the webContents has preferences and to ignore shortcuts
auto* web_preferences = WebContentsPreferences::From(source);
if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts())
return false;
NSEvent* ns_event = event.os_event.Get();
// Send the event to the menu before sending it to the window
if (ns_event.type == NSEventTypeKeyDown) {
// If the keyboard event is a system shortcut, it's already sent to the
// NSMenu instance in
// content/app_shim_remote_cocoa/render_widget_host_view_cocoa.mm via
// keyEvent:(NSEvent*)theEvent wasKeyEquivalent:(BOOL)equiv. If we let the
// NSMenu handle it here as well, it'll be sent twice with unexpected side
// effects.
bool is_a_keyboard_shortcut_event =
[[NSApp mainMenu] cr_menuItemForKeyEquivalentEvent:ns_event] != nil;
bool is_a_system_shortcut_event =
is_a_keyboard_shortcut_event &&
(ui::cocoa::ModifierMaskForKeyEvent(ns_event) &
NSEventModifierFlagFunction) != 0;
if (is_a_system_shortcut_event)
return false;
if ([[NSApp mainMenu] performKeyEquivalent:ns_event])
return true;
}
// Let the window redispatch the OS event
if (ns_event.window &&
[ns_event.window isKindOfClass:[EventDispatchingWindow class]]) {
[ns_event.window redispatchKeyEvent:ns_event];
// FIXME(nornagon): this isn't the right return value; we should implement
// devtools windows as Widgets in order to take advantage of the
// preexisting redispatch code in bridged_native_widget.
return false;
} else if (ns_event.window &&
[ns_event.window
conformsToProtocol:@protocol(CommandDispatchingWindow)]) {
NSObject<CommandDispatchingWindow>* window =
static_cast<NSObject<CommandDispatchingWindow>*>(ns_event.window);
[[window commandDispatcher] redispatchKeyEvent:ns_event];
// FIXME(clavin): Not exactly sure what to return here, likely the same
// situation as the branch above. If a future refactor removes
// |EventDispatchingWindow| then only this branch will need to remain.
return false;
}
return false;
}
} // namespace electron::api
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,342 |
[Bug]: Navigator.keyboard.lock() icw requestFullscreen does not change behavior to 'Press and Hold Escape'
|
### 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
27.0.2
### What operating system are you using?
Windows
### Operating System Version
Windows 10 Pro version 22H2
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
When an element is brought to fullscreen with:
[elem.requestFullscreen()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen)
and an event listener exists like:
```
document.addEventListener('fullscreenchange', async () => {
const nav: any = navigator;
const elem = document.getElementById('app');
if (elem) {
await nav.keyboard.lock(['Escape']);
return;
}
nav.keyboard.unlock();
});
```
I would expect that the behavior of the Esc key changes, where I would now need to press and hold Esc for a few seconds before fullscreen is actually exited. As described here: [https://developer.chrome.com/blog/better-full-screen-mode/](https://developer.chrome.com/blog/better-full-screen-mode/)
I imagine the same behavior change should hold for when [requestPointerLock()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestPointerLock) is used.
### Actual Behavior
When the Esc key is pressed after bringing an element to fullscreen, it ALWAYS exits fullscreen immediately, even when used in combination with [keyboard.lock() API](https://developer.mozilla.org/en-US/docs/Web/API/Keyboard/lock).
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/40342
|
https://github.com/electron/electron/pull/40365
|
4b1c31e4dbd00cd58e159cbc2ab41de3b1ce3a86
|
fcdd5cba71b82c13c4f64a3e529dea91ed72d23c
| 2023-10-26T09:51:51Z |
c++
| 2023-10-31T15:59:39Z |
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';
import { AddressInfo } from 'node:net';
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 listen(server);
const bw = new BrowserWindow({ show: false });
try {
const reportGenerated = once(reporting, 'report');
await bw.loadURL(`https://localhost:${(server.address() as AddressInfo).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.replaceAll('\\', '/'),
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.replaceAll(/(\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();
});
for (const isSandboxEnabled of [true, false]) {
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.replaceAll('\\', '/')}/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__');
});
it('works when used in conjunction with the vm module', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
await w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const { contextObject } = await w.webContents.executeJavaScript(`(async () => {
const vm = require('node:vm');
const contextObject = { count: 1, type: 'gecko' };
window.open('');
vm.runInNewContext('count += 1; type = "chameleon";', contextObject);
return { contextObject };
})()`);
expect(contextObject).to.deep.equal({ count: 2, type: 'chameleon' });
});
// 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":"object","exports":"object","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('IdleDetection', () => {
afterEach(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setPermissionRequestHandler(null);
});
it('can grant a permission request', async () => {
session.defaultSession.setPermissionRequestHandler(
(_wc, permission, callback) => {
callback(permission === 'idle-detection');
}
);
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'button.html'));
const permission = await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const button = document.getElementById('button');
button.addEventListener("click", async () => {
const permission = await IdleDetector.requestPermission();
resolve(permission);
});
button.click();
});
`, true);
expect(permission).to.eq('granted');
});
it('can deny a permission request', async () => {
session.defaultSession.setPermissionRequestHandler(
(_wc, permission, callback) => {
callback(permission !== 'idle-detection');
}
);
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'button.html'));
const permission = await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const button = document.getElementById('button');
button.addEventListener("click", async () => {
const permission = await IdleDetector.requestPermission();
resolve(permission);
});
button.click();
});
`, true);
expect(permission).to.eq('denied');
});
it('can allow the IdleDetector to start', async () => {
session.defaultSession.setPermissionCheckHandler((wc, permission) => {
return permission === 'idle-detection';
});
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const result = await w.webContents.executeJavaScript(`
const detector = new IdleDetector({ threshold: 60000 });
detector.start().then(() => {
return 'success';
}).catch(e => e.message);
`, true);
expect(result).to.eq('success');
});
it('can prevent the IdleDetector from starting', async () => {
session.defaultSession.setPermissionCheckHandler((wc, permission) => {
return permission !== 'idle-detection';
});
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const result = await w.webContents.executeJavaScript(`
const detector = new IdleDetector({ threshold: 60000 });
detector.start().then(() => {
console.log('success')
}).catch(e => e.message);
`, true);
expect(result).to.eq('Idle detection permission denied');
});
});
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', () => {
for (const storageName of ['localStorage', 'sessionStorage']) {
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').replaceAll('\\', '/'),
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.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.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.once('navigation-entry-committed' as any, () => {
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.getActiveIndex()).to.equal(1);
});
});
});
describe('chrome:// pages', () => {
const urls = [
'chrome://accessibility',
'chrome://gpu',
'chrome://media-internals',
'chrome://tracing',
'chrome://webrtc-internals'
];
for (const url of urls) {
describe(url, () => {
it('loads the page successfully', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(url);
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
| 40,342 |
[Bug]: Navigator.keyboard.lock() icw requestFullscreen does not change behavior to 'Press and Hold Escape'
|
### 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
27.0.2
### What operating system are you using?
Windows
### Operating System Version
Windows 10 Pro version 22H2
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
When an element is brought to fullscreen with:
[elem.requestFullscreen()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen)
and an event listener exists like:
```
document.addEventListener('fullscreenchange', async () => {
const nav: any = navigator;
const elem = document.getElementById('app');
if (elem) {
await nav.keyboard.lock(['Escape']);
return;
}
nav.keyboard.unlock();
});
```
I would expect that the behavior of the Esc key changes, where I would now need to press and hold Esc for a few seconds before fullscreen is actually exited. As described here: [https://developer.chrome.com/blog/better-full-screen-mode/](https://developer.chrome.com/blog/better-full-screen-mode/)
I imagine the same behavior change should hold for when [requestPointerLock()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestPointerLock) is used.
### Actual Behavior
When the Esc key is pressed after bringing an element to fullscreen, it ALWAYS exits fullscreen immediately, even when used in combination with [keyboard.lock() API](https://developer.mozilla.org/en-US/docs/Web/API/Keyboard/lock).
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/40342
|
https://github.com/electron/electron/pull/40365
|
4b1c31e4dbd00cd58e159cbc2ab41de3b1ce3a86
|
fcdd5cba71b82c13c4f64a3e529dea91ed72d23c
| 2023-10-26T09:51:51Z |
c++
| 2023-10-31T15:59:39Z |
spec/fixtures/pages/modal.html
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 40,342 |
[Bug]: Navigator.keyboard.lock() icw requestFullscreen does not change behavior to 'Press and Hold Escape'
|
### 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
27.0.2
### What operating system are you using?
Windows
### Operating System Version
Windows 10 Pro version 22H2
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
When an element is brought to fullscreen with:
[elem.requestFullscreen()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen)
and an event listener exists like:
```
document.addEventListener('fullscreenchange', async () => {
const nav: any = navigator;
const elem = document.getElementById('app');
if (elem) {
await nav.keyboard.lock(['Escape']);
return;
}
nav.keyboard.unlock();
});
```
I would expect that the behavior of the Esc key changes, where I would now need to press and hold Esc for a few seconds before fullscreen is actually exited. As described here: [https://developer.chrome.com/blog/better-full-screen-mode/](https://developer.chrome.com/blog/better-full-screen-mode/)
I imagine the same behavior change should hold for when [requestPointerLock()](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestPointerLock) is used.
### Actual Behavior
When the Esc key is pressed after bringing an element to fullscreen, it ALWAYS exits fullscreen immediately, even when used in combination with [keyboard.lock() API](https://developer.mozilla.org/en-US/docs/Web/API/Keyboard/lock).
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/40342
|
https://github.com/electron/electron/pull/40365
|
4b1c31e4dbd00cd58e159cbc2ab41de3b1ce3a86
|
fcdd5cba71b82c13c4f64a3e529dea91ed72d23c
| 2023-10-26T09:51:51Z |
c++
| 2023-10-31T15:59:39Z |
spec/webview-spec.ts
|
import * as path from 'node:path';
import * as url from 'node:url';
import { BrowserWindow, session, ipcMain, app, WebContents } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import { emittedUntil } from './lib/events-helpers';
import { ifit, ifdescribe, defer, itremote, useRemoteContext, listen } from './lib/spec-helpers';
import { expect } from 'chai';
import * as http from 'node:http';
import * as auth from 'basic-auth';
import { once } from 'node:events';
import { setTimeout } from 'node:timers/promises';
declare let WebView: any;
const features = process._linkedBinding('electron_common_features');
async function loadWebView (w: WebContents, attributes: Record<string, string>, opts?: {openDevTools?: boolean}): Promise<void> {
const { openDevTools } = {
openDevTools: false,
...opts
};
await w.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView()
webview.id = 'webview'
for (const [k, v] of Object.entries(${JSON.stringify(attributes)})) {
webview.setAttribute(k, v)
}
document.body.appendChild(webview)
webview.addEventListener('dom-ready', () => {
if (${openDevTools}) {
webview.openDevTools()
}
})
webview.addEventListener('did-finish-load', () => {
resolve()
})
})
`);
}
async function loadWebViewAndWaitForEvent (w: WebContents, attributes: Record<string, string>, eventName: string): Promise<any> {
return await w.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.id = 'webview'
for (const [k, v] of Object.entries(${JSON.stringify(attributes)})) {
webview.setAttribute(k, v)
}
webview.addEventListener(${JSON.stringify(eventName)}, (e) => resolve({...e}), {once: true})
document.body.appendChild(webview)
})`);
};
async function loadWebViewAndWaitForMessage (w: WebContents, attributes: Record<string, string>): Promise<string> {
const { message } = await loadWebViewAndWaitForEvent(w, attributes, 'console-message');
return message;
};
describe('<webview> tag', function () {
const fixtures = path.join(__dirname, 'fixtures');
const blankPageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'blank.html')).toString();
function hideChildWindows (e: any, wc: WebContents) {
wc.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
show: false
}
}));
}
before(() => {
app.on('web-contents-created', hideChildWindows);
});
after(() => {
app.off('web-contents-created', hideChildWindows);
});
describe('behavior', () => {
afterEach(closeAllWindows);
it('works without script tag in page', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html'));
await once(ipcMain, 'pong');
});
it('works with sandbox', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
sandbox: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html'));
await once(ipcMain, 'pong');
});
it('works with contextIsolation', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html'));
await once(ipcMain, 'pong');
});
it('works with contextIsolation + sandbox', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true,
sandbox: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html'));
await once(ipcMain, 'pong');
});
it('works with Trusted Types', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-trusted-types.html'));
await once(ipcMain, 'pong');
});
it('is disabled by default', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
preload: path.join(fixtures, 'module', 'preload-webview.js'),
nodeIntegration: true
}
});
const webview = once(ipcMain, 'webview');
w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html'));
const [, type] = await webview;
expect(type).to.equal('undefined', 'WebView still exists');
});
});
// FIXME(deepak1556): Ch69 follow up.
xdescribe('document.visibilityState/hidden', () => {
afterEach(() => {
ipcMain.removeAllListeners('pong');
});
afterEach(closeAllWindows);
it('updates when the window is shown after the ready-to-show event', async () => {
const w = new BrowserWindow({ show: false });
const readyToShowSignal = once(w, 'ready-to-show');
const pongSignal1 = once(ipcMain, 'pong');
w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html'));
await pongSignal1;
const pongSignal2 = once(ipcMain, 'pong');
await readyToShowSignal;
w.show();
const [, visibilityState, hidden] = await pongSignal2;
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false();
});
it('inherits the parent window visibility state and receives visibilitychange events', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html'));
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true();
// We have to start waiting for the event
// before we ask the webContents to resize.
const getResponse = once(ipcMain, 'pong');
w.webContents.emit('-window-visibility-change', 'visible');
return getResponse.then(([, visibilityState, hidden]) => {
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false();
});
});
});
describe('did-attach-webview event', () => {
afterEach(closeAllWindows);
it('is emitted when a webview has been attached', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: 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('did-attach event', () => {
afterEach(closeAllWindows);
it('is emitted when a webview has been attached', async () => {
const w = new BrowserWindow({
webPreferences: {
webviewTag: true
}
});
await w.loadURL('about:blank');
const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', 'about:blank')
webview.addEventListener('did-attach', (e) => {
resolve('ok')
})
document.body.appendChild(webview)
})`);
expect(message).to.equal('ok');
});
});
describe('did-change-theme-color event', () => {
afterEach(closeAllWindows);
it('emits when theme color changes', async () => {
const w = new BrowserWindow({
webPreferences: {
webviewTag: true
}
});
await w.loadURL('about:blank');
const src = url.format({
pathname: `${fixtures.replaceAll('\\', '/')}/pages/theme-color.html`,
protocol: 'file',
slashes: true
});
const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', '${src}')
webview.addEventListener('did-change-theme-color', (e) => {
resolve('ok')
})
document.body.appendChild(webview)
})`);
expect(message).to.equal('ok');
});
});
describe('devtools', () => {
afterEach(closeAllWindows);
// FIXME: This test is flaky on WOA, so skip it there.
ifit(process.platform !== 'win32' || process.arch !== 'arm64')('loads devtools extensions registered on the parent window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
w.webContents.session.removeExtension('foo');
const extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo');
await w.webContents.session.loadExtension(extensionPath, {
allowFileAccess: true
});
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'webview-devtools.html'));
loadWebView(w.webContents, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(__dirname, 'fixtures', 'blank.html')}`
}, { openDevTools: true });
let childWebContentsId = 0;
app.once('web-contents-created', (e, webContents) => {
childWebContentsId = webContents.id;
webContents.on('devtools-opened', function () {
const showPanelIntervalId = setInterval(function () {
if (!webContents.isDestroyed() && webContents.devToolsWebContents) {
webContents.devToolsWebContents.executeJavaScript('(' + function () {
const { EUI } = (window as any);
const instance = EUI.InspectorView.InspectorView.instance();
const tabs = instance.tabbedPane.tabs;
const lastPanelId: any = tabs[tabs.length - 1].id;
instance.showPanel(lastPanelId);
}.toString() + ')()');
} else {
clearInterval(showPanelIntervalId);
}
}, 100);
});
});
const [, { runtimeId, tabId }] = await once(ipcMain, 'answer');
expect(runtimeId).to.match(/^[a-z]{32}$/);
expect(tabId).to.equal(childWebContentsId);
await w.webContents.executeJavaScript('webview.closeDevTools()');
});
});
describe('zoom behavior', () => {
const zoomScheme = standardScheme;
const webviewSession = session.fromPartition('webview-temp');
afterEach(closeAllWindows);
before(() => {
const protocol = webviewSession.protocol;
protocol.registerStringProtocol(zoomScheme, (request, callback) => {
callback('hello');
});
});
after(() => {
const protocol = webviewSession.protocol;
protocol.unregisterProtocol(zoomScheme);
});
it('inherits the zoomFactor of the parent window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
});
const zoomEventPromise = once(ipcMain, 'webview-parent-zoom-level');
w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-factor.html'));
const [, zoomFactor, zoomLevel] = await zoomEventPromise;
expect(zoomFactor).to.equal(1.2);
expect(zoomLevel).to.equal(1);
});
it('maintains zoom level on navigation', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
});
const promise = new Promise<void>((resolve) => {
ipcMain.on('webview-zoom-level', (event, zoomLevel, zoomFactor, newHost, final) => {
if (!newHost) {
expect(zoomFactor).to.equal(1.44);
expect(zoomLevel).to.equal(2.0);
} else {
expect(zoomFactor).to.equal(1.2);
expect(zoomLevel).to.equal(1);
}
if (final) {
resolve();
}
});
});
w.loadFile(path.join(fixtures, 'pages', 'webview-custom-zoom-level.html'));
await promise;
});
it('maintains zoom level when navigating within same page', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
});
const promise = new Promise<void>((resolve) => {
ipcMain.on('webview-zoom-in-page', (event, zoomLevel, zoomFactor, final) => {
expect(zoomFactor).to.equal(1.44);
expect(zoomLevel).to.equal(2.0);
if (final) {
resolve();
}
});
});
w.loadFile(path.join(fixtures, 'pages', 'webview-in-page-navigate.html'));
await promise;
});
it('inherits zoom level for the origin when available', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'webview-origin-zoom-level.html'));
const [, zoomLevel] = await once(ipcMain, 'webview-origin-zoom-level');
expect(zoomLevel).to.equal(2.0);
});
it('does not crash when navigating with zoom level inherited from parent', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
zoomFactor: 1.2,
session: webviewSession,
contextIsolation: false
}
});
const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
const readyPromise = once(ipcMain, 'dom-ready');
w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-inherited.html'));
const [, webview] = await attachPromise;
await readyPromise;
expect(webview.getZoomFactor()).to.equal(1.2);
await w.loadURL(`${zoomScheme}://host1`);
});
it('does not crash when changing zoom level after webview is destroyed', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
session: webviewSession,
contextIsolation: false
}
});
const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
await w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-inherited.html'));
await attachPromise;
await w.webContents.executeJavaScript('view.remove()');
w.webContents.setZoomLevel(0.5);
});
});
describe('requestFullscreen from webview', () => {
afterEach(closeAllWindows);
async function loadWebViewWindow (): Promise<[BrowserWindow, WebContents]> {
const w = new BrowserWindow({
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
const attachPromise = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
const loadPromise = once(w.webContents, 'did-finish-load');
const readyPromise = once(ipcMain, 'webview-ready');
w.loadFile(path.join(__dirname, 'fixtures', 'webview', 'fullscreen', 'main.html'));
const [, webview] = await attachPromise;
await Promise.all([readyPromise, loadPromise]);
return [w, webview];
};
afterEach(async () => {
// The leaving animation is un-observable but can interfere with future tests
// Specifically this is async on macOS but can be on other platforms too
await setTimeout(1000);
closeAllWindows();
});
ifit(process.platform !== 'darwin')('should make parent frame element fullscreen too (non-macOS)', async () => {
const [w, webview] = await loadWebViewWindow();
expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.false();
const parentFullscreen = once(ipcMain, 'fullscreenchange');
await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await parentFullscreen;
expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.true();
const close = once(w, 'closed');
w.close();
await close;
});
ifit(process.platform === 'darwin')('should make parent frame element fullscreen too (macOS)', async () => {
const [w, webview] = await loadWebViewWindow();
expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.false();
const parentFullscreen = once(ipcMain, 'fullscreenchange');
const enterHTMLFS = once(w.webContents, 'enter-html-full-screen');
const leaveHTMLFS = once(w.webContents, 'leave-html-full-screen');
await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.true();
await webview.executeJavaScript('document.exitFullscreen()');
await Promise.all([enterHTMLFS, leaveHTMLFS, parentFullscreen]);
const close = once(w, 'closed');
w.close();
await close;
});
// FIXME(zcbenz): Fullscreen events do not work on Linux.
ifit(process.platform !== 'linux')('exiting fullscreen should unfullscreen window', async () => {
const [w, webview] = await loadWebViewWindow();
const enterFullScreen = once(w, 'enter-full-screen');
await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
const leaveFullScreen = once(w, 'leave-full-screen');
await webview.executeJavaScript('document.exitFullscreen()', true);
await leaveFullScreen;
await setTimeout();
expect(w.isFullScreen()).to.be.false();
const close = once(w, 'closed');
w.close();
await close;
});
// Sending ESC via sendInputEvent only works on Windows.
ifit(process.platform === 'win32')('pressing ESC should unfullscreen window', async () => {
const [w, webview] = await loadWebViewWindow();
const enterFullScreen = once(w, 'enter-full-screen');
await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
const leaveFullScreen = once(w, 'leave-full-screen');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
await leaveFullScreen;
await setTimeout();
expect(w.isFullScreen()).to.be.false();
const close = once(w, 'closed');
w.close();
await close;
});
it('pressing ESC should emit the leave-html-full-screen event', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
const didAttachWebview = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'));
const [, webContents] = await didAttachWebview;
const enterFSWindow = once(w, 'enter-html-full-screen');
const enterFSWebview = once(webContents, 'enter-html-full-screen');
await webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFSWindow;
await enterFSWebview;
const leaveFSWindow = once(w, 'leave-html-full-screen');
const leaveFSWebview = once(webContents, 'leave-html-full-screen');
webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
await leaveFSWebview;
await leaveFSWindow;
const close = once(w, 'closed');
w.close();
await close;
});
it('should support user gesture', async () => {
const [w, webview] = await loadWebViewWindow();
const waitForEnterHtmlFullScreen = once(webview, 'enter-html-full-screen');
const jsScript = "document.querySelector('video').webkitRequestFullscreen()";
webview.executeJavaScript(jsScript, true);
await waitForEnterHtmlFullScreen;
const close = once(w, 'closed');
w.close();
await close;
});
});
describe('child windows', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
it('opens window of about:blank with cross-scripting enabled', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-blank.html')}`
});
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('Hello');
});
it('opens window of same domain with cross-scripting enabled', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-file.html')}`
});
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('Hello');
});
it('returns null from window.open when allowpopups is not set', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-no-allowpopups.html')}`
});
const [, { windowOpenReturnedNull }] = await once(ipcMain, 'answer');
expect(windowOpenReturnedNull).to.be.true();
});
it('blocks accessing cross-origin frames', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${path.join(fixtures, 'api', 'native-window-open-cross-origin.html')}`
});
const [, content] = await once(ipcMain, 'answer');
const expectedContent =
/Failed to read a named property 'toString' from 'Location': Blocked a frame with origin "(.*?)" from accessing a cross-origin frame./;
expect(content).to.match(expectedContent);
});
it('emits a browser-window-created event', async () => {
// Don't wait for loading to finish.
loadWebView(w.webContents, {
allowpopups: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/window-open.html`
});
await once(app, 'browser-window-created');
});
it('emits a web-contents-created event', async () => {
const webContentsCreated = emittedUntil(app, 'web-contents-created',
(event: Electron.Event, contents: Electron.WebContents) => contents.getType() === 'window');
loadWebView(w.webContents, {
allowpopups: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/window-open.html`
});
await webContentsCreated;
});
it('does not crash when creating window with noopener', async () => {
loadWebView(w.webContents, {
allowpopups: 'on',
src: `file://${path.join(fixtures, 'api', 'native-window-open-noopener.html')}`
});
await once(app, 'browser-window-created');
});
});
describe('webpreferences attribute', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true } });
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
it('can enable context isolation', async () => {
loadWebView(w.webContents, {
allowpopups: 'yes',
preload: `file://${fixtures}/api/isolated-preload.js`,
src: `file://${fixtures}/api/isolated.html`,
webpreferences: 'contextIsolation=yes'
});
const [, data] = await once(ipcMain, 'isolated-world');
expect(data).to.deep.equal({
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'
}
});
});
});
describe('permission request handlers', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
const partition = 'permissionTest';
function setUpRequestHandler (webContentsId: number, requestedPermission: string) {
return new Promise<void>((resolve, reject) => {
session.fromPartition(partition).setPermissionRequestHandler(function (webContents, permission, callback) {
if (webContents.id === webContentsId) {
// requestMIDIAccess with sysex requests both midi and midiSysex so
// grant the first midi one and then reject the midiSysex one
if (requestedPermission === 'midiSysex' && permission === 'midi') {
return callback(true);
}
try {
expect(permission).to.equal(requestedPermission);
} catch (e) {
return reject(e);
}
callback(false);
resolve();
}
});
});
}
afterEach(() => {
session.fromPartition(partition).setPermissionRequestHandler(null);
});
// This is disabled because CI machines don't have cameras or microphones,
// so Chrome responds with "NotFoundError" instead of
// "PermissionDeniedError". It should be re-enabled if we find a way to mock
// the presence of a microphone & camera.
xit('emits when using navigator.getUserMedia api', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/media.html`,
partition,
nodeintegration: 'on'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
setUpRequestHandler(webViewContents.id, 'media');
const [, errorName] = await errorFromRenderer;
expect(errorName).to.equal('PermissionDeniedError');
});
it('emits when using navigator.geolocation api', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/geolocation.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
setUpRequestHandler(webViewContents.id, 'geolocation');
const [, error] = await errorFromRenderer;
expect(error).to.equal('User denied Geolocation');
});
it('emits when using navigator.requestMIDIAccess without sysex api', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/midi.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
setUpRequestHandler(webViewContents.id, 'midi');
const [, error] = await errorFromRenderer;
expect(error).to.equal('SecurityError');
});
it('emits when using navigator.requestMIDIAccess with sysex api', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/midi-sysex.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
setUpRequestHandler(webViewContents.id, 'midiSysex');
const [, error] = await errorFromRenderer;
expect(error).to.equal('SecurityError');
});
it('emits when accessing external protocol', async () => {
loadWebView(w.webContents, {
src: 'magnet:test',
partition
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
await setUpRequestHandler(webViewContents.id, 'openExternal');
});
it('emits when using Notification.requestPermission', async () => {
const errorFromRenderer = once(ipcMain, 'message');
loadWebView(w.webContents, {
src: `file://${fixtures}/pages/permissions/notification.html`,
partition,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
});
const [, webViewContents] = await once(app, 'web-contents-created') as [any, WebContents];
await setUpRequestHandler(webViewContents.id, 'notifications');
const [, error] = await errorFromRenderer;
expect(error).to.equal('denied');
});
});
describe('DOM events', () => {
afterEach(closeAllWindows);
it('receives extra properties on DOM events when contextIsolation is enabled', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true
}
});
await w.loadURL('about:blank');
const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', 'data:text/html,<script>console.log("hi")</script>')
webview.addEventListener('console-message', (e) => {
resolve(e.message)
})
document.body.appendChild(webview)
})`);
expect(message).to.equal('hi');
});
it('emits focus event when contextIsolation is enabled', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
contextIsolation: true
}
});
await w.loadURL('about:blank');
await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
const webview = new WebView()
webview.setAttribute('src', 'about:blank')
webview.addEventListener('dom-ready', () => {
webview.focus()
})
webview.addEventListener('focus', () => {
resolve();
})
document.body.appendChild(webview)
})`);
});
});
describe('attributes', () => {
let w: WebContents;
before(async () => {
const window = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
await window.loadURL(`file://${fixtures}/pages/blank.html`);
w = window.webContents;
});
afterEach(async () => {
await w.executeJavaScript(`{
for (const el of document.querySelectorAll('webview')) el.remove();
}`);
});
after(closeAllWindows);
describe('src attribute', () => {
it('specifies the page to load', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/a.html`
});
expect(message).to.equal('a');
});
it('navigates to new page when changed', async () => {
await loadWebView(w, {
src: `file://${fixtures}/pages/a.html`
});
const { message } = await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('console-message', e => resolve({message: e.message}))
webview.src = ${JSON.stringify(`file://${fixtures}/pages/b.html`)}
})`);
expect(message).to.equal('b');
});
it('resolves relative URLs', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
src: './e.html'
});
expect(message).to.equal('Window script is loaded before preload script');
});
it('ignores empty values', async () => {
loadWebView(w, {});
for (const emptyValue of ['""', 'null', 'undefined']) {
const src = await w.executeJavaScript(`webview.src = ${emptyValue}, webview.src`);
expect(src).to.equal('');
}
});
it('does not wait until loadURL is resolved', async () => {
await loadWebView(w, { src: 'about:blank' });
const delay = await w.executeJavaScript(`new Promise(resolve => {
const before = Date.now();
webview.src = 'file://${fixtures}/pages/blank.html';
const now = Date.now();
resolve(now - before);
})`);
// Setting src is essentially sending a sync IPC message, which should
// not exceed more than a few ms.
//
// This is for testing #18638.
expect(delay).to.be.below(100);
});
});
describe('nodeintegration attribute', () => {
it('inserts no node symbols when not set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/c.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'undefined',
module: 'undefined',
process: 'undefined',
global: 'undefined'
});
});
it('inserts node symbols when set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/d.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('loads node symbols after POST navigation when set', async function () {
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/post.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('disables node integration on child windows when it is disabled on the webview', async () => {
const src = url.format({
pathname: `${fixtures}/pages/webview-opener-no-node-integration.html`,
protocol: 'file',
query: {
p: `${fixtures}/pages/window-opener-node.html`
},
slashes: true
});
const message = await loadWebViewAndWaitForMessage(w, {
allowpopups: 'on',
webpreferences: 'contextIsolation=no',
src
});
expect(JSON.parse(message).isProcessGlobalUndefined).to.be.true();
});
ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native modules when navigation happens', async function () {
await loadWebView(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/native-module.html`
});
const message = await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('console-message', e => resolve(e.message))
webview.reload();
})`);
expect(message).to.equal('function');
});
});
describe('preload attribute', () => {
useRemoteContext({ webPreferences: { webviewTag: true } });
it('loads the script before other scripts in window', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload.js`,
src: `file://${fixtures}/pages/e.html`
});
expect(message).to.be.a('string');
expect(message).to.be.not.equal('Window script is loaded before preload script');
});
it('preload script can still use "process" and "Buffer" when nodeintegration is off', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload-node-off.js`,
src: `file://${fixtures}/api/blank.html`
});
const types = JSON.parse(message);
expect(types).to.include({
process: 'object',
Buffer: 'function'
});
});
it('runs in the correct scope when sandboxed', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload-context.js`,
src: `file://${fixtures}/api/blank.html`,
webpreferences: 'sandbox=yes'
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function', // arguments passed to it should be available
electron: 'undefined', // objects from the scope it is called from should not be available
window: 'object', // the window object should be available
localVar: 'undefined' // but local variables should not be exposed to the window
});
});
it('preload script can require modules that still use "process" and "Buffer" when nodeintegration is off', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload-node-off-wrapper.js`,
webpreferences: 'sandbox=no',
src: `file://${fixtures}/api/blank.html`
});
const types = JSON.parse(message);
expect(types).to.include({
process: 'object',
Buffer: 'function'
});
});
it('receives ipc message in preload script', async () => {
await loadWebView(w, {
preload: `${fixtures}/module/preload-ipc.js`,
src: `file://${fixtures}/pages/e.html`
});
const message = 'boom!';
const { channel, args } = await w.executeJavaScript(`new Promise(resolve => {
webview.send('ping', ${JSON.stringify(message)})
webview.addEventListener('ipc-message', ({channel, args}) => resolve({channel, args}))
})`);
expect(channel).to.equal('pong');
expect(args).to.deep.equal([message]);
});
itremote('<webview>.sendToFrame()', async (fixtures: string) => {
const w = new WebView();
w.setAttribute('nodeintegration', 'on');
w.setAttribute('webpreferences', 'contextIsolation=no');
w.setAttribute('preload', `file://${fixtures}/module/preload-ipc.js`);
w.setAttribute('src', `file://${fixtures}/pages/ipc-message.html`);
document.body.appendChild(w);
const { frameId } = await new Promise<any>(resolve => w.addEventListener('ipc-message', resolve, { once: true }));
const message = 'boom!';
w.sendToFrame(frameId, 'ping', message);
const { channel, args } = await new Promise<any>(resolve => w.addEventListener('ipc-message', resolve, { once: true }));
expect(channel).to.equal('pong');
expect(args).to.deep.equal([message]);
}, [fixtures]);
it('works without script tag in page', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: `${fixtures}/module/preload.js`,
webpreferences: 'sandbox=no',
src: `file://${fixtures}/pages/base-page.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object',
Buffer: 'function'
});
});
it('resolves relative URLs', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
preload: '../module/preload.js',
webpreferences: 'sandbox=no',
src: `file://${fixtures}/pages/e.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object',
Buffer: 'function'
});
});
itremote('ignores empty values', async () => {
const webview = new WebView();
for (const emptyValue of ['', null, undefined]) {
webview.preload = emptyValue;
expect(webview.preload).to.equal('');
}
});
});
describe('httpreferrer attribute', () => {
it('sets the referrer url', async () => {
const referrer = 'http://github.com/';
const received = await new Promise<string | undefined>((resolve, reject) => {
const server = http.createServer((req, res) => {
try {
resolve(req.headers.referer);
} catch (e) {
reject(e);
} finally {
res.end();
server.close();
}
});
listen(server).then(({ url }) => {
loadWebView(w, {
httpreferrer: referrer,
src: url
});
});
});
expect(received).to.equal(referrer);
});
});
describe('useragent attribute', () => {
it('sets the user agent', async () => {
const referrer = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko';
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/useragent.html`,
useragent: referrer
});
expect(message).to.equal(referrer);
});
});
describe('disablewebsecurity attribute', () => {
it('does not disable web security when not set', async () => {
await loadWebView(w, { src: 'about:blank' });
const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`);
expect(result).to.equal('failed');
});
it('disables web security when set', async () => {
await loadWebView(w, { src: 'about:blank', disablewebsecurity: '' });
const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`);
expect(result).to.equal('ok');
});
it('does not break node integration', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
disablewebsecurity: '',
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/d.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('does not break preload script', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
disablewebsecurity: '',
preload: `${fixtures}/module/preload.js`,
webpreferences: 'sandbox=no',
src: `file://${fixtures}/pages/e.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object',
Buffer: 'function'
});
});
});
describe('partition attribute', () => {
it('inserts no node symbols when not set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
partition: 'test1',
src: `file://${fixtures}/pages/c.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'undefined',
module: 'undefined',
process: 'undefined',
global: 'undefined'
});
});
it('inserts node symbols when set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'on',
partition: 'test2',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/d.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('isolates storage for different id', async () => {
await w.executeJavaScript('localStorage.setItem(\'test\', \'one\')');
const message = await loadWebViewAndWaitForMessage(w, {
partition: 'test3',
src: `file://${fixtures}/pages/partition/one.html`
});
const parsedMessage = JSON.parse(message);
expect(parsedMessage).to.include({
numberOfEntries: 0,
testValue: null
});
});
it('uses current session storage when no id is provided', async () => {
await w.executeJavaScript('localStorage.setItem(\'test\', \'two\')');
const testValue = 'two';
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/partition/one.html`
});
const parsedMessage = JSON.parse(message);
expect(parsedMessage).to.include({
testValue
});
});
});
describe('allowpopups attribute', () => {
const generateSpecs = (description: string, webpreferences = '') => {
describe(description, () => {
it('can not open new window when not set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
webpreferences,
src: `file://${fixtures}/pages/window-open-hide.html`
});
expect(message).to.equal('null');
});
it('can open new window when set', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
webpreferences,
allowpopups: 'on',
src: `file://${fixtures}/pages/window-open-hide.html`
});
expect(message).to.equal('window');
});
});
};
generateSpecs('without sandbox');
generateSpecs('with sandbox', 'sandbox=yes');
});
describe('webpreferences attribute', () => {
it('can enable nodeintegration', async () => {
const message = await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/d.html`,
webpreferences: 'nodeIntegration,contextIsolation=no'
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
});
});
it('can disable web security and enable nodeintegration', async () => {
await loadWebView(w, { src: 'about:blank', webpreferences: 'webSecurity=no, nodeIntegration=yes, contextIsolation=no' });
const result = await w.executeJavaScript(`webview.executeJavaScript(\`fetch(${JSON.stringify(blankPageUrl)}).then(() => 'ok', () => 'failed')\`)`);
expect(result).to.equal('ok');
const type = await w.executeJavaScript('webview.executeJavaScript("typeof require")');
expect(type).to.equal('function');
});
});
});
describe('events', () => {
useRemoteContext({ webPreferences: { webviewTag: true } });
let w: WebContents;
before(async () => {
const window = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
await window.loadURL(`file://${fixtures}/pages/blank.html`);
w = window.webContents;
});
afterEach(async () => {
await w.executeJavaScript(`{
for (const el of document.querySelectorAll('webview')) el.remove();
}`);
});
after(closeAllWindows);
describe('ipc-message event', () => {
it('emits when guest sends an ipc message to browser', async () => {
const { frameId, channel, args } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/ipc-message.html`,
nodeintegration: 'on',
webpreferences: 'contextIsolation=no'
}, 'ipc-message');
expect(frameId).to.be.an('array').that.has.lengthOf(2);
expect(channel).to.equal('channel');
expect(args).to.deep.equal(['arg1', 'arg2']);
});
});
describe('page-title-updated event', () => {
it('emits when title is set', async () => {
const { title, explicitSet } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/a.html`
}, 'page-title-updated');
expect(title).to.equal('test');
expect(explicitSet).to.be.true();
});
});
describe('page-favicon-updated event', () => {
it('emits when favicon urls are received', async () => {
const { favicons } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/a.html`
}, 'page-favicon-updated');
expect(favicons).to.be.an('array').of.length(2);
if (process.platform === 'win32') {
expect(favicons[0]).to.match(/^file:\/\/\/[A-Z]:\/favicon.png$/i);
} else {
expect(favicons[0]).to.equal('file:///favicon.png');
}
});
});
describe('did-redirect-navigation event', () => {
it('is emitted on redirects', async () => {
const server = http.createServer((req, res) => {
if (req.url === '/302') {
res.setHeader('Location', '/200');
res.statusCode = 302;
res.end();
} else {
res.end();
}
});
const { url } = await listen(server);
defer(() => { server.close(); });
const event = await loadWebViewAndWaitForEvent(w, {
src: `${url}/302`
}, 'did-redirect-navigation');
expect(event.url).to.equal(`${url}/200`);
expect(event.isInPlace).to.be.false();
expect(event.isMainFrame).to.be.true();
expect(event.frameProcessId).to.be.a('number');
expect(event.frameRoutingId).to.be.a('number');
});
});
describe('will-navigate event', () => {
it('emits when a url that leads to outside of the page is loaded', async () => {
const { url } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/webview-will-navigate.html`
}, 'will-navigate');
expect(url).to.equal('http://host/');
});
});
describe('will-frame-navigate event', () => {
it('emits when a link that leads to outside of the page is loaded', async () => {
const { url, isMainFrame } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/webview-will-navigate.html`
}, 'will-frame-navigate');
expect(url).to.equal('http://host/');
expect(isMainFrame).to.be.true();
});
it('emits when a link within an iframe, which leads to outside of the page, is loaded', async () => {
await loadWebView(w, {
src: `file://${fixtures}/pages/webview-will-navigate-in-frame.html`,
nodeIntegration: ''
});
const { url, frameProcessId, frameRoutingId } = await w.executeJavaScript(`
new Promise((resolve, reject) => {
let hasFrameNavigatedOnce = false;
const webview = document.getElementById('webview');
webview.addEventListener('will-frame-navigate', ({url, isMainFrame, frameProcessId, frameRoutingId}) => {
if (isMainFrame) return;
if (hasFrameNavigatedOnce) resolve({
url,
isMainFrame,
frameProcessId,
frameRoutingId,
});
// First navigation is the initial iframe load within the <webview>
hasFrameNavigatedOnce = true;
});
webview.executeJavaScript('loadSubframe()');
});
`);
expect(url).to.equal('http://host/');
expect(frameProcessId).to.be.a('number');
expect(frameRoutingId).to.be.a('number');
});
});
describe('did-navigate event', () => {
it('emits when a url that leads to outside of the page is clicked', async () => {
const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-will-navigate.html')).toString();
const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate');
expect(event.url).to.equal(pageUrl);
});
});
describe('did-navigate-in-page event', () => {
it('emits when an anchor link is clicked', async () => {
const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-did-navigate-in-page.html')).toString();
const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate-in-page');
expect(event.url).to.equal(`${pageUrl}#test_content`);
});
it('emits when window.history.replaceState is called', async () => {
const { url } = await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/webview-did-navigate-in-page-with-history.html`
}, 'did-navigate-in-page');
expect(url).to.equal('http://host/');
});
it('emits when window.location.hash is changed', async () => {
const pageUrl = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-did-navigate-in-page-with-hash.html')).toString();
const event = await loadWebViewAndWaitForEvent(w, { src: pageUrl }, 'did-navigate-in-page');
expect(event.url).to.equal(`${pageUrl}#test`);
});
});
describe('close event', () => {
it('should fire when interior page calls window.close', async () => {
await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/close.html` }, 'close');
});
});
describe('devtools-opened event', () => {
it('should fire when webview.openDevTools() is called', async () => {
await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/base-page.html`
}, 'dom-ready');
await w.executeJavaScript(`new Promise((resolve) => {
webview.openDevTools()
webview.addEventListener('devtools-opened', () => resolve(), {once: true})
})`);
await w.executeJavaScript('webview.closeDevTools()');
});
});
describe('devtools-closed event', () => {
itremote('should fire when webview.closeDevTools() is called', async (fixtures: string) => {
const webview = new WebView();
webview.src = `file://${fixtures}/pages/base-page.html`;
document.body.appendChild(webview);
await new Promise(resolve => webview.addEventListener('dom-ready', resolve, { once: true }));
webview.openDevTools();
await new Promise(resolve => webview.addEventListener('devtools-opened', resolve, { once: true }));
webview.closeDevTools();
await new Promise(resolve => webview.addEventListener('devtools-closed', resolve, { once: true }));
}, [fixtures]);
});
describe('devtools-focused event', () => {
itremote('should fire when webview.openDevTools() is called', async (fixtures: string) => {
const webview = new WebView();
webview.src = `file://${fixtures}/pages/base-page.html`;
document.body.appendChild(webview);
const waitForDevToolsFocused = new Promise(resolve => webview.addEventListener('devtools-focused', resolve, { once: true }));
await new Promise(resolve => webview.addEventListener('dom-ready', resolve, { once: true }));
webview.openDevTools();
await waitForDevToolsFocused;
webview.closeDevTools();
}, [fixtures]);
});
describe('dom-ready event', () => {
it('emits when document is loaded', async () => {
const server = http.createServer(() => {});
const { port } = await listen(server);
await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/dom-ready.html?port=${port}`
}, 'dom-ready');
});
itremote('throws a custom error when an API method is called before the event is emitted', () => {
const expectedErrorMessage =
'The WebView must be attached to the DOM ' +
'and the dom-ready event emitted before this method can be called.';
const webview = new WebView();
expect(() => { webview.stop(); }).to.throw(expectedErrorMessage);
});
});
describe('context-menu event', () => {
it('emits when right-clicked in page', async () => {
await loadWebView(w, { src: 'about:blank' });
const { params, url } = await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('context-menu', (e) => resolve({...e, url: webview.getURL() }), {once: true})
// Simulate right-click to create context-menu event.
const opts = { x: 0, y: 0, button: 'right' };
webview.sendInputEvent({ ...opts, type: 'mouseDown' });
webview.sendInputEvent({ ...opts, type: 'mouseUp' });
})`);
expect(params.pageURL).to.equal(url);
expect(params.frame).to.be.undefined();
expect(params.x).to.be.a('number');
expect(params.y).to.be.a('number');
});
});
describe('found-in-page event', () => {
itremote('emits when a request is made', async (fixtures: string) => {
const webview = new WebView();
const didFinishLoad = new Promise(resolve => webview.addEventListener('did-finish-load', resolve, { once: true }));
webview.src = `file://${fixtures}/pages/content.html`;
document.body.appendChild(webview);
// TODO(deepak1556): With https://codereview.chromium.org/2836973002
// focus of the webContents is required when triggering the api.
// Remove this workaround after determining the cause for
// incorrect focus.
webview.focus();
await didFinishLoad;
const activeMatchOrdinal = [];
for (;;) {
const foundInPage = new Promise<any>(resolve => webview.addEventListener('found-in-page', resolve, { once: true }));
const requestId = webview.findInPage('virtual');
const event = await foundInPage;
expect(event.result.requestId).to.equal(requestId);
expect(event.result.matches).to.equal(3);
activeMatchOrdinal.push(event.result.activeMatchOrdinal);
if (event.result.activeMatchOrdinal === event.result.matches) {
break;
}
}
expect(activeMatchOrdinal).to.deep.equal([1, 2, 3]);
webview.stopFindInPage('clearSelection');
}, [fixtures]);
});
describe('will-attach-webview event', () => {
itremote('does not emit when src is not changed', async () => {
const webview = new WebView();
document.body.appendChild(webview);
await setTimeout();
const expectedErrorMessage = 'The WebView must be attached to the DOM and the dom-ready event emitted before this method can be called.';
expect(() => { webview.stop(); }).to.throw(expectedErrorMessage);
});
it('supports changing the web preferences', async () => {
w.once('will-attach-webview', (event, webPreferences, params) => {
params.src = `file://${path.join(fixtures, 'pages', 'c.html')}`;
webPreferences.nodeIntegration = false;
});
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'yes',
src: `file://${fixtures}/pages/a.html`
});
const types = JSON.parse(message);
expect(types).to.include({
require: 'undefined',
module: 'undefined',
process: 'undefined',
global: 'undefined'
});
});
it('handler modifying params.instanceId does not break <webview>', async () => {
w.once('will-attach-webview', (event, webPreferences, params) => {
params.instanceId = null as any;
});
await loadWebViewAndWaitForMessage(w, {
src: `file://${fixtures}/pages/a.html`
});
});
it('supports preventing a webview from being created', async () => {
w.once('will-attach-webview', event => event.preventDefault());
await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/c.html`
}, 'destroyed');
});
it('supports removing the preload script', async () => {
w.once('will-attach-webview', (event, webPreferences, params) => {
params.src = url.pathToFileURL(path.join(fixtures, 'pages', 'webview-stripped-preload.html')).toString();
delete webPreferences.preload;
});
const message = await loadWebViewAndWaitForMessage(w, {
nodeintegration: 'yes',
preload: path.join(fixtures, 'module', 'preload-set-global.js'),
src: `file://${fixtures}/pages/a.html`
});
expect(message).to.equal('undefined');
});
});
describe('media-started-playing and media-paused events', () => {
it('emits when audio starts and stops playing', async function () {
if (!await w.executeJavaScript('document.createElement(\'audio\').canPlayType(\'audio/wav\')')) {
return this.skip();
}
await loadWebView(w, { src: blankPageUrl });
// With the new autoplay policy, audio elements must be unmuted
// see https://goo.gl/xX8pDD.
await w.executeJavaScript(`new Promise(resolve => {
webview.executeJavaScript(\`
const audio = document.createElement("audio")
audio.src = "../assets/tone.wav"
document.body.appendChild(audio);
audio.play()
\`, true)
webview.addEventListener('media-started-playing', () => resolve(), {once: true})
})`);
await w.executeJavaScript(`new Promise(resolve => {
webview.executeJavaScript(\`
document.querySelector("audio").pause()
\`, true)
webview.addEventListener('media-paused', () => resolve(), {once: true})
})`);
});
});
});
describe('methods', () => {
let w: WebContents;
before(async () => {
const window = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
await window.loadURL(`file://${fixtures}/pages/blank.html`);
w = window.webContents;
});
afterEach(async () => {
await w.executeJavaScript(`{
for (const el of document.querySelectorAll('webview')) el.remove();
}`);
});
after(closeAllWindows);
describe('<webview>.reload()', () => {
it('should emit beforeunload handler', async () => {
await loadWebView(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/beforeunload-false.html`
});
// Event handler has to be added before reload.
const channel = await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('ipc-message', e => resolve(e.channel))
webview.reload();
})`);
expect(channel).to.equal('onbeforeunload');
});
});
describe('<webview>.goForward()', () => {
useRemoteContext({ webPreferences: { webviewTag: true } });
itremote('should work after a replaced history entry', async (fixtures: string) => {
function waitForEvent (target: EventTarget, event: string) {
return new Promise<any>(resolve => target.addEventListener(event, resolve, { once: true }));
}
function waitForEvents (target: EventTarget, ...events: string[]) {
return Promise.all(events.map(event => waitForEvent(webview, event)));
}
const webview = new WebView();
webview.setAttribute('nodeintegration', 'on');
webview.setAttribute('webpreferences', 'contextIsolation=no');
webview.src = `file://${fixtures}/pages/history-replace.html`;
document.body.appendChild(webview);
{
const [e] = await waitForEvents(webview, 'ipc-message', 'did-stop-loading');
expect(e.channel).to.equal('history');
expect(e.args[0]).to.equal(1);
expect(webview.canGoBack()).to.be.false();
expect(webview.canGoForward()).to.be.false();
}
webview.src = `file://${fixtures}/pages/base-page.html`;
await new Promise<void>(resolve => webview.addEventListener('did-stop-loading', resolve, { once: true }));
expect(webview.canGoBack()).to.be.true();
expect(webview.canGoForward()).to.be.false();
webview.goBack();
{
const [e] = await waitForEvents(webview, 'ipc-message', 'did-stop-loading');
expect(e.channel).to.equal('history');
expect(e.args[0]).to.equal(2);
expect(webview.canGoBack()).to.be.false();
expect(webview.canGoForward()).to.be.true();
}
webview.goForward();
await new Promise<void>(resolve => webview.addEventListener('did-stop-loading', resolve, { once: true }));
expect(webview.canGoBack()).to.be.true();
expect(webview.canGoForward()).to.be.false();
}, [fixtures]);
});
describe('<webview>.clearHistory()', () => {
it('should clear the navigation history', async () => {
await loadWebView(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: blankPageUrl
});
// Navigation must be triggered by a user gesture to make canGoBack() return true
await w.executeJavaScript('webview.executeJavaScript(`history.pushState(null, "", "foo.html")`, true)');
expect(await w.executeJavaScript('webview.canGoBack()')).to.be.true();
await w.executeJavaScript('webview.clearHistory()');
expect(await w.executeJavaScript('webview.canGoBack()')).to.be.false();
});
});
describe('executeJavaScript', () => {
it('can return the result of the executed script', async () => {
await loadWebView(w, {
src: 'about:blank'
});
const jsScript = "'4'+2";
const expectedResult = '42';
const result = await w.executeJavaScript(`webview.executeJavaScript(${JSON.stringify(jsScript)})`);
expect(result).to.equal(expectedResult);
});
});
it('supports inserting CSS', async () => {
await loadWebView(w, { src: `file://${fixtures}/pages/base-page.html` });
await w.executeJavaScript('webview.insertCSS(\'body { background-repeat: round; }\')');
const result = await w.executeJavaScript('webview.executeJavaScript(\'window.getComputedStyle(document.body).getPropertyValue("background-repeat")\')');
expect(result).to.equal('round');
});
it('supports removing inserted CSS', async () => {
await loadWebView(w, { src: `file://${fixtures}/pages/base-page.html` });
const key = await w.executeJavaScript('webview.insertCSS(\'body { background-repeat: round; }\')');
await w.executeJavaScript(`webview.removeInsertedCSS(${JSON.stringify(key)})`);
const result = await w.executeJavaScript('webview.executeJavaScript(\'window.getComputedStyle(document.body).getPropertyValue("background-repeat")\')');
expect(result).to.equal('repeat');
});
describe('sendInputEvent', () => {
it('can send keyboard event', async () => {
await loadWebViewAndWaitForEvent(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/onkeyup.html`
}, 'dom-ready');
const waitForIpcMessage = w.executeJavaScript('new Promise(resolve => webview.addEventListener("ipc-message", e => resolve({...e})), {once: true})');
w.executeJavaScript(`webview.sendInputEvent({
type: 'keyup',
keyCode: 'c',
modifiers: ['shift']
})`);
const { channel, args } = await waitForIpcMessage;
expect(channel).to.equal('keyup');
expect(args).to.deep.equal(['C', 'KeyC', 67, true, false]);
});
it('can send mouse event', async () => {
await loadWebViewAndWaitForEvent(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/onmouseup.html`
}, 'dom-ready');
const waitForIpcMessage = w.executeJavaScript('new Promise(resolve => webview.addEventListener("ipc-message", e => resolve({...e})), {once: true})');
w.executeJavaScript(`webview.sendInputEvent({
type: 'mouseup',
modifiers: ['ctrl'],
x: 10,
y: 20
})`);
const { channel, args } = await waitForIpcMessage;
expect(channel).to.equal('mouseup');
expect(args).to.deep.equal([10, 20, false, true]);
});
});
describe('<webview>.getWebContentsId', () => {
it('can return the WebContents ID', async () => {
await loadWebView(w, { src: 'about:blank' });
expect(await w.executeJavaScript('webview.getWebContentsId()')).to.be.a('number');
});
});
ifdescribe(features.isPrintingEnabled())('<webview>.printToPDF()', () => {
it('rejects on incorrectly typed parameters', async () => {
const badTypes = {
landscape: [],
displayHeaderFooter: '123',
printBackground: 2,
scale: 'not-a-number',
pageSize: 'IAmAPageSize',
margins: 'terrible',
pageRanges: { oops: 'im-not-the-right-key' },
headerTemplate: [1, 2, 3],
footerTemplate: [4, 5, 6],
preferCSSPageSize: 'no'
};
// These will hard crash in Chromium unless we type-check
for (const [key, value] of Object.entries(badTypes)) {
const param = { [key]: value };
const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
await loadWebView(w, { src });
await expect(w.executeJavaScript(`webview.printToPDF(${JSON.stringify(param)})`)).to.eventually.be.rejected();
}
});
it('can print to PDF', async () => {
const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
await loadWebView(w, { src });
const data = await w.executeJavaScript('webview.printToPDF({})');
expect(data).to.be.an.instanceof(Uint8Array).that.is.not.empty();
});
});
describe('DOM events', () => {
for (const [description, sandbox] of [
['without sandbox', false] as const,
['with sandbox', true] as const
]) {
describe(description, () => {
it('emits focus event', async () => {
await loadWebViewAndWaitForEvent(w, {
src: `file://${fixtures}/pages/a.html`,
webpreferences: `sandbox=${sandbox ? 'yes' : 'no'}`
}, 'dom-ready');
// If this test fails, check if webview.focus() still works.
await w.executeJavaScript(`new Promise(resolve => {
webview.addEventListener('focus', () => resolve(), {once: true});
webview.focus();
})`);
});
});
}
});
// TODO(miniak): figure out why this is failing on windows
ifdescribe(process.platform !== 'win32')('<webview>.capturePage()', () => {
it('returns a Promise with a NativeImage', async function () {
this.retries(5);
const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
await loadWebViewAndWaitForEvent(w, { src }, 'did-stop-loading');
const image = await w.executeJavaScript('webview.capturePage()');
expect(image.isEmpty()).to.be.false();
// Check the 25th byte in the PNG.
// Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
const imgBuffer = image.toPNG();
expect(imgBuffer[25]).to.equal(6);
});
it('returns a Promise with a NativeImage in the renderer', async function () {
this.retries(5);
const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
await loadWebViewAndWaitForEvent(w, { src }, 'did-stop-loading');
const byte = await w.executeJavaScript(`new Promise(resolve => {
webview.capturePage().then(image => {
resolve(image.toPNG()[25])
});
})`);
expect(byte).to.equal(6);
});
});
// FIXME(zcbenz): Disabled because of moving to OOPIF webview.
xdescribe('setDevToolsWebContents() API', () => {
/*
it('sets webContents of webview as devtools', async () => {
const webview2 = new WebView();
loadWebView(webview2);
// Setup an event handler for further usage.
const waitForDomReady = waitForEvent(webview2, 'dom-ready');
loadWebView(webview, { src: 'about:blank' });
await waitForEvent(webview, 'dom-ready');
webview.getWebContents().setDevToolsWebContents(webview2.getWebContents());
webview.getWebContents().openDevTools();
await waitForDomReady;
// Its WebContents should be a DevTools.
const devtools = webview2.getWebContents();
expect(devtools.getURL().startsWith('devtools://devtools')).to.be.true();
const name = await devtools.executeJavaScript('InspectorFrontendHost.constructor.name');
document.body.removeChild(webview2);
expect(name).to.be.equal('InspectorFrontendHostImpl');
});
*/
});
});
describe('basic auth', () => {
let w: WebContents;
before(async () => {
const window = new BrowserWindow({
show: false,
webPreferences: {
webviewTag: true,
nodeIntegration: true,
contextIsolation: false
}
});
await window.loadURL(`file://${fixtures}/pages/blank.html`);
w = window.webContents;
});
afterEach(async () => {
await w.executeJavaScript(`{
for (const el of document.querySelectorAll('webview')) el.remove();
}`);
});
after(closeAllWindows);
it('should authenticate with correct credentials', async () => {
const message = 'Authenticated';
const server = http.createServer((req, res) => {
const credentials = auth(req)!;
if (credentials.name === 'test' && credentials.pass === 'test') {
res.end(message);
} else {
res.end('failed');
}
});
defer(() => {
server.close();
});
const { port } = await listen(server);
const e = await loadWebViewAndWaitForEvent(w, {
nodeintegration: 'on',
webpreferences: 'contextIsolation=no',
src: `file://${fixtures}/pages/basic-auth.html?port=${port}`
}, 'ipc-message');
expect(e.channel).to.equal(message);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 31,431 |
[Feature Request]: Set ELECTRON_USE_REMOTE_CHECKSUMS from `.npmrc`
|
### 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
Starting with Electron 15 consuming custom electron binaries from a custom mirror requires setting the `ELECTRON_USE_REMOTE_CHECKSUMS` environment variable, otherwise the checksum match fails.
Specifying environment variables is cumbersome across all dev and CI hosts.
### Proposed Solution
If the electron installer script also looked at the `.npmrc` it would be a one time configuration option for the project and wouldn't require additional step (of setting env variable) during dev host setup.
@electron/get allows setting the mirror options this way.
### Alternatives Considered
Other option could be an npm package config, which would also work.
@electron/get also allows setting the mirror options this way.
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/31431
|
https://github.com/electron/electron/pull/40253
|
29d7be1565f6d5bcd4f8b5d95ccb77baece81717
|
f5262060957b7e32b33d64b3529a69417bdb5c26
| 2021-10-14T18:01:44Z |
c++
| 2023-10-31T20:51:59Z |
docs/tutorial/installation.md
|
# Advanced Installation Instructions
To install prebuilt Electron binaries, use [`npm`][npm].
The preferred method is to install Electron as a development dependency in your
app:
```sh
npm install electron --save-dev
```
See the [Electron versioning doc][versioning] for info on how to
manage Electron versions in your apps.
## Running Electron ad-hoc
If you're in a pinch and would prefer to not use `npm install` in your local
project, you can also run Electron ad-hoc using the [`npx`][npx] command runner
bundled with `npm`:
```sh
npx electron .
```
The above command will run the current working directory with Electron. Note that
any dependencies in your app will not be installed.
## Customization
If you want to change the architecture that is downloaded (e.g., `ia32` on an
`x64` machine), you can use the `--arch` flag with npm install or set the
`npm_config_arch` environment variable:
```shell
npm install --arch=ia32 electron
```
In addition to changing the architecture, you can also specify the platform
(e.g., `win32`, `linux`, etc.) using the `--platform` flag:
```shell
npm install --platform=win32 electron
```
## Proxies
If you need to use an HTTP proxy, you need to set the `ELECTRON_GET_USE_PROXY` variable to any
value, plus additional environment variables depending on your host system's Node version:
* [Node 10 and above][proxy-env-10]
* [Before Node 10][proxy-env]
## Custom Mirrors and Caches
During installation, the `electron` module will call out to
[`@electron/get`][electron-get] to download prebuilt binaries of
Electron for your platform. It will do so by contacting GitHub's
release download page (`https://github.com/electron/electron/releases/tag/v$VERSION`,
where `$VERSION` is the exact version of Electron).
If you are unable to access GitHub or you need to provide a custom build, you
can do so by either providing a mirror or an existing cache directory.
#### Mirror
You can use environment variables to override the base URL, the path at which to
look for Electron binaries, and the binary filename. The URL used by `@electron/get`
is composed as follows:
```javascript @ts-nocheck
url = ELECTRON_MIRROR + ELECTRON_CUSTOM_DIR + '/' + ELECTRON_CUSTOM_FILENAME
```
For instance, to use the China CDN mirror:
```shell
ELECTRON_MIRROR="https://npmmirror.com/mirrors/electron/"
```
By default, `ELECTRON_CUSTOM_DIR` is set to `v$VERSION`. To change the format,
use the `{{ version }}` placeholder. For example, `version-{{ version }}`
resolves to `version-5.0.0`, `{{ version }}` resolves to `5.0.0`, and
`v{{ version }}` is equivalent to the default. As a more concrete example, to
use the China non-CDN mirror:
```shell
ELECTRON_MIRROR="https://npmmirror.com/mirrors/electron/"
ELECTRON_CUSTOM_DIR="{{ version }}"
```
The above configuration will download from URLs such as
`https://npmmirror.com/mirrors/electron/8.0.0/electron-v8.0.0-linux-x64.zip`.
If your mirror serves artifacts with different checksums to the official
Electron release you may have to set `electron_use_remote_checksums=1` to
force Electron to use the remote `SHASUMS256.txt` file to verify the checksum
instead of the embedded checksums.
#### Cache
Alternatively, you can override the local cache. `@electron/get` will cache
downloaded binaries in a local directory to not stress your network. You can use
that cache folder to provide custom builds of Electron or to avoid making contact
with the network at all.
* Linux: `$XDG_CACHE_HOME` or `~/.cache/electron/`
* macOS: `~/Library/Caches/electron/`
* Windows: `$LOCALAPPDATA/electron/Cache` or `~/AppData/Local/electron/Cache/`
On environments that have been using older versions of Electron, you might find the
cache also in `~/.electron`.
You can also override the local cache location by providing a `electron_config_cache`
environment variable.
The cache contains the version's official zip file as well as a checksum, and is stored as
`[checksum]/[filename]`. A typical cache might look like this:
```sh
βββ a91b089b5dc5b1279966511344b805ec84869b6cd60af44f800b363bba25b915
β βββ electron-v15.3.1-darwin-x64.zip
```
## Skip binary download
Under the hood, Electron's JavaScript API binds to a binary that contains its
implementations. Because this binary is crucial to the function of any Electron app,
it is downloaded by default in the `postinstall` step every time you install `electron`
from the npm registry.
However, if you want to install your project's dependencies but don't need to use
Electron functionality, you can set the `ELECTRON_SKIP_BINARY_DOWNLOAD` environment
variable to prevent the binary from being downloaded. For instance, this feature can
be useful in continuous integration environments when running unit tests that mock
out the `electron` module.
```sh npm2yarn
ELECTRON_SKIP_BINARY_DOWNLOAD=1 npm install
```
## Troubleshooting
When running `npm install electron`, some users occasionally encounter
installation errors.
In almost all cases, these errors are the result of network problems and not
actual issues with the `electron` npm package. Errors like `ELIFECYCLE`,
`EAI_AGAIN`, `ECONNRESET`, and `ETIMEDOUT` are all indications of such
network problems. The best resolution is to try switching networks, or
wait a bit and try installing again.
You can also attempt to download Electron directly from
[electron/electron/releases][releases]
if installing via `npm` is failing.
If installation fails with an `EACCESS` error you may need to
[fix your npm permissions][npm-permissions].
If the above error persists, the [unsafe-perm][unsafe-perm] flag may need to be
set to true:
```sh
sudo npm install electron --unsafe-perm=true
```
On slower networks, it may be advisable to use the `--verbose` flag in order to
show download progress:
```sh
npm install --verbose electron
```
If you need to force a re-download of the asset and the SHASUM file set the
`force_no_cache` environment variable to `true`.
[npm]: https://docs.npmjs.com
[versioning]: ./electron-versioning.md
[npx]: https://docs.npmjs.com/cli/v7/commands/npx
[releases]: https://github.com/electron/electron/releases
[proxy-env-10]: https://github.com/gajus/global-agent/blob/v2.1.5/README.md#environment-variables
[proxy-env]: https://github.com/np-maintain/global-tunnel/blob/v2.7.1/README.md#auto-config
[electron-get]: https://github.com/electron/get
[npm-permissions]: https://docs.npmjs.com/getting-started/fixing-npm-permissions
[unsafe-perm]: https://docs.npmjs.com/misc/config#unsafe-perm
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.