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
34,887
Web Serial API removed and added events are never called
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.8 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.4 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to update UI when picking a port if a serial port is plugged in or unplugged. Test Steps: 1, Click button to call `navigator.serial.requestPort()` 2, Show a modal to show port list in the `select-serial-port` event handler 3, Plug in or unplug a device to check the `serial-port-added` and `serial-port-removed` events ``` modal.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { //Add listeners to handle ports being added or removed before the callback for `select-serial-port` //is called. modal.webContents.session.on('serial-port-added', (event, port) => { console.log('serial-port-added FIRED WITH', port) //Optionally update portList to add the new port }) modal.webContents.session.on('serial-port-removed', (event, port) => { console.log('serial-port-removed FIRED WITH', port) //Optionally update portList to remove the port }) // modal.webContents.openDevTools(); modal.webContents.send('update-list', portList); modal.show(); event.preventDefault(); ipcMain.once('serial-port', (_event, portId = '') => { callback(portId); modal.hide(); }); }); ``` ### Actual Behavior But the `select-serial-port` and `select-serial-removed` events never called. Did I use these api in a wrong way? ### Testcase Gist URL https://gist.github.com/0bbeeaa1c9e8f5affb6b59663870616e ### Additional Information _No response_
https://github.com/electron/electron/issues/34887
https://github.com/electron/electron/pull/34958
aeba6ca973c8ed8a8b75cceb4e0dde33f3595850
648c9934c01c12ea082a18fdf690c37e3112ce12
2022-07-12T03:31:13Z
c++
2022-07-25T14:50:19Z
shell/browser/serial/electron_serial_delegate.h
// Copyright (c) 2020 Microsoft, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_SERIAL_ELECTRON_SERIAL_DELEGATE_H_ #define ELECTRON_SHELL_BROWSER_SERIAL_ELECTRON_SERIAL_DELEGATE_H_ #include <memory> #include <unordered_map> #include <vector> #include "base/memory/weak_ptr.h" #include "content/public/browser/serial_delegate.h" #include "shell/browser/serial/serial_chooser_controller.h" namespace electron { class SerialChooserController; class ElectronSerialDelegate : public content::SerialDelegate { public: ElectronSerialDelegate(); ~ElectronSerialDelegate() override; // disable copy ElectronSerialDelegate(const ElectronSerialDelegate&) = delete; ElectronSerialDelegate& operator=(const ElectronSerialDelegate&) = delete; std::unique_ptr<content::SerialChooser> RunChooser( content::RenderFrameHost* frame, std::vector<blink::mojom::SerialPortFilterPtr> filters, content::SerialChooser::Callback callback) override; bool CanRequestPortPermission(content::RenderFrameHost* frame) override; bool HasPortPermission(content::RenderFrameHost* frame, const device::mojom::SerialPortInfo& port) override; device::mojom::SerialPortManager* GetPortManager( content::RenderFrameHost* frame) override; void AddObserver(content::RenderFrameHost* frame, Observer* observer) override; void RemoveObserver(content::RenderFrameHost* frame, Observer* observer) override; void RevokePortPermissionWebInitiated( content::RenderFrameHost* frame, const base::UnguessableToken& token) override; const device::mojom::SerialPortInfo* GetPortInfo( content::RenderFrameHost* frame, const base::UnguessableToken& token) override; void DeleteControllerForFrame(content::RenderFrameHost* render_frame_host); private: SerialChooserController* ControllerForFrame( content::RenderFrameHost* render_frame_host); SerialChooserController* AddControllerForFrame( content::RenderFrameHost* render_frame_host, std::vector<blink::mojom::SerialPortFilterPtr> filters, content::SerialChooser::Callback callback); std::unordered_map<content::RenderFrameHost*, std::unique_ptr<SerialChooserController>> controller_map_; base::WeakPtrFactory<ElectronSerialDelegate> weak_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_SERIAL_ELECTRON_SERIAL_DELEGATE_H_
closed
electron/electron
https://github.com/electron/electron
34,887
Web Serial API removed and added events are never called
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.8 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.4 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to update UI when picking a port if a serial port is plugged in or unplugged. Test Steps: 1, Click button to call `navigator.serial.requestPort()` 2, Show a modal to show port list in the `select-serial-port` event handler 3, Plug in or unplug a device to check the `serial-port-added` and `serial-port-removed` events ``` modal.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { //Add listeners to handle ports being added or removed before the callback for `select-serial-port` //is called. modal.webContents.session.on('serial-port-added', (event, port) => { console.log('serial-port-added FIRED WITH', port) //Optionally update portList to add the new port }) modal.webContents.session.on('serial-port-removed', (event, port) => { console.log('serial-port-removed FIRED WITH', port) //Optionally update portList to remove the port }) // modal.webContents.openDevTools(); modal.webContents.send('update-list', portList); modal.show(); event.preventDefault(); ipcMain.once('serial-port', (_event, portId = '') => { callback(portId); modal.hide(); }); }); ``` ### Actual Behavior But the `select-serial-port` and `select-serial-removed` events never called. Did I use these api in a wrong way? ### Testcase Gist URL https://gist.github.com/0bbeeaa1c9e8f5affb6b59663870616e ### Additional Information _No response_
https://github.com/electron/electron/issues/34887
https://github.com/electron/electron/pull/34958
aeba6ca973c8ed8a8b75cceb4e0dde33f3595850
648c9934c01c12ea082a18fdf690c37e3112ce12
2022-07-12T03:31:13Z
c++
2022-07-25T14:50:19Z
shell/browser/serial/serial_chooser_context.cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "shell/browser/serial/serial_chooser_context.h" #include <memory> #include <string> #include <utility> #include "base/base64.h" #include "base/containers/contains.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "content/public/browser/device_service.h" #include "content/public/browser/web_contents.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "shell/browser/electron_permission_manager.h" #include "shell/browser/web_contents_permission_helper.h" namespace electron { constexpr char kPortNameKey[] = "name"; constexpr char kTokenKey[] = "token"; #if BUILDFLAG(IS_WIN) const char kDeviceInstanceIdKey[] = "device_instance_id"; #else const char kVendorIdKey[] = "vendor_id"; const char kProductIdKey[] = "product_id"; const char kSerialNumberKey[] = "serial_number"; #if BUILDFLAG(IS_MAC) const char kUsbDriverKey[] = "usb_driver"; #endif // BUILDFLAG(IS_MAC) #endif // BUILDFLAG(IS_WIN) std::string EncodeToken(const base::UnguessableToken& token) { const uint64_t data[2] = {token.GetHighForSerialization(), token.GetLowForSerialization()}; std::string buffer; base::Base64Encode( base::StringPiece(reinterpret_cast<const char*>(&data[0]), sizeof(data)), &buffer); return buffer; } base::UnguessableToken DecodeToken(base::StringPiece input) { std::string buffer; if (!base::Base64Decode(input, &buffer) || buffer.length() != sizeof(uint64_t) * 2) { return base::UnguessableToken(); } const uint64_t* data = reinterpret_cast<const uint64_t*>(buffer.data()); return base::UnguessableToken::Deserialize(data[0], data[1]); } base::Value PortInfoToValue(const device::mojom::SerialPortInfo& port) { base::Value value(base::Value::Type::DICTIONARY); if (port.display_name && !port.display_name->empty()) value.SetStringKey(kPortNameKey, *port.display_name); else value.SetStringKey(kPortNameKey, port.path.LossyDisplayName()); if (!SerialChooserContext::CanStorePersistentEntry(port)) { value.SetStringKey(kTokenKey, EncodeToken(port.token)); return value; } #if BUILDFLAG(IS_WIN) // Windows provides a handy device identifier which we can rely on to be // sufficiently stable for identifying devices across restarts. value.SetStringKey(kDeviceInstanceIdKey, port.device_instance_id); #else DCHECK(port.has_vendor_id); value.SetIntKey(kVendorIdKey, port.vendor_id); DCHECK(port.has_product_id); value.SetIntKey(kProductIdKey, port.product_id); DCHECK(port.serial_number); value.SetStringKey(kSerialNumberKey, *port.serial_number); #if BUILDFLAG(IS_MAC) DCHECK(port.usb_driver_name && !port.usb_driver_name->empty()); value.SetStringKey(kUsbDriverKey, *port.usb_driver_name); #endif // BUILDFLAG(IS_MAC) #endif // BUILDFLAG(IS_WIN) return value; } SerialChooserContext::SerialChooserContext(ElectronBrowserContext* context) : browser_context_(context) {} SerialChooserContext::~SerialChooserContext() = default; void SerialChooserContext::OnPermissionRevoked(const url::Origin& origin) { for (auto& observer : port_observer_list_) observer.OnPermissionRevoked(origin); } void SerialChooserContext::GrantPortPermission( const url::Origin& origin, const device::mojom::SerialPortInfo& port, content::RenderFrameHost* render_frame_host) { auto* permission_manager = static_cast<ElectronPermissionManager*>( browser_context_->GetPermissionControllerDelegate()); return permission_manager->GrantDevicePermission( static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::SERIAL), origin, PortInfoToValue(port), browser_context_); } bool SerialChooserContext::HasPortPermission( const url::Origin& origin, const device::mojom::SerialPortInfo& port, content::RenderFrameHost* render_frame_host) { auto* permission_manager = static_cast<ElectronPermissionManager*>( browser_context_->GetPermissionControllerDelegate()); return permission_manager->CheckDevicePermission( static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::SERIAL), origin, PortInfoToValue(port), browser_context_); } void SerialChooserContext::RevokePortPermissionWebInitiated( const url::Origin& origin, const base::UnguessableToken& token) { auto it = port_info_.find(token); if (it == port_info_.end()) return; return OnPermissionRevoked(origin); } // static bool SerialChooserContext::CanStorePersistentEntry( const device::mojom::SerialPortInfo& port) { // If there is no display name then the path name will be used instead. The // path name is not guaranteed to be stable. For example, on Linux the name // "ttyUSB0" is reused for any USB serial device. A name like that would be // confusing to show in settings when the device is disconnected. if (!port.display_name || port.display_name->empty()) return false; #if BUILDFLAG(IS_WIN) return !port.device_instance_id.empty(); #else if (!port.has_vendor_id || !port.has_product_id || !port.serial_number || port.serial_number->empty()) { return false; } #if BUILDFLAG(IS_MAC) // The combination of the standard USB vendor ID, product ID and serial // number properties should be enough to uniquely identify a device // however recent versions of macOS include built-in drivers for common // types of USB-to-serial adapters while their manufacturers still // recommend installing their custom drivers. When both are loaded two // IOSerialBSDClient instances are found for each device. Including the // USB driver name allows us to distinguish between the two. if (!port.usb_driver_name || port.usb_driver_name->empty()) return false; #endif // BUILDFLAG(IS_MAC) return true; #endif // BUILDFLAG(IS_WIN) } const device::mojom::SerialPortInfo* SerialChooserContext::GetPortInfo( const base::UnguessableToken& token) { DCHECK(is_initialized_); auto it = port_info_.find(token); return it == port_info_.end() ? nullptr : it->second.get(); } device::mojom::SerialPortManager* SerialChooserContext::GetPortManager() { EnsurePortManagerConnection(); return port_manager_.get(); } void SerialChooserContext::AddPortObserver(PortObserver* observer) { port_observer_list_.AddObserver(observer); } void SerialChooserContext::RemovePortObserver(PortObserver* observer) { port_observer_list_.RemoveObserver(observer); } base::WeakPtr<SerialChooserContext> SerialChooserContext::AsWeakPtr() { return weak_factory_.GetWeakPtr(); } void SerialChooserContext::OnPortAdded(device::mojom::SerialPortInfoPtr port) { for (auto& observer : port_observer_list_) observer.OnPortAdded(*port); } void SerialChooserContext::OnPortRemoved( device::mojom::SerialPortInfoPtr port) { for (auto& observer : port_observer_list_) observer.OnPortRemoved(*port); } void SerialChooserContext::EnsurePortManagerConnection() { if (port_manager_) return; mojo::PendingRemote<device::mojom::SerialPortManager> manager; content::GetDeviceService().BindSerialPortManager( manager.InitWithNewPipeAndPassReceiver()); SetUpPortManagerConnection(std::move(manager)); } void SerialChooserContext::SetUpPortManagerConnection( mojo::PendingRemote<device::mojom::SerialPortManager> manager) { port_manager_.Bind(std::move(manager)); port_manager_.set_disconnect_handler( base::BindOnce(&SerialChooserContext::OnPortManagerConnectionError, base::Unretained(this))); port_manager_->SetClient(client_receiver_.BindNewPipeAndPassRemote()); } void SerialChooserContext::OnPortManagerConnectionError() { port_manager_.reset(); client_receiver_.reset(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,887
Web Serial API removed and added events are never called
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.8 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.4 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to update UI when picking a port if a serial port is plugged in or unplugged. Test Steps: 1, Click button to call `navigator.serial.requestPort()` 2, Show a modal to show port list in the `select-serial-port` event handler 3, Plug in or unplug a device to check the `serial-port-added` and `serial-port-removed` events ``` modal.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { //Add listeners to handle ports being added or removed before the callback for `select-serial-port` //is called. modal.webContents.session.on('serial-port-added', (event, port) => { console.log('serial-port-added FIRED WITH', port) //Optionally update portList to add the new port }) modal.webContents.session.on('serial-port-removed', (event, port) => { console.log('serial-port-removed FIRED WITH', port) //Optionally update portList to remove the port }) // modal.webContents.openDevTools(); modal.webContents.send('update-list', portList); modal.show(); event.preventDefault(); ipcMain.once('serial-port', (_event, portId = '') => { callback(portId); modal.hide(); }); }); ``` ### Actual Behavior But the `select-serial-port` and `select-serial-removed` events never called. Did I use these api in a wrong way? ### Testcase Gist URL https://gist.github.com/0bbeeaa1c9e8f5affb6b59663870616e ### Additional Information _No response_
https://github.com/electron/electron/issues/34887
https://github.com/electron/electron/pull/34958
aeba6ca973c8ed8a8b75cceb4e0dde33f3595850
648c9934c01c12ea082a18fdf690c37e3112ce12
2022-07-12T03:31:13Z
c++
2022-07-25T14:50:19Z
shell/browser/serial/serial_chooser_context.h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_SERIAL_SERIAL_CHOOSER_CONTEXT_H_ #define ELECTRON_SHELL_BROWSER_SERIAL_SERIAL_CHOOSER_CONTEXT_H_ #include <map> #include <set> #include <utility> #include <vector> #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/unguessable_token.h" #include "components/keyed_service/core/keyed_service.h" #include "content/public/browser/serial_delegate.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/serial.mojom-forward.h" #include "shell/browser/electron_browser_context.h" #include "third_party/blink/public/mojom/serial/serial.mojom.h" #include "url/gurl.h" #include "url/origin.h" namespace base { class Value; } namespace electron { extern const char kHidVendorIdKey[]; extern const char kHidProductIdKey[]; #if BUILDFLAG(IS_WIN) extern const char kDeviceInstanceIdKey[]; #else extern const char kVendorIdKey[]; extern const char kProductIdKey[]; extern const char kSerialNumberKey[]; #if BUILDFLAG(IS_MAC) extern const char kUsbDriverKey[]; #endif // BUILDFLAG(IS_MAC) #endif // BUILDFLAG(IS_WIN) class SerialChooserContext : public KeyedService, public device::mojom::SerialPortManagerClient { public: using PortObserver = content::SerialDelegate::Observer; explicit SerialChooserContext(ElectronBrowserContext* context); ~SerialChooserContext() override; // disable copy SerialChooserContext(const SerialChooserContext&) = delete; SerialChooserContext& operator=(const SerialChooserContext&) = delete; // ObjectPermissionContextBase::PermissionObserver: void OnPermissionRevoked(const url::Origin& origin); // Serial-specific interface for granting and checking permissions. void GrantPortPermission(const url::Origin& origin, const device::mojom::SerialPortInfo& port, content::RenderFrameHost* render_frame_host); bool HasPortPermission(const url::Origin& origin, const device::mojom::SerialPortInfo& port, content::RenderFrameHost* render_frame_host); static bool CanStorePersistentEntry( const device::mojom::SerialPortInfo& port); device::mojom::SerialPortManager* GetPortManager(); void AddPortObserver(PortObserver* observer); void RemovePortObserver(PortObserver* observer); base::WeakPtr<SerialChooserContext> AsWeakPtr(); bool is_initialized_ = false; // Map from port token to port info. std::map<base::UnguessableToken, device::mojom::SerialPortInfoPtr> port_info_; // SerialPortManagerClient implementation. void OnPortAdded(device::mojom::SerialPortInfoPtr port) override; void OnPortRemoved(device::mojom::SerialPortInfoPtr port) override; void RevokePortPermissionWebInitiated(const url::Origin& origin, const base::UnguessableToken& token); // Only call this if you're sure |port_info_| has been initialized // before-hand. The returned raw pointer is owned by |port_info_| and will be // destroyed when the port is removed. const device::mojom::SerialPortInfo* GetPortInfo( const base::UnguessableToken& token); private: void EnsurePortManagerConnection(); void SetUpPortManagerConnection( mojo::PendingRemote<device::mojom::SerialPortManager> manager); void OnPortManagerConnectionError(); void RevokeObjectPermissionInternal(const url::Origin& origin, const base::Value& object, bool revoked_by_website); mojo::Remote<device::mojom::SerialPortManager> port_manager_; mojo::Receiver<device::mojom::SerialPortManagerClient> client_receiver_{this}; base::ObserverList<PortObserver> port_observer_list_; ElectronBrowserContext* browser_context_; base::WeakPtrFactory<SerialChooserContext> weak_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_SERIAL_SERIAL_CHOOSER_CONTEXT_H_
closed
electron/electron
https://github.com/electron/electron
34,887
Web Serial API removed and added events are never called
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.8 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.4 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to update UI when picking a port if a serial port is plugged in or unplugged. Test Steps: 1, Click button to call `navigator.serial.requestPort()` 2, Show a modal to show port list in the `select-serial-port` event handler 3, Plug in or unplug a device to check the `serial-port-added` and `serial-port-removed` events ``` modal.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { //Add listeners to handle ports being added or removed before the callback for `select-serial-port` //is called. modal.webContents.session.on('serial-port-added', (event, port) => { console.log('serial-port-added FIRED WITH', port) //Optionally update portList to add the new port }) modal.webContents.session.on('serial-port-removed', (event, port) => { console.log('serial-port-removed FIRED WITH', port) //Optionally update portList to remove the port }) // modal.webContents.openDevTools(); modal.webContents.send('update-list', portList); modal.show(); event.preventDefault(); ipcMain.once('serial-port', (_event, portId = '') => { callback(portId); modal.hide(); }); }); ``` ### Actual Behavior But the `select-serial-port` and `select-serial-removed` events never called. Did I use these api in a wrong way? ### Testcase Gist URL https://gist.github.com/0bbeeaa1c9e8f5affb6b59663870616e ### Additional Information _No response_
https://github.com/electron/electron/issues/34887
https://github.com/electron/electron/pull/34958
aeba6ca973c8ed8a8b75cceb4e0dde33f3595850
648c9934c01c12ea082a18fdf690c37e3112ce12
2022-07-12T03:31:13Z
c++
2022-07-25T14:50:19Z
shell/browser/serial/serial_chooser_controller.cc
// Copyright (c) 2020 Microsoft, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/serial/serial_chooser_controller.h" #include <algorithm> #include <utility> #include "base/bind.h" #include "base/files/file_path.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/serial/serial_chooser_context.h" #include "shell/browser/serial/serial_chooser_context_factory.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/content_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "ui/base/l10n/l10n_util.h" namespace gin { template <> struct Converter<device::mojom::SerialPortInfoPtr> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const device::mojom::SerialPortInfoPtr& port) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); dict.Set("portId", port->token.ToString()); dict.Set("portName", port->path.BaseName().LossyDisplayName()); if (port->display_name && !port->display_name->empty()) { dict.Set("displayName", *port->display_name); } if (port->has_vendor_id) { dict.Set("vendorId", base::StringPrintf("%u", port->vendor_id)); } if (port->has_product_id) { dict.Set("productId", base::StringPrintf("%u", port->product_id)); } if (port->serial_number && !port->serial_number->empty()) { dict.Set("serialNumber", *port->serial_number); } #if BUILDFLAG(IS_MAC) if (port->usb_driver_name && !port->usb_driver_name->empty()) { dict.Set("usbDriverName", *port->usb_driver_name); } #elif BUILDFLAG(IS_WIN) if (!port->device_instance_id.empty()) { dict.Set("deviceInstanceId", port->device_instance_id); } #endif return gin::ConvertToV8(isolate, dict); } }; } // namespace gin namespace electron { SerialChooserController::SerialChooserController( content::RenderFrameHost* render_frame_host, std::vector<blink::mojom::SerialPortFilterPtr> filters, content::SerialChooser::Callback callback, content::WebContents* web_contents, base::WeakPtr<ElectronSerialDelegate> serial_delegate) : WebContentsObserver(web_contents), filters_(std::move(filters)), callback_(std::move(callback)), serial_delegate_(serial_delegate), render_frame_host_id_(render_frame_host->GetGlobalId()) { origin_ = web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin(); chooser_context_ = SerialChooserContextFactory::GetForBrowserContext( web_contents->GetBrowserContext()) ->AsWeakPtr(); DCHECK(chooser_context_); chooser_context_->GetPortManager()->GetDevices(base::BindOnce( &SerialChooserController::OnGetDevices, weak_factory_.GetWeakPtr())); } SerialChooserController::~SerialChooserController() { RunCallback(/*port=*/nullptr); if (chooser_context_) { chooser_context_->RemovePortObserver(this); } } api::Session* SerialChooserController::GetSession() { if (!web_contents()) { return nullptr; } return api::Session::FromBrowserContext(web_contents()->GetBrowserContext()); } void SerialChooserController::OnPortAdded( const device::mojom::SerialPortInfo& port) { ports_.push_back(port.Clone()); api::Session* session = GetSession(); if (session) { session->Emit("serial-port-added", port.Clone(), web_contents()); } } void SerialChooserController::OnPortRemoved( const device::mojom::SerialPortInfo& port) { const auto it = std::find_if( ports_.begin(), ports_.end(), [&port](const auto& ptr) { return ptr->token == port.token; }); if (it != ports_.end()) { api::Session* session = GetSession(); if (session) { session->Emit("serial-port-removed", port.Clone(), web_contents()); } ports_.erase(it); } } void SerialChooserController::OnPortManagerConnectionError() { // TODO(nornagon/jkleinsc): report event } void SerialChooserController::OnDeviceChosen(const std::string& port_id) { if (port_id.empty()) { RunCallback(/*port=*/nullptr); } else { const auto it = std::find_if(ports_.begin(), ports_.end(), [&port_id](const auto& ptr) { return ptr->token.ToString() == port_id; }); if (it != ports_.end()) { auto* rfh = content::RenderFrameHost::FromID(render_frame_host_id_); chooser_context_->GrantPortPermission(origin_, *it->get(), rfh); RunCallback(it->Clone()); } else { RunCallback(/*port=*/nullptr); } } } void SerialChooserController::OnGetDevices( std::vector<device::mojom::SerialPortInfoPtr> ports) { // Sort ports by file paths. std::sort(ports.begin(), ports.end(), [](const auto& port1, const auto& port2) { return port1->path.BaseName() < port2->path.BaseName(); }); for (auto& port : ports) { if (FilterMatchesAny(*port)) ports_.push_back(std::move(port)); } bool prevent_default = false; api::Session* session = GetSession(); if (session) { prevent_default = session->Emit("select-serial-port", ports_, web_contents(), base::AdaptCallbackForRepeating(base::BindOnce( &SerialChooserController::OnDeviceChosen, weak_factory_.GetWeakPtr()))); } if (!prevent_default) { RunCallback(/*port=*/nullptr); } } bool SerialChooserController::FilterMatchesAny( const device::mojom::SerialPortInfo& port) const { if (filters_.empty()) return true; for (const auto& filter : filters_) { if (filter->has_vendor_id && (!port.has_vendor_id || filter->vendor_id != port.vendor_id)) { continue; } if (filter->has_product_id && (!port.has_product_id || filter->product_id != port.product_id)) { continue; } return true; } return false; } void SerialChooserController::RunCallback( device::mojom::SerialPortInfoPtr port) { if (callback_) { std::move(callback_).Run(std::move(port)); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,887
Web Serial API removed and added events are never called
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.8 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.4 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to update UI when picking a port if a serial port is plugged in or unplugged. Test Steps: 1, Click button to call `navigator.serial.requestPort()` 2, Show a modal to show port list in the `select-serial-port` event handler 3, Plug in or unplug a device to check the `serial-port-added` and `serial-port-removed` events ``` modal.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { //Add listeners to handle ports being added or removed before the callback for `select-serial-port` //is called. modal.webContents.session.on('serial-port-added', (event, port) => { console.log('serial-port-added FIRED WITH', port) //Optionally update portList to add the new port }) modal.webContents.session.on('serial-port-removed', (event, port) => { console.log('serial-port-removed FIRED WITH', port) //Optionally update portList to remove the port }) // modal.webContents.openDevTools(); modal.webContents.send('update-list', portList); modal.show(); event.preventDefault(); ipcMain.once('serial-port', (_event, portId = '') => { callback(portId); modal.hide(); }); }); ``` ### Actual Behavior But the `select-serial-port` and `select-serial-removed` events never called. Did I use these api in a wrong way? ### Testcase Gist URL https://gist.github.com/0bbeeaa1c9e8f5affb6b59663870616e ### Additional Information _No response_
https://github.com/electron/electron/issues/34887
https://github.com/electron/electron/pull/34958
aeba6ca973c8ed8a8b75cceb4e0dde33f3595850
648c9934c01c12ea082a18fdf690c37e3112ce12
2022-07-12T03:31:13Z
c++
2022-07-25T14:50:19Z
shell/browser/serial/serial_chooser_controller.h
// Copyright (c) 2020 Microsoft, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_SERIAL_SERIAL_CHOOSER_CONTROLLER_H_ #define ELECTRON_SHELL_BROWSER_SERIAL_SERIAL_CHOOSER_CONTROLLER_H_ #include <string> #include <vector> #include "base/memory/weak_ptr.h" #include "content/public/browser/global_routing_id.h" #include "content/public/browser/serial_chooser.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" #include "services/device/public/mojom/serial.mojom-forward.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/serial/electron_serial_delegate.h" #include "shell/browser/serial/serial_chooser_context.h" #include "third_party/blink/public/mojom/serial/serial.mojom.h" namespace content { class RenderFrameHost; } namespace electron { class ElectronSerialDelegate; // SerialChooserController provides data for the Serial API permission prompt. class SerialChooserController final : public SerialChooserContext::PortObserver, public content::WebContentsObserver { public: SerialChooserController( content::RenderFrameHost* render_frame_host, std::vector<blink::mojom::SerialPortFilterPtr> filters, content::SerialChooser::Callback callback, content::WebContents* web_contents, base::WeakPtr<ElectronSerialDelegate> serial_delegate); ~SerialChooserController() override; // disable copy SerialChooserController(const SerialChooserController&) = delete; SerialChooserController& operator=(const SerialChooserController&) = delete; // SerialChooserContext::PortObserver: void OnPortAdded(const device::mojom::SerialPortInfo& port) override; void OnPortRemoved(const device::mojom::SerialPortInfo& port) override; void OnPortManagerConnectionError() override; void OnPermissionRevoked(const url::Origin& origin) override {} private: api::Session* GetSession(); void OnGetDevices(std::vector<device::mojom::SerialPortInfoPtr> ports); bool FilterMatchesAny(const device::mojom::SerialPortInfo& port) const; void RunCallback(device::mojom::SerialPortInfoPtr port); void OnDeviceChosen(const std::string& port_id); std::vector<blink::mojom::SerialPortFilterPtr> filters_; content::SerialChooser::Callback callback_; url::Origin origin_; base::WeakPtr<SerialChooserContext> chooser_context_; std::vector<device::mojom::SerialPortInfoPtr> ports_; base::WeakPtr<ElectronSerialDelegate> serial_delegate_; content::GlobalRenderFrameHostId render_frame_host_id_; base::WeakPtrFactory<SerialChooserController> weak_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_SERIAL_SERIAL_CHOOSER_CONTROLLER_H_
closed
electron/electron
https://github.com/electron/electron
34,887
Web Serial API removed and added events are never called
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.8 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.4 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to update UI when picking a port if a serial port is plugged in or unplugged. Test Steps: 1, Click button to call `navigator.serial.requestPort()` 2, Show a modal to show port list in the `select-serial-port` event handler 3, Plug in or unplug a device to check the `serial-port-added` and `serial-port-removed` events ``` modal.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { //Add listeners to handle ports being added or removed before the callback for `select-serial-port` //is called. modal.webContents.session.on('serial-port-added', (event, port) => { console.log('serial-port-added FIRED WITH', port) //Optionally update portList to add the new port }) modal.webContents.session.on('serial-port-removed', (event, port) => { console.log('serial-port-removed FIRED WITH', port) //Optionally update portList to remove the port }) // modal.webContents.openDevTools(); modal.webContents.send('update-list', portList); modal.show(); event.preventDefault(); ipcMain.once('serial-port', (_event, portId = '') => { callback(portId); modal.hide(); }); }); ``` ### Actual Behavior But the `select-serial-port` and `select-serial-removed` events never called. Did I use these api in a wrong way? ### Testcase Gist URL https://gist.github.com/0bbeeaa1c9e8f5affb6b59663870616e ### Additional Information _No response_
https://github.com/electron/electron/issues/34887
https://github.com/electron/electron/pull/34958
aeba6ca973c8ed8a8b75cceb4e0dde33f3595850
648c9934c01c12ea082a18fdf690c37e3112ce12
2022-07-12T03:31:13Z
c++
2022-07-25T14:50:19Z
shell/browser/serial/electron_serial_delegate.cc
// Copyright (c) 2020 Microsoft, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/serial/electron_serial_delegate.h" #include <utility> #include "base/feature_list.h" #include "content/public/browser/web_contents.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/serial/serial_chooser_context.h" #include "shell/browser/serial/serial_chooser_context_factory.h" #include "shell/browser/serial/serial_chooser_controller.h" #include "shell/browser/web_contents_permission_helper.h" namespace electron { SerialChooserContext* GetChooserContext(content::RenderFrameHost* frame) { auto* web_contents = content::WebContents::FromRenderFrameHost(frame); auto* browser_context = web_contents->GetBrowserContext(); return SerialChooserContextFactory::GetForBrowserContext(browser_context); } ElectronSerialDelegate::ElectronSerialDelegate() = default; ElectronSerialDelegate::~ElectronSerialDelegate() = default; std::unique_ptr<content::SerialChooser> ElectronSerialDelegate::RunChooser( content::RenderFrameHost* frame, std::vector<blink::mojom::SerialPortFilterPtr> filters, content::SerialChooser::Callback callback) { SerialChooserController* controller = ControllerForFrame(frame); if (controller) { DeleteControllerForFrame(frame); } AddControllerForFrame(frame, std::move(filters), std::move(callback)); // Return a nullptr because the return value isn't used for anything, eg // there is no mechanism to cancel navigator.serial.requestPort(). The return // value is simply used in Chromium to cleanup the chooser UI once the serial // service is destroyed. return nullptr; } bool ElectronSerialDelegate::CanRequestPortPermission( content::RenderFrameHost* frame) { auto* web_contents = content::WebContents::FromRenderFrameHost(frame); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckSerialAccessPermission( web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin()); } bool ElectronSerialDelegate::HasPortPermission( content::RenderFrameHost* frame, const device::mojom::SerialPortInfo& port) { auto* web_contents = content::WebContents::FromRenderFrameHost(frame); auto* browser_context = web_contents->GetBrowserContext(); auto* chooser_context = SerialChooserContextFactory::GetForBrowserContext(browser_context); return chooser_context->HasPortPermission( web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin(), port, frame); } device::mojom::SerialPortManager* ElectronSerialDelegate::GetPortManager( content::RenderFrameHost* frame) { return GetChooserContext(frame)->GetPortManager(); } void ElectronSerialDelegate::AddObserver(content::RenderFrameHost* frame, Observer* observer) { return GetChooserContext(frame)->AddPortObserver(observer); } void ElectronSerialDelegate::RemoveObserver(content::RenderFrameHost* frame, Observer* observer) { SerialChooserContext* serial_chooser_context = GetChooserContext(frame); if (serial_chooser_context) { return serial_chooser_context->RemovePortObserver(observer); } } void ElectronSerialDelegate::RevokePortPermissionWebInitiated( content::RenderFrameHost* frame, const base::UnguessableToken& token) { // TODO(nornagon/jkleinsc): pass this on to the chooser context } const device::mojom::SerialPortInfo* ElectronSerialDelegate::GetPortInfo( content::RenderFrameHost* frame, const base::UnguessableToken& token) { // TODO(nornagon/jkleinsc): pass this on to the chooser context return nullptr; } SerialChooserController* ElectronSerialDelegate::ControllerForFrame( content::RenderFrameHost* render_frame_host) { auto mapping = controller_map_.find(render_frame_host); return mapping == controller_map_.end() ? nullptr : mapping->second.get(); } SerialChooserController* ElectronSerialDelegate::AddControllerForFrame( content::RenderFrameHost* render_frame_host, std::vector<blink::mojom::SerialPortFilterPtr> filters, content::SerialChooser::Callback callback) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto controller = std::make_unique<SerialChooserController>( render_frame_host, std::move(filters), 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 ElectronSerialDelegate::DeleteControllerForFrame( content::RenderFrameHost* render_frame_host) { controller_map_.erase(render_frame_host); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,887
Web Serial API removed and added events are never called
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.8 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.4 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to update UI when picking a port if a serial port is plugged in or unplugged. Test Steps: 1, Click button to call `navigator.serial.requestPort()` 2, Show a modal to show port list in the `select-serial-port` event handler 3, Plug in or unplug a device to check the `serial-port-added` and `serial-port-removed` events ``` modal.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { //Add listeners to handle ports being added or removed before the callback for `select-serial-port` //is called. modal.webContents.session.on('serial-port-added', (event, port) => { console.log('serial-port-added FIRED WITH', port) //Optionally update portList to add the new port }) modal.webContents.session.on('serial-port-removed', (event, port) => { console.log('serial-port-removed FIRED WITH', port) //Optionally update portList to remove the port }) // modal.webContents.openDevTools(); modal.webContents.send('update-list', portList); modal.show(); event.preventDefault(); ipcMain.once('serial-port', (_event, portId = '') => { callback(portId); modal.hide(); }); }); ``` ### Actual Behavior But the `select-serial-port` and `select-serial-removed` events never called. Did I use these api in a wrong way? ### Testcase Gist URL https://gist.github.com/0bbeeaa1c9e8f5affb6b59663870616e ### Additional Information _No response_
https://github.com/electron/electron/issues/34887
https://github.com/electron/electron/pull/34958
aeba6ca973c8ed8a8b75cceb4e0dde33f3595850
648c9934c01c12ea082a18fdf690c37e3112ce12
2022-07-12T03:31:13Z
c++
2022-07-25T14:50:19Z
shell/browser/serial/electron_serial_delegate.h
// Copyright (c) 2020 Microsoft, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_SERIAL_ELECTRON_SERIAL_DELEGATE_H_ #define ELECTRON_SHELL_BROWSER_SERIAL_ELECTRON_SERIAL_DELEGATE_H_ #include <memory> #include <unordered_map> #include <vector> #include "base/memory/weak_ptr.h" #include "content/public/browser/serial_delegate.h" #include "shell/browser/serial/serial_chooser_controller.h" namespace electron { class SerialChooserController; class ElectronSerialDelegate : public content::SerialDelegate { public: ElectronSerialDelegate(); ~ElectronSerialDelegate() override; // disable copy ElectronSerialDelegate(const ElectronSerialDelegate&) = delete; ElectronSerialDelegate& operator=(const ElectronSerialDelegate&) = delete; std::unique_ptr<content::SerialChooser> RunChooser( content::RenderFrameHost* frame, std::vector<blink::mojom::SerialPortFilterPtr> filters, content::SerialChooser::Callback callback) override; bool CanRequestPortPermission(content::RenderFrameHost* frame) override; bool HasPortPermission(content::RenderFrameHost* frame, const device::mojom::SerialPortInfo& port) override; device::mojom::SerialPortManager* GetPortManager( content::RenderFrameHost* frame) override; void AddObserver(content::RenderFrameHost* frame, Observer* observer) override; void RemoveObserver(content::RenderFrameHost* frame, Observer* observer) override; void RevokePortPermissionWebInitiated( content::RenderFrameHost* frame, const base::UnguessableToken& token) override; const device::mojom::SerialPortInfo* GetPortInfo( content::RenderFrameHost* frame, const base::UnguessableToken& token) override; void DeleteControllerForFrame(content::RenderFrameHost* render_frame_host); private: SerialChooserController* ControllerForFrame( content::RenderFrameHost* render_frame_host); SerialChooserController* AddControllerForFrame( content::RenderFrameHost* render_frame_host, std::vector<blink::mojom::SerialPortFilterPtr> filters, content::SerialChooser::Callback callback); std::unordered_map<content::RenderFrameHost*, std::unique_ptr<SerialChooserController>> controller_map_; base::WeakPtrFactory<ElectronSerialDelegate> weak_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_SERIAL_ELECTRON_SERIAL_DELEGATE_H_
closed
electron/electron
https://github.com/electron/electron
34,887
Web Serial API removed and added events are never called
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.8 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.4 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to update UI when picking a port if a serial port is plugged in or unplugged. Test Steps: 1, Click button to call `navigator.serial.requestPort()` 2, Show a modal to show port list in the `select-serial-port` event handler 3, Plug in or unplug a device to check the `serial-port-added` and `serial-port-removed` events ``` modal.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { //Add listeners to handle ports being added or removed before the callback for `select-serial-port` //is called. modal.webContents.session.on('serial-port-added', (event, port) => { console.log('serial-port-added FIRED WITH', port) //Optionally update portList to add the new port }) modal.webContents.session.on('serial-port-removed', (event, port) => { console.log('serial-port-removed FIRED WITH', port) //Optionally update portList to remove the port }) // modal.webContents.openDevTools(); modal.webContents.send('update-list', portList); modal.show(); event.preventDefault(); ipcMain.once('serial-port', (_event, portId = '') => { callback(portId); modal.hide(); }); }); ``` ### Actual Behavior But the `select-serial-port` and `select-serial-removed` events never called. Did I use these api in a wrong way? ### Testcase Gist URL https://gist.github.com/0bbeeaa1c9e8f5affb6b59663870616e ### Additional Information _No response_
https://github.com/electron/electron/issues/34887
https://github.com/electron/electron/pull/34958
aeba6ca973c8ed8a8b75cceb4e0dde33f3595850
648c9934c01c12ea082a18fdf690c37e3112ce12
2022-07-12T03:31:13Z
c++
2022-07-25T14:50:19Z
shell/browser/serial/serial_chooser_context.cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "shell/browser/serial/serial_chooser_context.h" #include <memory> #include <string> #include <utility> #include "base/base64.h" #include "base/containers/contains.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "content/public/browser/device_service.h" #include "content/public/browser/web_contents.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "shell/browser/electron_permission_manager.h" #include "shell/browser/web_contents_permission_helper.h" namespace electron { constexpr char kPortNameKey[] = "name"; constexpr char kTokenKey[] = "token"; #if BUILDFLAG(IS_WIN) const char kDeviceInstanceIdKey[] = "device_instance_id"; #else const char kVendorIdKey[] = "vendor_id"; const char kProductIdKey[] = "product_id"; const char kSerialNumberKey[] = "serial_number"; #if BUILDFLAG(IS_MAC) const char kUsbDriverKey[] = "usb_driver"; #endif // BUILDFLAG(IS_MAC) #endif // BUILDFLAG(IS_WIN) std::string EncodeToken(const base::UnguessableToken& token) { const uint64_t data[2] = {token.GetHighForSerialization(), token.GetLowForSerialization()}; std::string buffer; base::Base64Encode( base::StringPiece(reinterpret_cast<const char*>(&data[0]), sizeof(data)), &buffer); return buffer; } base::UnguessableToken DecodeToken(base::StringPiece input) { std::string buffer; if (!base::Base64Decode(input, &buffer) || buffer.length() != sizeof(uint64_t) * 2) { return base::UnguessableToken(); } const uint64_t* data = reinterpret_cast<const uint64_t*>(buffer.data()); return base::UnguessableToken::Deserialize(data[0], data[1]); } base::Value PortInfoToValue(const device::mojom::SerialPortInfo& port) { base::Value value(base::Value::Type::DICTIONARY); if (port.display_name && !port.display_name->empty()) value.SetStringKey(kPortNameKey, *port.display_name); else value.SetStringKey(kPortNameKey, port.path.LossyDisplayName()); if (!SerialChooserContext::CanStorePersistentEntry(port)) { value.SetStringKey(kTokenKey, EncodeToken(port.token)); return value; } #if BUILDFLAG(IS_WIN) // Windows provides a handy device identifier which we can rely on to be // sufficiently stable for identifying devices across restarts. value.SetStringKey(kDeviceInstanceIdKey, port.device_instance_id); #else DCHECK(port.has_vendor_id); value.SetIntKey(kVendorIdKey, port.vendor_id); DCHECK(port.has_product_id); value.SetIntKey(kProductIdKey, port.product_id); DCHECK(port.serial_number); value.SetStringKey(kSerialNumberKey, *port.serial_number); #if BUILDFLAG(IS_MAC) DCHECK(port.usb_driver_name && !port.usb_driver_name->empty()); value.SetStringKey(kUsbDriverKey, *port.usb_driver_name); #endif // BUILDFLAG(IS_MAC) #endif // BUILDFLAG(IS_WIN) return value; } SerialChooserContext::SerialChooserContext(ElectronBrowserContext* context) : browser_context_(context) {} SerialChooserContext::~SerialChooserContext() = default; void SerialChooserContext::OnPermissionRevoked(const url::Origin& origin) { for (auto& observer : port_observer_list_) observer.OnPermissionRevoked(origin); } void SerialChooserContext::GrantPortPermission( const url::Origin& origin, const device::mojom::SerialPortInfo& port, content::RenderFrameHost* render_frame_host) { auto* permission_manager = static_cast<ElectronPermissionManager*>( browser_context_->GetPermissionControllerDelegate()); return permission_manager->GrantDevicePermission( static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::SERIAL), origin, PortInfoToValue(port), browser_context_); } bool SerialChooserContext::HasPortPermission( const url::Origin& origin, const device::mojom::SerialPortInfo& port, content::RenderFrameHost* render_frame_host) { auto* permission_manager = static_cast<ElectronPermissionManager*>( browser_context_->GetPermissionControllerDelegate()); return permission_manager->CheckDevicePermission( static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::SERIAL), origin, PortInfoToValue(port), browser_context_); } void SerialChooserContext::RevokePortPermissionWebInitiated( const url::Origin& origin, const base::UnguessableToken& token) { auto it = port_info_.find(token); if (it == port_info_.end()) return; return OnPermissionRevoked(origin); } // static bool SerialChooserContext::CanStorePersistentEntry( const device::mojom::SerialPortInfo& port) { // If there is no display name then the path name will be used instead. The // path name is not guaranteed to be stable. For example, on Linux the name // "ttyUSB0" is reused for any USB serial device. A name like that would be // confusing to show in settings when the device is disconnected. if (!port.display_name || port.display_name->empty()) return false; #if BUILDFLAG(IS_WIN) return !port.device_instance_id.empty(); #else if (!port.has_vendor_id || !port.has_product_id || !port.serial_number || port.serial_number->empty()) { return false; } #if BUILDFLAG(IS_MAC) // The combination of the standard USB vendor ID, product ID and serial // number properties should be enough to uniquely identify a device // however recent versions of macOS include built-in drivers for common // types of USB-to-serial adapters while their manufacturers still // recommend installing their custom drivers. When both are loaded two // IOSerialBSDClient instances are found for each device. Including the // USB driver name allows us to distinguish between the two. if (!port.usb_driver_name || port.usb_driver_name->empty()) return false; #endif // BUILDFLAG(IS_MAC) return true; #endif // BUILDFLAG(IS_WIN) } const device::mojom::SerialPortInfo* SerialChooserContext::GetPortInfo( const base::UnguessableToken& token) { DCHECK(is_initialized_); auto it = port_info_.find(token); return it == port_info_.end() ? nullptr : it->second.get(); } device::mojom::SerialPortManager* SerialChooserContext::GetPortManager() { EnsurePortManagerConnection(); return port_manager_.get(); } void SerialChooserContext::AddPortObserver(PortObserver* observer) { port_observer_list_.AddObserver(observer); } void SerialChooserContext::RemovePortObserver(PortObserver* observer) { port_observer_list_.RemoveObserver(observer); } base::WeakPtr<SerialChooserContext> SerialChooserContext::AsWeakPtr() { return weak_factory_.GetWeakPtr(); } void SerialChooserContext::OnPortAdded(device::mojom::SerialPortInfoPtr port) { for (auto& observer : port_observer_list_) observer.OnPortAdded(*port); } void SerialChooserContext::OnPortRemoved( device::mojom::SerialPortInfoPtr port) { for (auto& observer : port_observer_list_) observer.OnPortRemoved(*port); } void SerialChooserContext::EnsurePortManagerConnection() { if (port_manager_) return; mojo::PendingRemote<device::mojom::SerialPortManager> manager; content::GetDeviceService().BindSerialPortManager( manager.InitWithNewPipeAndPassReceiver()); SetUpPortManagerConnection(std::move(manager)); } void SerialChooserContext::SetUpPortManagerConnection( mojo::PendingRemote<device::mojom::SerialPortManager> manager) { port_manager_.Bind(std::move(manager)); port_manager_.set_disconnect_handler( base::BindOnce(&SerialChooserContext::OnPortManagerConnectionError, base::Unretained(this))); port_manager_->SetClient(client_receiver_.BindNewPipeAndPassRemote()); } void SerialChooserContext::OnPortManagerConnectionError() { port_manager_.reset(); client_receiver_.reset(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,887
Web Serial API removed and added events are never called
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.8 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.4 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to update UI when picking a port if a serial port is plugged in or unplugged. Test Steps: 1, Click button to call `navigator.serial.requestPort()` 2, Show a modal to show port list in the `select-serial-port` event handler 3, Plug in or unplug a device to check the `serial-port-added` and `serial-port-removed` events ``` modal.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { //Add listeners to handle ports being added or removed before the callback for `select-serial-port` //is called. modal.webContents.session.on('serial-port-added', (event, port) => { console.log('serial-port-added FIRED WITH', port) //Optionally update portList to add the new port }) modal.webContents.session.on('serial-port-removed', (event, port) => { console.log('serial-port-removed FIRED WITH', port) //Optionally update portList to remove the port }) // modal.webContents.openDevTools(); modal.webContents.send('update-list', portList); modal.show(); event.preventDefault(); ipcMain.once('serial-port', (_event, portId = '') => { callback(portId); modal.hide(); }); }); ``` ### Actual Behavior But the `select-serial-port` and `select-serial-removed` events never called. Did I use these api in a wrong way? ### Testcase Gist URL https://gist.github.com/0bbeeaa1c9e8f5affb6b59663870616e ### Additional Information _No response_
https://github.com/electron/electron/issues/34887
https://github.com/electron/electron/pull/34958
aeba6ca973c8ed8a8b75cceb4e0dde33f3595850
648c9934c01c12ea082a18fdf690c37e3112ce12
2022-07-12T03:31:13Z
c++
2022-07-25T14:50:19Z
shell/browser/serial/serial_chooser_context.h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_SERIAL_SERIAL_CHOOSER_CONTEXT_H_ #define ELECTRON_SHELL_BROWSER_SERIAL_SERIAL_CHOOSER_CONTEXT_H_ #include <map> #include <set> #include <utility> #include <vector> #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/unguessable_token.h" #include "components/keyed_service/core/keyed_service.h" #include "content/public/browser/serial_delegate.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/serial.mojom-forward.h" #include "shell/browser/electron_browser_context.h" #include "third_party/blink/public/mojom/serial/serial.mojom.h" #include "url/gurl.h" #include "url/origin.h" namespace base { class Value; } namespace electron { extern const char kHidVendorIdKey[]; extern const char kHidProductIdKey[]; #if BUILDFLAG(IS_WIN) extern const char kDeviceInstanceIdKey[]; #else extern const char kVendorIdKey[]; extern const char kProductIdKey[]; extern const char kSerialNumberKey[]; #if BUILDFLAG(IS_MAC) extern const char kUsbDriverKey[]; #endif // BUILDFLAG(IS_MAC) #endif // BUILDFLAG(IS_WIN) class SerialChooserContext : public KeyedService, public device::mojom::SerialPortManagerClient { public: using PortObserver = content::SerialDelegate::Observer; explicit SerialChooserContext(ElectronBrowserContext* context); ~SerialChooserContext() override; // disable copy SerialChooserContext(const SerialChooserContext&) = delete; SerialChooserContext& operator=(const SerialChooserContext&) = delete; // ObjectPermissionContextBase::PermissionObserver: void OnPermissionRevoked(const url::Origin& origin); // Serial-specific interface for granting and checking permissions. void GrantPortPermission(const url::Origin& origin, const device::mojom::SerialPortInfo& port, content::RenderFrameHost* render_frame_host); bool HasPortPermission(const url::Origin& origin, const device::mojom::SerialPortInfo& port, content::RenderFrameHost* render_frame_host); static bool CanStorePersistentEntry( const device::mojom::SerialPortInfo& port); device::mojom::SerialPortManager* GetPortManager(); void AddPortObserver(PortObserver* observer); void RemovePortObserver(PortObserver* observer); base::WeakPtr<SerialChooserContext> AsWeakPtr(); bool is_initialized_ = false; // Map from port token to port info. std::map<base::UnguessableToken, device::mojom::SerialPortInfoPtr> port_info_; // SerialPortManagerClient implementation. void OnPortAdded(device::mojom::SerialPortInfoPtr port) override; void OnPortRemoved(device::mojom::SerialPortInfoPtr port) override; void RevokePortPermissionWebInitiated(const url::Origin& origin, const base::UnguessableToken& token); // Only call this if you're sure |port_info_| has been initialized // before-hand. The returned raw pointer is owned by |port_info_| and will be // destroyed when the port is removed. const device::mojom::SerialPortInfo* GetPortInfo( const base::UnguessableToken& token); private: void EnsurePortManagerConnection(); void SetUpPortManagerConnection( mojo::PendingRemote<device::mojom::SerialPortManager> manager); void OnPortManagerConnectionError(); void RevokeObjectPermissionInternal(const url::Origin& origin, const base::Value& object, bool revoked_by_website); mojo::Remote<device::mojom::SerialPortManager> port_manager_; mojo::Receiver<device::mojom::SerialPortManagerClient> client_receiver_{this}; base::ObserverList<PortObserver> port_observer_list_; ElectronBrowserContext* browser_context_; base::WeakPtrFactory<SerialChooserContext> weak_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_SERIAL_SERIAL_CHOOSER_CONTEXT_H_
closed
electron/electron
https://github.com/electron/electron
34,887
Web Serial API removed and added events are never called
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.8 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.4 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to update UI when picking a port if a serial port is plugged in or unplugged. Test Steps: 1, Click button to call `navigator.serial.requestPort()` 2, Show a modal to show port list in the `select-serial-port` event handler 3, Plug in or unplug a device to check the `serial-port-added` and `serial-port-removed` events ``` modal.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { //Add listeners to handle ports being added or removed before the callback for `select-serial-port` //is called. modal.webContents.session.on('serial-port-added', (event, port) => { console.log('serial-port-added FIRED WITH', port) //Optionally update portList to add the new port }) modal.webContents.session.on('serial-port-removed', (event, port) => { console.log('serial-port-removed FIRED WITH', port) //Optionally update portList to remove the port }) // modal.webContents.openDevTools(); modal.webContents.send('update-list', portList); modal.show(); event.preventDefault(); ipcMain.once('serial-port', (_event, portId = '') => { callback(portId); modal.hide(); }); }); ``` ### Actual Behavior But the `select-serial-port` and `select-serial-removed` events never called. Did I use these api in a wrong way? ### Testcase Gist URL https://gist.github.com/0bbeeaa1c9e8f5affb6b59663870616e ### Additional Information _No response_
https://github.com/electron/electron/issues/34887
https://github.com/electron/electron/pull/34958
aeba6ca973c8ed8a8b75cceb4e0dde33f3595850
648c9934c01c12ea082a18fdf690c37e3112ce12
2022-07-12T03:31:13Z
c++
2022-07-25T14:50:19Z
shell/browser/serial/serial_chooser_controller.cc
// Copyright (c) 2020 Microsoft, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/serial/serial_chooser_controller.h" #include <algorithm> #include <utility> #include "base/bind.h" #include "base/files/file_path.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/serial/serial_chooser_context.h" #include "shell/browser/serial/serial_chooser_context_factory.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/content_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "ui/base/l10n/l10n_util.h" namespace gin { template <> struct Converter<device::mojom::SerialPortInfoPtr> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const device::mojom::SerialPortInfoPtr& port) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); dict.Set("portId", port->token.ToString()); dict.Set("portName", port->path.BaseName().LossyDisplayName()); if (port->display_name && !port->display_name->empty()) { dict.Set("displayName", *port->display_name); } if (port->has_vendor_id) { dict.Set("vendorId", base::StringPrintf("%u", port->vendor_id)); } if (port->has_product_id) { dict.Set("productId", base::StringPrintf("%u", port->product_id)); } if (port->serial_number && !port->serial_number->empty()) { dict.Set("serialNumber", *port->serial_number); } #if BUILDFLAG(IS_MAC) if (port->usb_driver_name && !port->usb_driver_name->empty()) { dict.Set("usbDriverName", *port->usb_driver_name); } #elif BUILDFLAG(IS_WIN) if (!port->device_instance_id.empty()) { dict.Set("deviceInstanceId", port->device_instance_id); } #endif return gin::ConvertToV8(isolate, dict); } }; } // namespace gin namespace electron { SerialChooserController::SerialChooserController( content::RenderFrameHost* render_frame_host, std::vector<blink::mojom::SerialPortFilterPtr> filters, content::SerialChooser::Callback callback, content::WebContents* web_contents, base::WeakPtr<ElectronSerialDelegate> serial_delegate) : WebContentsObserver(web_contents), filters_(std::move(filters)), callback_(std::move(callback)), serial_delegate_(serial_delegate), render_frame_host_id_(render_frame_host->GetGlobalId()) { origin_ = web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin(); chooser_context_ = SerialChooserContextFactory::GetForBrowserContext( web_contents->GetBrowserContext()) ->AsWeakPtr(); DCHECK(chooser_context_); chooser_context_->GetPortManager()->GetDevices(base::BindOnce( &SerialChooserController::OnGetDevices, weak_factory_.GetWeakPtr())); } SerialChooserController::~SerialChooserController() { RunCallback(/*port=*/nullptr); if (chooser_context_) { chooser_context_->RemovePortObserver(this); } } api::Session* SerialChooserController::GetSession() { if (!web_contents()) { return nullptr; } return api::Session::FromBrowserContext(web_contents()->GetBrowserContext()); } void SerialChooserController::OnPortAdded( const device::mojom::SerialPortInfo& port) { ports_.push_back(port.Clone()); api::Session* session = GetSession(); if (session) { session->Emit("serial-port-added", port.Clone(), web_contents()); } } void SerialChooserController::OnPortRemoved( const device::mojom::SerialPortInfo& port) { const auto it = std::find_if( ports_.begin(), ports_.end(), [&port](const auto& ptr) { return ptr->token == port.token; }); if (it != ports_.end()) { api::Session* session = GetSession(); if (session) { session->Emit("serial-port-removed", port.Clone(), web_contents()); } ports_.erase(it); } } void SerialChooserController::OnPortManagerConnectionError() { // TODO(nornagon/jkleinsc): report event } void SerialChooserController::OnDeviceChosen(const std::string& port_id) { if (port_id.empty()) { RunCallback(/*port=*/nullptr); } else { const auto it = std::find_if(ports_.begin(), ports_.end(), [&port_id](const auto& ptr) { return ptr->token.ToString() == port_id; }); if (it != ports_.end()) { auto* rfh = content::RenderFrameHost::FromID(render_frame_host_id_); chooser_context_->GrantPortPermission(origin_, *it->get(), rfh); RunCallback(it->Clone()); } else { RunCallback(/*port=*/nullptr); } } } void SerialChooserController::OnGetDevices( std::vector<device::mojom::SerialPortInfoPtr> ports) { // Sort ports by file paths. std::sort(ports.begin(), ports.end(), [](const auto& port1, const auto& port2) { return port1->path.BaseName() < port2->path.BaseName(); }); for (auto& port : ports) { if (FilterMatchesAny(*port)) ports_.push_back(std::move(port)); } bool prevent_default = false; api::Session* session = GetSession(); if (session) { prevent_default = session->Emit("select-serial-port", ports_, web_contents(), base::AdaptCallbackForRepeating(base::BindOnce( &SerialChooserController::OnDeviceChosen, weak_factory_.GetWeakPtr()))); } if (!prevent_default) { RunCallback(/*port=*/nullptr); } } bool SerialChooserController::FilterMatchesAny( const device::mojom::SerialPortInfo& port) const { if (filters_.empty()) return true; for (const auto& filter : filters_) { if (filter->has_vendor_id && (!port.has_vendor_id || filter->vendor_id != port.vendor_id)) { continue; } if (filter->has_product_id && (!port.has_product_id || filter->product_id != port.product_id)) { continue; } return true; } return false; } void SerialChooserController::RunCallback( device::mojom::SerialPortInfoPtr port) { if (callback_) { std::move(callback_).Run(std::move(port)); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,887
Web Serial API removed and added events are never called
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.8 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.4 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to update UI when picking a port if a serial port is plugged in or unplugged. Test Steps: 1, Click button to call `navigator.serial.requestPort()` 2, Show a modal to show port list in the `select-serial-port` event handler 3, Plug in or unplug a device to check the `serial-port-added` and `serial-port-removed` events ``` modal.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { //Add listeners to handle ports being added or removed before the callback for `select-serial-port` //is called. modal.webContents.session.on('serial-port-added', (event, port) => { console.log('serial-port-added FIRED WITH', port) //Optionally update portList to add the new port }) modal.webContents.session.on('serial-port-removed', (event, port) => { console.log('serial-port-removed FIRED WITH', port) //Optionally update portList to remove the port }) // modal.webContents.openDevTools(); modal.webContents.send('update-list', portList); modal.show(); event.preventDefault(); ipcMain.once('serial-port', (_event, portId = '') => { callback(portId); modal.hide(); }); }); ``` ### Actual Behavior But the `select-serial-port` and `select-serial-removed` events never called. Did I use these api in a wrong way? ### Testcase Gist URL https://gist.github.com/0bbeeaa1c9e8f5affb6b59663870616e ### Additional Information _No response_
https://github.com/electron/electron/issues/34887
https://github.com/electron/electron/pull/34958
aeba6ca973c8ed8a8b75cceb4e0dde33f3595850
648c9934c01c12ea082a18fdf690c37e3112ce12
2022-07-12T03:31:13Z
c++
2022-07-25T14:50:19Z
shell/browser/serial/serial_chooser_controller.h
// Copyright (c) 2020 Microsoft, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_SERIAL_SERIAL_CHOOSER_CONTROLLER_H_ #define ELECTRON_SHELL_BROWSER_SERIAL_SERIAL_CHOOSER_CONTROLLER_H_ #include <string> #include <vector> #include "base/memory/weak_ptr.h" #include "content/public/browser/global_routing_id.h" #include "content/public/browser/serial_chooser.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" #include "services/device/public/mojom/serial.mojom-forward.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/serial/electron_serial_delegate.h" #include "shell/browser/serial/serial_chooser_context.h" #include "third_party/blink/public/mojom/serial/serial.mojom.h" namespace content { class RenderFrameHost; } namespace electron { class ElectronSerialDelegate; // SerialChooserController provides data for the Serial API permission prompt. class SerialChooserController final : public SerialChooserContext::PortObserver, public content::WebContentsObserver { public: SerialChooserController( content::RenderFrameHost* render_frame_host, std::vector<blink::mojom::SerialPortFilterPtr> filters, content::SerialChooser::Callback callback, content::WebContents* web_contents, base::WeakPtr<ElectronSerialDelegate> serial_delegate); ~SerialChooserController() override; // disable copy SerialChooserController(const SerialChooserController&) = delete; SerialChooserController& operator=(const SerialChooserController&) = delete; // SerialChooserContext::PortObserver: void OnPortAdded(const device::mojom::SerialPortInfo& port) override; void OnPortRemoved(const device::mojom::SerialPortInfo& port) override; void OnPortManagerConnectionError() override; void OnPermissionRevoked(const url::Origin& origin) override {} private: api::Session* GetSession(); void OnGetDevices(std::vector<device::mojom::SerialPortInfoPtr> ports); bool FilterMatchesAny(const device::mojom::SerialPortInfo& port) const; void RunCallback(device::mojom::SerialPortInfoPtr port); void OnDeviceChosen(const std::string& port_id); std::vector<blink::mojom::SerialPortFilterPtr> filters_; content::SerialChooser::Callback callback_; url::Origin origin_; base::WeakPtr<SerialChooserContext> chooser_context_; std::vector<device::mojom::SerialPortInfoPtr> ports_; base::WeakPtr<ElectronSerialDelegate> serial_delegate_; content::GlobalRenderFrameHostId render_frame_host_id_; base::WeakPtrFactory<SerialChooserController> weak_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_SERIAL_SERIAL_CHOOSER_CONTROLLER_H_
closed
electron/electron
https://github.com/electron/electron
34,592
[Bug]: disable-color-correct-rendering flag is not respected
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4.2 ### What operating system are you using? macOS ### Operating System Version 11.6.1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Required: disable-color-correct-rendering is enabled and using wide gamut display In the provided gist, there are 2 div elements on the page. The 1st div's red background should render with wide gamut colors i.e. it should correctly respect the disable-color-correct-rendering flag. ### Actual Behavior The 1st div's red background renders incorrectly in sRGB (i.e. it seems to disregard the disable-color-correct-rendering flag). If only the 1st element is present, its red background does render correctly with wide gamut colors (i.e. it correctly respects the disable-color-correct-rendering flag). There seems to be some interaction between the 2 elements that causes the flag to switch from being respected to not being respected. ### Testcase Gist URL https://gist.github.com/landersonfigma/10b141139cd97271ac7c1dfb3cd60e44 ### Additional Information _No response_
https://github.com/electron/electron/issues/34592
https://github.com/electron/electron/pull/35050
c842f63383d8d9500a850e3470972de74ff0809f
0be73d18ef7386584fac964794c2f5a3dcc48f01
2022-06-16T00:56:06Z
c++
2022-07-26T16:35:10Z
patches/chromium/disable_color_correct_rendering.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Birunthan Mohanathas <[email protected]> Date: Fri, 30 Nov 2018 12:44:12 +0200 Subject: disable_color_correct_rendering.patch This adds a --disable-color-correct-rendering switch. In Electron 2.0, `--disable-features=ColorCorrectRendering` could be used to make the app use the display color space (e.g. P3 on Macs) instead of color correcting to sRGB. Because color correct rendering is always enabled on Chromium 62 and later and because `--force-color-profile` has no effect on macOS, apps that need e.g. P3 colors are currently stuck on Electron 2.0. This restores the functionality removed in https://chromium-review.googlesource.com/698347 in the form of the `--disable-color-correct-rendering` switch. This can be removed once web content (including WebGL) learn how to deal with color spaces. That is being tracked at https://crbug.com/634542 and https://crbug.com/711107. diff --git a/cc/trees/layer_tree_host_impl.cc b/cc/trees/layer_tree_host_impl.cc index 6a148c3173f8f5653b945ed9b6ffcbf48d76d511..b30c2e686ff9b64691142ff893225c60cedeaebd 100644 --- a/cc/trees/layer_tree_host_impl.cc +++ b/cc/trees/layer_tree_host_impl.cc @@ -1864,6 +1864,9 @@ void LayerTreeHostImpl::SetIsLikelyToRequireADraw( TargetColorParams LayerTreeHostImpl::GetTargetColorParams( gfx::ContentColorUsage content_color_usage) const { TargetColorParams params; + if (!settings_.enable_color_correct_rendering) { + return params; + } // If we are likely to software composite the resource, we use sRGB because // software compositing is unable to perform color conversion. diff --git a/cc/trees/layer_tree_settings.h b/cc/trees/layer_tree_settings.h index 5eaf2d9cab94def423be78b414179e6ccc596437..1ca8b5968350e88761d9ebc073fe8c573d0f3b5d 100644 --- a/cc/trees/layer_tree_settings.h +++ b/cc/trees/layer_tree_settings.h @@ -93,6 +93,8 @@ class CC_EXPORT LayerTreeSettings { bool use_rgba_4444 = false; bool unpremultiply_and_dither_low_bit_depth_tiles = false; + bool enable_color_correct_rendering = true; + // If set to true, the compositor may selectively defer image decodes to the // Image Decode Service and raster tiles without images until the decode is // ready. diff --git a/components/viz/common/display/renderer_settings.h b/components/viz/common/display/renderer_settings.h index bc48a50a7664f12a454997db54d893cde9b04881..810a8ce52bf9ac74f47a710f8b332980754996f5 100644 --- a/components/viz/common/display/renderer_settings.h +++ b/components/viz/common/display/renderer_settings.h @@ -24,6 +24,7 @@ class VIZ_COMMON_EXPORT RendererSettings { ~RendererSettings(); bool apply_simple_frame_rate_throttling = false; + bool enable_color_correct_rendering = true; bool allow_antialiasing = true; bool force_antialiasing = false; bool force_blending_with_shaders = false; diff --git a/components/viz/host/renderer_settings_creation.cc b/components/viz/host/renderer_settings_creation.cc index 9d34ced366026eb7cdd00ce40a4eb1af56180d39..abf67f8246bfa37df08cd2216c388dd316fb6499 100644 --- a/components/viz/host/renderer_settings_creation.cc +++ b/components/viz/host/renderer_settings_creation.cc @@ -17,6 +17,7 @@ #include "components/viz/common/features.h" #include "components/viz/common/switches.h" #include "ui/base/ui_base_switches.h" +#include "ui/gfx/switches.h" #if defined(USE_OZONE) #include "ui/ozone/public/ozone_platform.h" @@ -49,6 +50,8 @@ bool GetSwitchValueAsInt(const base::CommandLine* command_line, RendererSettings CreateRendererSettings() { RendererSettings renderer_settings; base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + renderer_settings.enable_color_correct_rendering = + !command_line->HasSwitch(switches::kDisableColorCorrectRendering); renderer_settings.partial_swap_enabled = !command_line->HasSwitch(switches::kUIDisablePartialSwap); diff --git a/content/browser/gpu/gpu_process_host.cc b/content/browser/gpu/gpu_process_host.cc index 9b29ab96d6e7dd7160502ee2252843bdeeab84c9..a9889d625dac9148dd8bbc2853c4e09f6546bd0d 100644 --- a/content/browser/gpu/gpu_process_host.cc +++ b/content/browser/gpu/gpu_process_host.cc @@ -228,6 +228,7 @@ GpuTerminationStatus ConvertToGpuTerminationStatus( // Command-line switches to propagate to the GPU process. static const char* const kSwitchNames[] = { + switches::kDisableColorCorrectRendering, sandbox::policy::switches::kDisableSeccompFilterSandbox, sandbox::policy::switches::kGpuSandboxAllowSysVShm, sandbox::policy::switches::kGpuSandboxFailuresFatal, diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index 3f0a3b2133f0d48054f33df28b93a9ee40d7ed78..801bf4b1090a8f0de922fdac6c4145c27a154460 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc @@ -199,6 +199,7 @@ #include "ui/accessibility/accessibility_switches.h" #include "ui/base/ui_base_switches.h" #include "ui/display/display_switches.h" +#include "ui/gfx/switches.h" #include "ui/gl/gl_switches.h" #include "url/gurl.h" #include "url/origin.h" @@ -3185,6 +3186,7 @@ void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer( // Propagate the following switches to the renderer command line (along // with any associated values) if present in the browser command line. static const char* const kSwitchNames[] = { + switches::kDisableColorCorrectRendering, switches::kDisableInProcessStackTraces, sandbox::policy::switches::kDisableSeccompFilterSandbox, sandbox::policy::switches::kNoSandbox, diff --git a/third_party/blink/renderer/platform/graphics/canvas_color_params.cc b/third_party/blink/renderer/platform/graphics/canvas_color_params.cc index 75d7af9a79d4e7f2cd39e45496ab5fff66407638..b4ddafdd126edd16172f00448bbbd56eaf509b1f 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_color_params.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_color_params.cc @@ -4,6 +4,7 @@ #include "third_party/blink/renderer/platform/graphics/canvas_color_params.h" +#include "base/command_line.h" #include "cc/paint/skia_paint_canvas.h" #include "components/viz/common/resources/resource_format_utils.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" @@ -12,6 +13,7 @@ #include "third_party/khronos/GLES3/gl3.h" #include "third_party/skia/include/core/SkSurfaceProps.h" #include "ui/gfx/color_space.h" +#include "ui/gfx/switches.h" namespace blink { @@ -118,6 +120,11 @@ uint8_t CanvasColorParams::BytesPerPixel() const { } gfx::ColorSpace CanvasColorParams::GetStorageGfxColorSpace() const { + auto* cmd_line = base::CommandLine::ForCurrentProcess(); + if (cmd_line->HasSwitch(switches::kDisableColorCorrectRendering)) { + return gfx::ColorSpace(); + } + return PredefinedColorSpaceToGfxColorSpace(color_space_); } diff --git a/third_party/blink/renderer/platform/widget/compositing/layer_tree_settings.cc b/third_party/blink/renderer/platform/widget/compositing/layer_tree_settings.cc index 4f3b9b181b1998e0ebbd95955feeec28a5d6bcb7..00f2a213cded1985b3131fabf3560937c56f6ffd 100644 --- a/third_party/blink/renderer/platform/widget/compositing/layer_tree_settings.cc +++ b/third_party/blink/renderer/platform/widget/compositing/layer_tree_settings.cc @@ -24,6 +24,7 @@ #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "ui/base/ui_base_features.h" #include "ui/base/ui_base_switches.h" +#include "ui/gfx/switches.h" #include "ui/native_theme/native_theme_features.h" #include "ui/native_theme/overlay_scrollbar_constants_aura.h" @@ -178,6 +179,9 @@ cc::LayerTreeSettings GenerateLayerTreeSettings( settings.main_frame_before_activation_enabled = cmd.HasSwitch(cc::switches::kEnableMainFrameBeforeActivation); + settings.enable_color_correct_rendering = + !cmd.HasSwitch(::switches::kDisableColorCorrectRendering); + // Checkerimaging is not supported for synchronous single-threaded mode, which // is what the renderer uses if its not threaded. settings.enable_checker_imaging = diff --git a/ui/gfx/mac/io_surface.cc b/ui/gfx/mac/io_surface.cc index 8bdb9fafc4c5e59d6d6aad323ca2547ecc1b4069..069ed9744dca4fb208daaaf76d4618706c65b84e 100644 --- a/ui/gfx/mac/io_surface.cc +++ b/ui/gfx/mac/io_surface.cc @@ -20,6 +20,7 @@ #include "ui/gfx/buffer_format_util.h" #include "ui/gfx/color_space.h" #include "ui/gfx/icc_profile.h" +#include "ui/gfx/switches.h" namespace gfx { @@ -142,6 +143,14 @@ void IOSurfaceMachPortTraits::Release(mach_port_t port) { // Common method used by IOSurfaceSetColorSpace and IOSurfaceCanSetColorSpace. bool IOSurfaceSetColorSpace(IOSurfaceRef io_surface, const ColorSpace& color_space) { + auto* cmd_line = base::CommandLine::ForCurrentProcess(); + if (cmd_line->HasSwitch(switches::kDisableColorCorrectRendering)) { + base::ScopedCFTypeRef<CFDataRef> system_icc( + CGColorSpaceCopyICCData(base::mac::GetSystemColorSpace())); + IOSurfaceSetValue(io_surface, CFSTR("IOSurfaceColorSpace"), system_icc); + return true; + } + // Allow but ignore invalid color spaces. if (!color_space.IsValid()) return true; @@ -312,6 +321,15 @@ IOSurfaceRef CreateIOSurface(const gfx::Size& size, DCHECK_EQ(kIOReturnSuccess, r); } + auto* cmd_line = base::CommandLine::ForCurrentProcess(); + if (cmd_line->HasSwitch(switches::kDisableColorCorrectRendering)) { + CGColorSpaceRef color_space = base::mac::GetSystemColorSpace(); + base::ScopedCFTypeRef<CFDataRef> color_space_icc( + CGColorSpaceCopyICCData(color_space)); + IOSurfaceSetValue(surface, CFSTR("IOSurfaceColorSpace"), color_space_icc); + return surface; + } + // Ensure that all IOSurfaces start as sRGB. IOSurfaceSetValue(surface, CFSTR("IOSurfaceColorSpace"), kCGColorSpaceSRGB); diff --git a/ui/gfx/switches.cc b/ui/gfx/switches.cc index 0e8044c6d87008c51fd165c6ef8bdc3687d6cc29..78015868927602b5225f252f0a9182f61b8431dc 100644 --- a/ui/gfx/switches.cc +++ b/ui/gfx/switches.cc @@ -11,6 +11,8 @@ namespace switches { // only apply to LinearAnimation and its subclasses. const char kAnimationDurationScale[] = "animation-duration-scale"; +const char kDisableColorCorrectRendering[] = "disable-color-correct-rendering"; + // Force disables font subpixel positioning. This affects the character glyph // sharpness, kerning, hinting and layout. const char kDisableFontSubpixelPositioning[] = diff --git a/ui/gfx/switches.h b/ui/gfx/switches.h index e8e5d44e246364dd45594efb442c129676c14270..252096ee18ca33f4b98f68beb1f534e1c2ab805e 100644 --- a/ui/gfx/switches.h +++ b/ui/gfx/switches.h @@ -12,6 +12,7 @@ namespace switches { GFX_SWITCHES_EXPORT extern const char kAnimationDurationScale[]; +GFX_SWITCHES_EXPORT extern const char kDisableColorCorrectRendering[]; GFX_SWITCHES_EXPORT extern const char kDisableFontSubpixelPositioning[]; GFX_SWITCHES_EXPORT extern const char kEnableNativeGpuMemoryBuffers[]; GFX_SWITCHES_EXPORT extern const char kForcePrefersReducedMotion[];
closed
electron/electron
https://github.com/electron/electron
34,592
[Bug]: disable-color-correct-rendering flag is not respected
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4.2 ### What operating system are you using? macOS ### Operating System Version 11.6.1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Required: disable-color-correct-rendering is enabled and using wide gamut display In the provided gist, there are 2 div elements on the page. The 1st div's red background should render with wide gamut colors i.e. it should correctly respect the disable-color-correct-rendering flag. ### Actual Behavior The 1st div's red background renders incorrectly in sRGB (i.e. it seems to disregard the disable-color-correct-rendering flag). If only the 1st element is present, its red background does render correctly with wide gamut colors (i.e. it correctly respects the disable-color-correct-rendering flag). There seems to be some interaction between the 2 elements that causes the flag to switch from being respected to not being respected. ### Testcase Gist URL https://gist.github.com/landersonfigma/10b141139cd97271ac7c1dfb3cd60e44 ### Additional Information _No response_
https://github.com/electron/electron/issues/34592
https://github.com/electron/electron/pull/35050
c842f63383d8d9500a850e3470972de74ff0809f
0be73d18ef7386584fac964794c2f5a3dcc48f01
2022-06-16T00:56:06Z
c++
2022-07-26T16:35:10Z
patches/chromium/disable_color_correct_rendering.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Birunthan Mohanathas <[email protected]> Date: Fri, 30 Nov 2018 12:44:12 +0200 Subject: disable_color_correct_rendering.patch This adds a --disable-color-correct-rendering switch. In Electron 2.0, `--disable-features=ColorCorrectRendering` could be used to make the app use the display color space (e.g. P3 on Macs) instead of color correcting to sRGB. Because color correct rendering is always enabled on Chromium 62 and later and because `--force-color-profile` has no effect on macOS, apps that need e.g. P3 colors are currently stuck on Electron 2.0. This restores the functionality removed in https://chromium-review.googlesource.com/698347 in the form of the `--disable-color-correct-rendering` switch. This can be removed once web content (including WebGL) learn how to deal with color spaces. That is being tracked at https://crbug.com/634542 and https://crbug.com/711107. diff --git a/cc/trees/layer_tree_host_impl.cc b/cc/trees/layer_tree_host_impl.cc index 6a148c3173f8f5653b945ed9b6ffcbf48d76d511..b30c2e686ff9b64691142ff893225c60cedeaebd 100644 --- a/cc/trees/layer_tree_host_impl.cc +++ b/cc/trees/layer_tree_host_impl.cc @@ -1864,6 +1864,9 @@ void LayerTreeHostImpl::SetIsLikelyToRequireADraw( TargetColorParams LayerTreeHostImpl::GetTargetColorParams( gfx::ContentColorUsage content_color_usage) const { TargetColorParams params; + if (!settings_.enable_color_correct_rendering) { + return params; + } // If we are likely to software composite the resource, we use sRGB because // software compositing is unable to perform color conversion. diff --git a/cc/trees/layer_tree_settings.h b/cc/trees/layer_tree_settings.h index 5eaf2d9cab94def423be78b414179e6ccc596437..1ca8b5968350e88761d9ebc073fe8c573d0f3b5d 100644 --- a/cc/trees/layer_tree_settings.h +++ b/cc/trees/layer_tree_settings.h @@ -93,6 +93,8 @@ class CC_EXPORT LayerTreeSettings { bool use_rgba_4444 = false; bool unpremultiply_and_dither_low_bit_depth_tiles = false; + bool enable_color_correct_rendering = true; + // If set to true, the compositor may selectively defer image decodes to the // Image Decode Service and raster tiles without images until the decode is // ready. diff --git a/components/viz/common/display/renderer_settings.h b/components/viz/common/display/renderer_settings.h index bc48a50a7664f12a454997db54d893cde9b04881..810a8ce52bf9ac74f47a710f8b332980754996f5 100644 --- a/components/viz/common/display/renderer_settings.h +++ b/components/viz/common/display/renderer_settings.h @@ -24,6 +24,7 @@ class VIZ_COMMON_EXPORT RendererSettings { ~RendererSettings(); bool apply_simple_frame_rate_throttling = false; + bool enable_color_correct_rendering = true; bool allow_antialiasing = true; bool force_antialiasing = false; bool force_blending_with_shaders = false; diff --git a/components/viz/host/renderer_settings_creation.cc b/components/viz/host/renderer_settings_creation.cc index 9d34ced366026eb7cdd00ce40a4eb1af56180d39..abf67f8246bfa37df08cd2216c388dd316fb6499 100644 --- a/components/viz/host/renderer_settings_creation.cc +++ b/components/viz/host/renderer_settings_creation.cc @@ -17,6 +17,7 @@ #include "components/viz/common/features.h" #include "components/viz/common/switches.h" #include "ui/base/ui_base_switches.h" +#include "ui/gfx/switches.h" #if defined(USE_OZONE) #include "ui/ozone/public/ozone_platform.h" @@ -49,6 +50,8 @@ bool GetSwitchValueAsInt(const base::CommandLine* command_line, RendererSettings CreateRendererSettings() { RendererSettings renderer_settings; base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + renderer_settings.enable_color_correct_rendering = + !command_line->HasSwitch(switches::kDisableColorCorrectRendering); renderer_settings.partial_swap_enabled = !command_line->HasSwitch(switches::kUIDisablePartialSwap); diff --git a/content/browser/gpu/gpu_process_host.cc b/content/browser/gpu/gpu_process_host.cc index 9b29ab96d6e7dd7160502ee2252843bdeeab84c9..a9889d625dac9148dd8bbc2853c4e09f6546bd0d 100644 --- a/content/browser/gpu/gpu_process_host.cc +++ b/content/browser/gpu/gpu_process_host.cc @@ -228,6 +228,7 @@ GpuTerminationStatus ConvertToGpuTerminationStatus( // Command-line switches to propagate to the GPU process. static const char* const kSwitchNames[] = { + switches::kDisableColorCorrectRendering, sandbox::policy::switches::kDisableSeccompFilterSandbox, sandbox::policy::switches::kGpuSandboxAllowSysVShm, sandbox::policy::switches::kGpuSandboxFailuresFatal, diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index 3f0a3b2133f0d48054f33df28b93a9ee40d7ed78..801bf4b1090a8f0de922fdac6c4145c27a154460 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc @@ -199,6 +199,7 @@ #include "ui/accessibility/accessibility_switches.h" #include "ui/base/ui_base_switches.h" #include "ui/display/display_switches.h" +#include "ui/gfx/switches.h" #include "ui/gl/gl_switches.h" #include "url/gurl.h" #include "url/origin.h" @@ -3185,6 +3186,7 @@ void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer( // Propagate the following switches to the renderer command line (along // with any associated values) if present in the browser command line. static const char* const kSwitchNames[] = { + switches::kDisableColorCorrectRendering, switches::kDisableInProcessStackTraces, sandbox::policy::switches::kDisableSeccompFilterSandbox, sandbox::policy::switches::kNoSandbox, diff --git a/third_party/blink/renderer/platform/graphics/canvas_color_params.cc b/third_party/blink/renderer/platform/graphics/canvas_color_params.cc index 75d7af9a79d4e7f2cd39e45496ab5fff66407638..b4ddafdd126edd16172f00448bbbd56eaf509b1f 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_color_params.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_color_params.cc @@ -4,6 +4,7 @@ #include "third_party/blink/renderer/platform/graphics/canvas_color_params.h" +#include "base/command_line.h" #include "cc/paint/skia_paint_canvas.h" #include "components/viz/common/resources/resource_format_utils.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" @@ -12,6 +13,7 @@ #include "third_party/khronos/GLES3/gl3.h" #include "third_party/skia/include/core/SkSurfaceProps.h" #include "ui/gfx/color_space.h" +#include "ui/gfx/switches.h" namespace blink { @@ -118,6 +120,11 @@ uint8_t CanvasColorParams::BytesPerPixel() const { } gfx::ColorSpace CanvasColorParams::GetStorageGfxColorSpace() const { + auto* cmd_line = base::CommandLine::ForCurrentProcess(); + if (cmd_line->HasSwitch(switches::kDisableColorCorrectRendering)) { + return gfx::ColorSpace(); + } + return PredefinedColorSpaceToGfxColorSpace(color_space_); } diff --git a/third_party/blink/renderer/platform/widget/compositing/layer_tree_settings.cc b/third_party/blink/renderer/platform/widget/compositing/layer_tree_settings.cc index 4f3b9b181b1998e0ebbd95955feeec28a5d6bcb7..00f2a213cded1985b3131fabf3560937c56f6ffd 100644 --- a/third_party/blink/renderer/platform/widget/compositing/layer_tree_settings.cc +++ b/third_party/blink/renderer/platform/widget/compositing/layer_tree_settings.cc @@ -24,6 +24,7 @@ #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "ui/base/ui_base_features.h" #include "ui/base/ui_base_switches.h" +#include "ui/gfx/switches.h" #include "ui/native_theme/native_theme_features.h" #include "ui/native_theme/overlay_scrollbar_constants_aura.h" @@ -178,6 +179,9 @@ cc::LayerTreeSettings GenerateLayerTreeSettings( settings.main_frame_before_activation_enabled = cmd.HasSwitch(cc::switches::kEnableMainFrameBeforeActivation); + settings.enable_color_correct_rendering = + !cmd.HasSwitch(::switches::kDisableColorCorrectRendering); + // Checkerimaging is not supported for synchronous single-threaded mode, which // is what the renderer uses if its not threaded. settings.enable_checker_imaging = diff --git a/ui/gfx/mac/io_surface.cc b/ui/gfx/mac/io_surface.cc index 8bdb9fafc4c5e59d6d6aad323ca2547ecc1b4069..069ed9744dca4fb208daaaf76d4618706c65b84e 100644 --- a/ui/gfx/mac/io_surface.cc +++ b/ui/gfx/mac/io_surface.cc @@ -20,6 +20,7 @@ #include "ui/gfx/buffer_format_util.h" #include "ui/gfx/color_space.h" #include "ui/gfx/icc_profile.h" +#include "ui/gfx/switches.h" namespace gfx { @@ -142,6 +143,14 @@ void IOSurfaceMachPortTraits::Release(mach_port_t port) { // Common method used by IOSurfaceSetColorSpace and IOSurfaceCanSetColorSpace. bool IOSurfaceSetColorSpace(IOSurfaceRef io_surface, const ColorSpace& color_space) { + auto* cmd_line = base::CommandLine::ForCurrentProcess(); + if (cmd_line->HasSwitch(switches::kDisableColorCorrectRendering)) { + base::ScopedCFTypeRef<CFDataRef> system_icc( + CGColorSpaceCopyICCData(base::mac::GetSystemColorSpace())); + IOSurfaceSetValue(io_surface, CFSTR("IOSurfaceColorSpace"), system_icc); + return true; + } + // Allow but ignore invalid color spaces. if (!color_space.IsValid()) return true; @@ -312,6 +321,15 @@ IOSurfaceRef CreateIOSurface(const gfx::Size& size, DCHECK_EQ(kIOReturnSuccess, r); } + auto* cmd_line = base::CommandLine::ForCurrentProcess(); + if (cmd_line->HasSwitch(switches::kDisableColorCorrectRendering)) { + CGColorSpaceRef color_space = base::mac::GetSystemColorSpace(); + base::ScopedCFTypeRef<CFDataRef> color_space_icc( + CGColorSpaceCopyICCData(color_space)); + IOSurfaceSetValue(surface, CFSTR("IOSurfaceColorSpace"), color_space_icc); + return surface; + } + // Ensure that all IOSurfaces start as sRGB. IOSurfaceSetValue(surface, CFSTR("IOSurfaceColorSpace"), kCGColorSpaceSRGB); diff --git a/ui/gfx/switches.cc b/ui/gfx/switches.cc index 0e8044c6d87008c51fd165c6ef8bdc3687d6cc29..78015868927602b5225f252f0a9182f61b8431dc 100644 --- a/ui/gfx/switches.cc +++ b/ui/gfx/switches.cc @@ -11,6 +11,8 @@ namespace switches { // only apply to LinearAnimation and its subclasses. const char kAnimationDurationScale[] = "animation-duration-scale"; +const char kDisableColorCorrectRendering[] = "disable-color-correct-rendering"; + // Force disables font subpixel positioning. This affects the character glyph // sharpness, kerning, hinting and layout. const char kDisableFontSubpixelPositioning[] = diff --git a/ui/gfx/switches.h b/ui/gfx/switches.h index e8e5d44e246364dd45594efb442c129676c14270..252096ee18ca33f4b98f68beb1f534e1c2ab805e 100644 --- a/ui/gfx/switches.h +++ b/ui/gfx/switches.h @@ -12,6 +12,7 @@ namespace switches { GFX_SWITCHES_EXPORT extern const char kAnimationDurationScale[]; +GFX_SWITCHES_EXPORT extern const char kDisableColorCorrectRendering[]; GFX_SWITCHES_EXPORT extern const char kDisableFontSubpixelPositioning[]; GFX_SWITCHES_EXPORT extern const char kEnableNativeGpuMemoryBuffers[]; GFX_SWITCHES_EXPORT extern const char kForcePrefersReducedMotion[];
closed
electron/electron
https://github.com/electron/electron
34,599
[Bug]: setBounds calls during will-resize are no longer applied when preventing the default resize
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4, 18, 19 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 21H1 ### What arch are you using? x64 ### Last Known Working Electron version 17.3.1 ### Expected Behavior Prior to version 17.4.0, it was possible to override the bounds received within will-resize event. While this ability is not explicitly documented, we rely on it for window management within our product. ### Actual Behavior The window no longer resizes when the will-resize event is prevented and we attempt to control the resize with setBounds. ### Testcase Gist URL https://gist.github.com/meredith-ciq/a7ad120e84bd028a3fbd26b8f61aa45c ### Additional Information This was caused during the changes from: [#33288](https://github.com/electron/electron/pull/33288) I believe the gate on is_resizing_ at the top of setBounds is preventing any ability to overwrite the bounds that come in during a will-resize event. Our application currently overrides the native resize and does our own resize after modifying the window bounds. This has caused resize to break in recent electron versions as the intermediate setBounds calls during resize are not being applied. We have several aspects of window management that depend on having this level of control over resize: - Groups of windows maintaining proportions when a single window in the group is resized - Snapping edges of windows to other windows during resize - Resolving jitter of a window during resize by applying our own calculations I've also mentioned this issue in a related issue: #33897. The fix from that issue only had the effect of not applying the final setBounds in the resize action. In our case that causes the window to no longer resize instead of giving no visual indication that a resize was occurring until the corner or edge of the window was dropped. I did some testing with the gist in that issue on the latest electron and it appears the behavior only works when some of the native resize events are allowed through.
https://github.com/electron/electron/issues/34599
https://github.com/electron/electron/pull/34843
6d9e8b65bc94dea8fc47f4e03c1833263c3622e9
9416091180e18c1ba1f625f86505332a018d9049
2022-06-16T17:39:52Z
c++
2022-07-27T00:02:06Z
shell/browser/native_window_views.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/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "shell/common/platform_util.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: NativeWindowViews* window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); 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.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; // Set Wayland application ID. params.wayland_app_id = platform_util::GetXdgAppId(); auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if BUILDFLAG(IS_LINUX) // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // TODO(ckerr): remove in Electron v20.0.0 // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; bool skip_taskbar = false; if (options.Get(options::kSkipTaskbar, &skip_taskbar) && skip_taskbar) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); } // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); } #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); } #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif #if defined(USE_OZONE_PLATFORM_X11) // On X11, setting Z order before showing the window doesn't take effect, // so we have to call it again. if (IsX11()) widget()->SetZOrderLevel(widget()->GetZOrderLevel()); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; return; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); } #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) SetWMSpecState(static_cast<x11::Window>(GetAcceleratedWidget()), skip, x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_OZONE) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (CreateGlobalMenuBar() && ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); } #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } void NativeWindowViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { draggable_region_ = DraggableRegionsToSkRegion(regions); } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blurred. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { // App window should claim mouse events that fall within any BrowserViews' // draggable region. for (auto* view : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(view); auto* view_draggable_region = native_view->draggable_region(); if (view_draggable_region && view_draggable_region->contains(location.x(), location.y())) return false; } // App window should claim mouse events that fall within the draggable region. if (draggable_region() && draggable_region()->contains(location.x(), location.y())) return false; // And the events on border for dragging resizable frameless window. if ((!has_frame() || has_client_frame()) && resizable_) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); return frame->ResizingBorderHitTest(location) == HTNOWHERE; } return true; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,599
[Bug]: setBounds calls during will-resize are no longer applied when preventing the default resize
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4, 18, 19 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 21H1 ### What arch are you using? x64 ### Last Known Working Electron version 17.3.1 ### Expected Behavior Prior to version 17.4.0, it was possible to override the bounds received within will-resize event. While this ability is not explicitly documented, we rely on it for window management within our product. ### Actual Behavior The window no longer resizes when the will-resize event is prevented and we attempt to control the resize with setBounds. ### Testcase Gist URL https://gist.github.com/meredith-ciq/a7ad120e84bd028a3fbd26b8f61aa45c ### Additional Information This was caused during the changes from: [#33288](https://github.com/electron/electron/pull/33288) I believe the gate on is_resizing_ at the top of setBounds is preventing any ability to overwrite the bounds that come in during a will-resize event. Our application currently overrides the native resize and does our own resize after modifying the window bounds. This has caused resize to break in recent electron versions as the intermediate setBounds calls during resize are not being applied. We have several aspects of window management that depend on having this level of control over resize: - Groups of windows maintaining proportions when a single window in the group is resized - Snapping edges of windows to other windows during resize - Resolving jitter of a window during resize by applying our own calculations I've also mentioned this issue in a related issue: #33897. The fix from that issue only had the effect of not applying the final setBounds in the resize action. In our case that causes the window to no longer resize instead of giving no visual indication that a resize was occurring until the corner or edge of the window was dropped. I did some testing with the gist in that issue on the latest electron and it appears the behavior only works when some of the native resize events are allowed through.
https://github.com/electron/electron/issues/34599
https://github.com/electron/electron/pull/34843
6d9e8b65bc94dea8fc47f4e03c1833263c3622e9
9416091180e18c1ba1f625f86505332a018d9049
2022-06-16T17:39:52Z
c++
2022-07-27T00:02:06Z
shell/browser/native_window_views.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/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "shell/common/platform_util.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: NativeWindowViews* window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); 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.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; // Set Wayland application ID. params.wayland_app_id = platform_util::GetXdgAppId(); auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if BUILDFLAG(IS_LINUX) // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // TODO(ckerr): remove in Electron v20.0.0 // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; bool skip_taskbar = false; if (options.Get(options::kSkipTaskbar, &skip_taskbar) && skip_taskbar) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); } // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); } #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); } #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif #if defined(USE_OZONE_PLATFORM_X11) // On X11, setting Z order before showing the window doesn't take effect, // so we have to call it again. if (IsX11()) widget()->SetZOrderLevel(widget()->GetZOrderLevel()); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; return; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); } #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) SetWMSpecState(static_cast<x11::Window>(GetAcceleratedWidget()), skip, x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_OZONE) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (CreateGlobalMenuBar() && ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); } #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } void NativeWindowViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { draggable_region_ = DraggableRegionsToSkRegion(regions); } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blurred. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { // App window should claim mouse events that fall within any BrowserViews' // draggable region. for (auto* view : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(view); auto* view_draggable_region = native_view->draggable_region(); if (view_draggable_region && view_draggable_region->contains(location.x(), location.y())) return false; } // App window should claim mouse events that fall within the draggable region. if (draggable_region() && draggable_region()->contains(location.x(), location.y())) return false; // And the events on border for dragging resizable frameless window. if ((!has_frame() || has_client_frame()) && resizable_) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); return frame->ResizingBorderHitTest(location) == HTNOWHERE; } return true; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,996
[Bug]: SIGTRAP when starting electron >= 20.0.0-beta.9
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.0-beta.9 and 20.0.0-beta.10 ### What operating system are you using? Other Linux ### Operating System Version Fedora 35 ### What arch are you using? x64 ### Last Known Working Electron version All older versions, including 19 and 20.0.0-beta.8 ### Expected Behavior Electron quickstart app should work, as should ANY other electron app, I have tested a bunch of them, but all gave the same results, after you install a recent 20 beta. ### Actual Behavior They don't start if I use version 20.0.0-beta.9 or 20.0.0-beta.10, older versions *do* work. It only happens on *one* of the devices I own, *all* others are fine, but this one does not handle these new versions, while older ones work. This must have been introduced somewhere in [these commits between those releases](https://github.com/electron/electron/compare/v20.0.0-beta.8...v20.0.0-beta.9). ### Testcase Gist URL https://github.com/electron/electron-quick-start/ ### Additional Information Running electron with `gdb` does not give a lot of info, unless I'm running it incorrectly, please see below and let me know if this should be done differently: ```gdb jelmerro ~/electron-quick-start (master)$ gdb --args node node_modules/.bin/electron . GNU gdb (GDB) Fedora 12.1-1.fc35 Copyright (C) 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-redhat-linux-gnu". Type "show configuration" for configuration details. For bug reporting instructions, please see: <https://www.gnu.org/software/gdb/bugs/>. Find the GDB manual and other documentation resources online at: <http://www.gnu.org/software/gdb/documentation/>. For help, type "help". Type "apropos word" to search for commands related to "word"... Reading symbols from node... This GDB supports auto-downloading debuginfo from the following URLs: https://debuginfod.fedoraproject.org/ Enable debuginfod for this session? (y or [n]) y Debuginfod has been enabled. To make this setting permanent, add 'set debuginfod enabled on' to .gdbinit. Reading symbols from /home/jelmerro/.cache/debuginfod_client/adca03b9b7e322bf173d4a6972adea6c254bf914/debuginfo... (gdb) run Starting program: /usr/bin/node node_modules/.bin/electron . [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib64/libthread_db.so.1". [New Thread 0x7ffff23c0640 (LWP 12930)] [New Thread 0x7ffff1bbf640 (LWP 12931)] [New Thread 0x7ffff13be640 (LWP 12932)] [New Thread 0x7ffff0bbd640 (LWP 12933)] [New Thread 0x7fffebfff640 (LWP 12934)] [New Thread 0x7ffff7fbe640 (LWP 12935)] [Detaching after fork from child process 12936] /home/jelmerro/electron-quick-start/node_modules/electron/dist/electron exited with signal SIGTRAP [Thread 0x7fffebfff640 (LWP 12934) exited] [Thread 0x7ffff0bbd640 (LWP 12933) exited] [Thread 0x7ffff13be640 (LWP 12932) exited] [Thread 0x7ffff1bbf640 (LWP 12931) exited] [Thread 0x7ffff23c0640 (LWP 12930) exited] [Thread 0x7ffff7fbe640 (LWP 12935) exited] [Inferior 1 (process 12927) exited with code 01] ```
https://github.com/electron/electron/issues/34996
https://github.com/electron/electron/pull/35075
ff804e3a748c72f4812af8ccf3b1d7442a468f4a
62001dc6cbfd78a82d2fca849ca5eb0504cd0b71
2022-07-20T15:23:25Z
c++
2022-07-27T04:44:44Z
shell/browser/electron_browser_main_parts.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_main_parts.h" #include <memory> #include <string> #include <utility> #include "base/base_switches.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/metrics/field_trial.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/icon_manager.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "components/os_crypt/key_storage_config_linux.h" #include "components/os_crypt/os_crypt.h" #include "content/browser/browser_main_loop.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/device_service.h" #include "content/public/browser/first_party_sets_handler.h" #include "content/public/browser/web_ui_controller_factory.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/result_codes.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "media/base/localized_strings.h" #include "services/network/public/cpp/features.h" #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" #include "shell/app/electron_main_delegate.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/browser.h" #include "shell/browser/browser_process_impl.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_web_ui_controller_factory.h" #include "shell/browser/feature_list.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" #include "shell/browser/ui/devtools_manager_delegate.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_helper/trackable_object.h" #include "shell/common/logging.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/idle/idle.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_switches.h" #if defined(USE_AURA) #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/views/widget/desktop_aura/desktop_screen.h" #include "ui/wm/core/wm_state.h" #endif #if BUILDFLAG(IS_LINUX) #include "base/environment.h" #include "base/threading/thread_task_runner_handle.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h" #include "electron/electron_gtk_stubs.h" #include "ui/base/cursor/cursor_factory.h" #include "ui/base/ime/linux/linux_input_method_context_factory.h" #include "ui/gfx/color_utils.h" #include "ui/gtk/gtk_compat.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #include "ui/linux/linux_ui.h" #include "ui/linux/linux_ui_factory.h" #include "ui/ozone/public/ozone_platform.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/l10n/l10n_util_win.h" #include "ui/display/win/dpi.h" #include "ui/gfx/system_fonts_win.h" #include "ui/strings/grit/app_locale_settings.h" #endif #if BUILDFLAG(IS_MAC) #include "services/device/public/cpp/geolocation/geolocation_manager.h" #include "shell/browser/ui/cocoa/views_delegate_mac.h" #else #include "shell/browser/ui/views/electron_views_delegate.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck #endif namespace electron { namespace { template <typename T> void Erase(T* container, typename T::iterator iter) { container->erase(iter); } #if BUILDFLAG(IS_WIN) // gfx::Font callbacks void AdjustUIFont(gfx::win::FontAdjustment* font_adjustment) { l10n_util::NeedOverrideDefaultUIFont(&font_adjustment->font_family_override, &font_adjustment->font_scale); font_adjustment->font_scale *= display::win::GetAccessibilityFontScale(); } int GetMinimumFontSize() { int min_font_size; base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE), &min_font_size); return min_font_size; } #endif std::u16string MediaStringProvider(media::MessageId id) { switch (id) { case media::DEFAULT_AUDIO_DEVICE_NAME: return u"Default"; #if BUILDFLAG(IS_WIN) case media::COMMUNICATIONS_AUDIO_DEVICE_NAME: return u"Communications"; #endif default: return std::u16string(); } } #if BUILDFLAG(IS_LINUX) // GTK does not provide a way to check if current theme is dark, so we compare // the text and background luminosity to get a result. // This trick comes from FireFox. void UpdateDarkThemeSetting() { float bg = color_utils::GetRelativeLuminance(gtk::GetBgColor("GtkLabel")); float fg = color_utils::GetRelativeLuminance(gtk::GetFgColor("GtkLabel")); bool is_dark = fg > bg; // Pass it to NativeUi theme, which is used by the nativeTheme module and most // places in Electron. ui::NativeTheme::GetInstanceForNativeUi()->set_use_dark_colors(is_dark); // Pass it to Web Theme, to make "prefers-color-scheme" media query work. ui::NativeTheme::GetInstanceForWeb()->set_use_dark_colors(is_dark); } #endif } // namespace #if BUILDFLAG(IS_LINUX) class DarkThemeObserver : public ui::NativeThemeObserver { public: DarkThemeObserver() = default; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override { UpdateDarkThemeSetting(); } }; #endif // static ElectronBrowserMainParts* ElectronBrowserMainParts::self_ = nullptr; ElectronBrowserMainParts::ElectronBrowserMainParts() : fake_browser_process_(std::make_unique<BrowserProcessImpl>()), browser_(std::make_unique<Browser>()), node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kBrowser)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) { DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts"; self_ = this; } ElectronBrowserMainParts::~ElectronBrowserMainParts() = default; // static ElectronBrowserMainParts* ElectronBrowserMainParts::Get() { DCHECK(self_); return self_; } bool ElectronBrowserMainParts::SetExitCode(int code) { if (!exit_code_) return false; content::BrowserMainLoop::GetInstance()->SetResultCode(code); *exit_code_ = code; return true; } int ElectronBrowserMainParts::GetExitCode() const { return exit_code_.value_or(content::RESULT_CODE_NORMAL_EXIT); } int ElectronBrowserMainParts::PreEarlyInitialization() { field_trial_list_ = std::make_unique<base::FieldTrialList>(nullptr); #if BUILDFLAG(IS_POSIX) HandleSIGCHLD(); #endif #if BUILDFLAG(IS_LINUX) DetectOzonePlatform(); ui::OzonePlatform::PreEarlyInitialization(); #endif #if BUILDFLAG(IS_MAC) screen_ = std::make_unique<display::ScopedNativeScreen>(); #endif return GetExitCode(); } void ElectronBrowserMainParts::PostEarlyInitialization() { // A workaround was previously needed because there was no ThreadTaskRunner // set. If this check is failing we may need to re-add that workaround DCHECK(base::ThreadTaskRunnerHandle::IsSet()); // The ProxyResolverV8 has setup a complete V8 environment, in order to // avoid conflicts we only initialize our V8 environment after that. js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop()); v8::HandleScope scope(js_env_->isolate()); node_bindings_->Initialize(); // Create the global environment. node::Environment* env = node_bindings_->CreateEnvironment( js_env_->context(), js_env_->platform()); node_env_ = std::make_unique<NodeEnvironment>(env); env->set_trace_sync_io(env->options()->trace_sync_io); // We do not want to crash the main process on unhandled rejections. env->options()->unhandled_rejections = "warn"; // Add Electron extended APIs. electron_bindings_->BindTo(js_env_->isolate(), env->process_object()); // Load everything. node_bindings_->LoadEnvironment(env); // Wrap the uv loop with global env. node_bindings_->set_uv_env(env); // We already initialized the feature list in PreEarlyInitialization(), but // the user JS script would not have had a chance to alter the command-line // switches at that point. Lets reinitialize it here to pick up the // command-line changes. base::FeatureList::ClearInstanceForTesting(); InitializeFeatureList(); // Initialize field trials. InitializeFieldTrials(); // Reinitialize logging now that the app has had a chance to set the app name // and/or user data directory. logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(), /* is_preinit = */ false); // Initialize after user script environment creation. fake_browser_process_->PostEarlyInitialization(); } int ElectronBrowserMainParts::PreCreateThreads() { #if defined(USE_AURA) if (!display::Screen::GetScreen()) { screen_ = views::CreateDesktopScreen(); } #endif if (!views::LayoutProvider::Get()) layout_provider_ = std::make_unique<views::LayoutProvider>(); auto* command_line = base::CommandLine::ForCurrentProcess(); std::string locale = command_line->GetSwitchValueASCII(::switches::kLang); #if BUILDFLAG(IS_MAC) // The browser process only wants to support the language Cocoa will use, // so force the app locale to be overridden with that value. This must // happen before the ResourceBundle is loaded if (locale.empty()) l10n_util::OverrideLocaleWithCocoaLocale(); #elif BUILDFLAG(IS_LINUX) // l10n_util::GetApplicationLocaleInternal uses g_get_language_names(), // which keys off of getenv("LC_ALL"). // We must set this env first to make ui::ResourceBundle accept the custom // locale. auto env = base::Environment::Create(); absl::optional<std::string> lc_all; if (!locale.empty()) { std::string str; if (env->GetVar("LC_ALL", &str)) lc_all.emplace(std::move(str)); env->SetVar("LC_ALL", locale.c_str()); } #endif // Load resources bundle according to locale. std::string loaded_locale = LoadResourceBundle(locale); // Initialize the app locale. std::string app_locale = l10n_util::GetApplicationLocale(loaded_locale); ElectronBrowserClient::SetApplicationLocale(app_locale); fake_browser_process_->SetApplicationLocale(app_locale); #if BUILDFLAG(IS_LINUX) // Reset to the original LC_ALL since we should not be changing it. if (!locale.empty()) { if (lc_all) env->SetVar("LC_ALL", *lc_all); else env->UnSetVar("LC_ALL"); } #endif // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); #if BUILDFLAG(IS_MAC) ui::InitIdleMonitor(); #endif fake_browser_process_->PreCreateThreads(); // Notify observers. Browser::Get()->PreCreateThreads(); return 0; } void ElectronBrowserMainParts::PostCreateThreads() { content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread)); } void ElectronBrowserMainParts::PostDestroyThreads() { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_browser_client_.reset(); extensions::ExtensionsBrowserClient::Set(nullptr); #endif #if BUILDFLAG(IS_LINUX) device::BluetoothAdapterFactory::Shutdown(); bluez::DBusBluezManagerWrapperLinux::Shutdown(); #endif fake_browser_process_->PostDestroyThreads(); } void ElectronBrowserMainParts::ToolkitInitialized() { #if BUILDFLAG(IS_LINUX) auto linux_ui = ui::CreateLinuxUi(); DCHECK(ui::LinuxInputMethodContextFactory::instance()); // Try loading gtk symbols used by Electron. electron::InitializeElectron_gtk(gtk::GetLibGtk()); if (!electron::IsElectron_gtkInitialized()) { electron::UninitializeElectron_gtk(); } electron::InitializeElectron_gdk_pixbuf(gtk::GetLibGdkPixbuf()); CHECK(electron::IsElectron_gdk_pixbufInitialized()) << "Failed to initialize libgdk_pixbuf-2.0.so.0"; // Chromium does not respect GTK dark theme setting, but they may change // in future and this code might be no longer needed. Check the Chromium // issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=998903 UpdateDarkThemeSetting(); // Update the native theme when GTK theme changes. The GetNativeTheme // here returns a NativeThemeGtk, which monitors GTK settings. dark_theme_observer_ = std::make_unique<DarkThemeObserver>(); linux_ui->GetNativeTheme(nullptr)->AddObserver(dark_theme_observer_.get()); ui::LinuxUi::SetInstance(std::move(linux_ui)); // Cursor theme changes are tracked by LinuxUI (via a CursorThemeManager // implementation). Start observing them once it's initialized. ui::CursorFactory::GetInstance()->ObserveThemeChanges(); #endif #if defined(USE_AURA) wm_state_ = std::make_unique<wm::WMState>(); #endif #if BUILDFLAG(IS_WIN) gfx::win::SetAdjustFontCallback(&AdjustUIFont); gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize); #endif #if BUILDFLAG(IS_MAC) views_delegate_ = std::make_unique<ViewsDelegateMac>(); #else views_delegate_ = std::make_unique<ViewsDelegate>(); #endif } int ElectronBrowserMainParts::PreMainMessageLoopRun() { // Run user's main script before most things get initialized, so we can have // a chance to setup everything. node_bindings_->PrepareEmbedThread(); node_bindings_->StartPolling(); // url::Add*Scheme are not threadsafe, this helps prevent data races. url::LockSchemeRegistries(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_client_ = std::make_unique<ElectronExtensionsClient>(); extensions::ExtensionsClient::Set(extensions_client_.get()); // BrowserContextKeyedAPIServiceFactories require an ExtensionsBrowserClient. extensions_browser_client_ = std::make_unique<ElectronExtensionsBrowserClient>(); extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get()); extensions::EnsureBrowserContextKeyedServiceFactoriesBuilt(); extensions::electron::EnsureBrowserContextKeyedServiceFactoriesBuilt(); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckServiceFactory::GetInstance(); #endif content::WebUIControllerFactory::RegisterFactory( ElectronWebUIControllerFactory::GetInstance()); auto* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kRemoteDebuggingPipe)) { // --remote-debugging-pipe auto on_disconnect = base::BindOnce([]() { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce([]() { Browser::Get()->Quit(); })); }); content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler( std::move(on_disconnect)); } else if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) { // --remote-debugging-port DevToolsManagerDelegate::StartHttpHandler(); } #if !BUILDFLAG(IS_MAC) // The corresponding call in macOS is in ElectronApplicationDelegate. Browser::Get()->WillFinishLaunching(); Browser::Get()->DidFinishLaunching(base::Value::Dict()); #endif // Notify observers that main thread message loop was initialized. Browser::Get()->PreMainMessageLoopRun(); return GetExitCode(); } void ElectronBrowserMainParts::WillRunMainMessageLoop( std::unique_ptr<base::RunLoop>& run_loop) { js_env_->OnMessageLoopCreated(); exit_code_ = content::RESULT_CODE_NORMAL_EXIT; Browser::Get()->SetMainMessageLoopQuitClosure( run_loop->QuitWhenIdleClosure()); } void ElectronBrowserMainParts::PostCreateMainMessageLoop() { #if BUILDFLAG(IS_LINUX) auto shutdown_cb = base::BindOnce(base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); ui::OzonePlatform::GetInstance()->PostCreateMainMessageLoop( std::move(shutdown_cb)); bluez::DBusBluezManagerWrapperLinux::Initialize(); // Set up crypt config. This needs to be done before anything starts the // network service, as the raw encryption key needs to be shared with the // network service for encrypted cookie storage. std::string app_name = electron::Browser::Get()->GetName(); const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); std::unique_ptr<os_crypt::Config> config = std::make_unique<os_crypt::Config>(); // Forward to os_crypt the flag to use a specific password store. config->store = command_line.GetSwitchValueASCII(::switches::kPasswordStore); config->product_name = app_name; config->application_name = app_name; config->main_thread_runner = base::ThreadTaskRunnerHandle::Get(); // c.f. // https://source.chromium.org/chromium/chromium/src/+/master:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1 config->should_use_preference = command_line.HasSwitch(::switches::kEnableEncryptionSelection); base::PathService::Get(DIR_SESSION_DATA, &config->user_data_path); OSCrypt::SetConfig(std::move(config)); #endif #if BUILDFLAG(IS_POSIX) // Exit in response to SIGINT, SIGTERM, etc. InstallShutdownSignalHandlers( base::BindOnce(&Browser::Quit, base::Unretained(Browser::Get())), content::GetUIThreadTaskRunner({})); #endif } void ElectronBrowserMainParts::PostMainMessageLoopRun() { #if BUILDFLAG(IS_MAC) FreeAppDelegate(); #endif // Shutdown the DownloadManager before destroying Node to prevent // DownloadItem callbacks from crashing. for (auto& iter : ElectronBrowserContext::browser_context_map()) { auto* download_manager = iter.second.get()->GetDownloadManager(); if (download_manager) { download_manager->Shutdown(); } } // Destroy node platform after all destructors_ are executed, as they may // invoke Node/V8 APIs inside them. node_env_->env()->set_trace_sync_io(false); js_env_->OnMessageLoopDestroying(); node::Stop(node_env_->env()); node_env_.reset(); auto default_context_key = ElectronBrowserContext::PartitionKey("", false); std::unique_ptr<ElectronBrowserContext> default_context = std::move( ElectronBrowserContext::browser_context_map()[default_context_key]); ElectronBrowserContext::browser_context_map().clear(); default_context.reset(); fake_browser_process_->PostMainMessageLoopRun(); content::DevToolsAgentHost::StopRemoteDebuggingPipeHandler(); #if BUILDFLAG(IS_LINUX) ui::OzonePlatform::GetInstance()->PostMainMessageLoopRun(); #endif } #if !BUILDFLAG(IS_MAC) void ElectronBrowserMainParts::PreCreateMainMessageLoop() { PreCreateMainMessageLoopCommon(); } #endif void ElectronBrowserMainParts::PreCreateMainMessageLoopCommon() { #if BUILDFLAG(IS_MAC) InitializeMainNib(); RegisterURLHandler(); #endif media::SetLocalizedStringProvider(MediaStringProvider); #if BUILDFLAG(IS_WIN) auto* local_state = g_browser_process->local_state(); DCHECK(local_state); bool os_crypt_init = OSCrypt::Init(local_state); DCHECK(os_crypt_init); #endif } device::mojom::GeolocationControl* ElectronBrowserMainParts::GetGeolocationControl() { if (!geolocation_control_) { content::GetDeviceService().BindGeolocationControl( geolocation_control_.BindNewPipeAndPassReceiver()); } return geolocation_control_.get(); } #if BUILDFLAG(IS_MAC) device::GeolocationManager* ElectronBrowserMainParts::GetGeolocationManager() { return geolocation_manager_.get(); } #endif IconManager* ElectronBrowserMainParts::GetIconManager() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!icon_manager_.get()) icon_manager_ = std::make_unique<IconManager>(); return icon_manager_.get(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,996
[Bug]: SIGTRAP when starting electron >= 20.0.0-beta.9
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.0-beta.9 and 20.0.0-beta.10 ### What operating system are you using? Other Linux ### Operating System Version Fedora 35 ### What arch are you using? x64 ### Last Known Working Electron version All older versions, including 19 and 20.0.0-beta.8 ### Expected Behavior Electron quickstart app should work, as should ANY other electron app, I have tested a bunch of them, but all gave the same results, after you install a recent 20 beta. ### Actual Behavior They don't start if I use version 20.0.0-beta.9 or 20.0.0-beta.10, older versions *do* work. It only happens on *one* of the devices I own, *all* others are fine, but this one does not handle these new versions, while older ones work. This must have been introduced somewhere in [these commits between those releases](https://github.com/electron/electron/compare/v20.0.0-beta.8...v20.0.0-beta.9). ### Testcase Gist URL https://github.com/electron/electron-quick-start/ ### Additional Information Running electron with `gdb` does not give a lot of info, unless I'm running it incorrectly, please see below and let me know if this should be done differently: ```gdb jelmerro ~/electron-quick-start (master)$ gdb --args node node_modules/.bin/electron . GNU gdb (GDB) Fedora 12.1-1.fc35 Copyright (C) 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-redhat-linux-gnu". Type "show configuration" for configuration details. For bug reporting instructions, please see: <https://www.gnu.org/software/gdb/bugs/>. Find the GDB manual and other documentation resources online at: <http://www.gnu.org/software/gdb/documentation/>. For help, type "help". Type "apropos word" to search for commands related to "word"... Reading symbols from node... This GDB supports auto-downloading debuginfo from the following URLs: https://debuginfod.fedoraproject.org/ Enable debuginfod for this session? (y or [n]) y Debuginfod has been enabled. To make this setting permanent, add 'set debuginfod enabled on' to .gdbinit. Reading symbols from /home/jelmerro/.cache/debuginfod_client/adca03b9b7e322bf173d4a6972adea6c254bf914/debuginfo... (gdb) run Starting program: /usr/bin/node node_modules/.bin/electron . [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib64/libthread_db.so.1". [New Thread 0x7ffff23c0640 (LWP 12930)] [New Thread 0x7ffff1bbf640 (LWP 12931)] [New Thread 0x7ffff13be640 (LWP 12932)] [New Thread 0x7ffff0bbd640 (LWP 12933)] [New Thread 0x7fffebfff640 (LWP 12934)] [New Thread 0x7ffff7fbe640 (LWP 12935)] [Detaching after fork from child process 12936] /home/jelmerro/electron-quick-start/node_modules/electron/dist/electron exited with signal SIGTRAP [Thread 0x7fffebfff640 (LWP 12934) exited] [Thread 0x7ffff0bbd640 (LWP 12933) exited] [Thread 0x7ffff13be640 (LWP 12932) exited] [Thread 0x7ffff1bbf640 (LWP 12931) exited] [Thread 0x7ffff23c0640 (LWP 12930) exited] [Thread 0x7ffff7fbe640 (LWP 12935) exited] [Inferior 1 (process 12927) exited with code 01] ```
https://github.com/electron/electron/issues/34996
https://github.com/electron/electron/pull/35075
ff804e3a748c72f4812af8ccf3b1d7442a468f4a
62001dc6cbfd78a82d2fca849ca5eb0504cd0b71
2022-07-20T15:23:25Z
c++
2022-07-27T04:44:44Z
shell/browser/electron_browser_main_parts.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_main_parts.h" #include <memory> #include <string> #include <utility> #include "base/base_switches.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/metrics/field_trial.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/icon_manager.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "components/os_crypt/key_storage_config_linux.h" #include "components/os_crypt/os_crypt.h" #include "content/browser/browser_main_loop.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/device_service.h" #include "content/public/browser/first_party_sets_handler.h" #include "content/public/browser/web_ui_controller_factory.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/result_codes.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "media/base/localized_strings.h" #include "services/network/public/cpp/features.h" #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" #include "shell/app/electron_main_delegate.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/browser.h" #include "shell/browser/browser_process_impl.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_web_ui_controller_factory.h" #include "shell/browser/feature_list.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" #include "shell/browser/ui/devtools_manager_delegate.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_helper/trackable_object.h" #include "shell/common/logging.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/idle/idle.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_switches.h" #if defined(USE_AURA) #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/views/widget/desktop_aura/desktop_screen.h" #include "ui/wm/core/wm_state.h" #endif #if BUILDFLAG(IS_LINUX) #include "base/environment.h" #include "base/threading/thread_task_runner_handle.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h" #include "electron/electron_gtk_stubs.h" #include "ui/base/cursor/cursor_factory.h" #include "ui/base/ime/linux/linux_input_method_context_factory.h" #include "ui/gfx/color_utils.h" #include "ui/gtk/gtk_compat.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #include "ui/linux/linux_ui.h" #include "ui/linux/linux_ui_factory.h" #include "ui/ozone/public/ozone_platform.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/l10n/l10n_util_win.h" #include "ui/display/win/dpi.h" #include "ui/gfx/system_fonts_win.h" #include "ui/strings/grit/app_locale_settings.h" #endif #if BUILDFLAG(IS_MAC) #include "services/device/public/cpp/geolocation/geolocation_manager.h" #include "shell/browser/ui/cocoa/views_delegate_mac.h" #else #include "shell/browser/ui/views/electron_views_delegate.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck #endif namespace electron { namespace { template <typename T> void Erase(T* container, typename T::iterator iter) { container->erase(iter); } #if BUILDFLAG(IS_WIN) // gfx::Font callbacks void AdjustUIFont(gfx::win::FontAdjustment* font_adjustment) { l10n_util::NeedOverrideDefaultUIFont(&font_adjustment->font_family_override, &font_adjustment->font_scale); font_adjustment->font_scale *= display::win::GetAccessibilityFontScale(); } int GetMinimumFontSize() { int min_font_size; base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE), &min_font_size); return min_font_size; } #endif std::u16string MediaStringProvider(media::MessageId id) { switch (id) { case media::DEFAULT_AUDIO_DEVICE_NAME: return u"Default"; #if BUILDFLAG(IS_WIN) case media::COMMUNICATIONS_AUDIO_DEVICE_NAME: return u"Communications"; #endif default: return std::u16string(); } } #if BUILDFLAG(IS_LINUX) // GTK does not provide a way to check if current theme is dark, so we compare // the text and background luminosity to get a result. // This trick comes from FireFox. void UpdateDarkThemeSetting() { float bg = color_utils::GetRelativeLuminance(gtk::GetBgColor("GtkLabel")); float fg = color_utils::GetRelativeLuminance(gtk::GetFgColor("GtkLabel")); bool is_dark = fg > bg; // Pass it to NativeUi theme, which is used by the nativeTheme module and most // places in Electron. ui::NativeTheme::GetInstanceForNativeUi()->set_use_dark_colors(is_dark); // Pass it to Web Theme, to make "prefers-color-scheme" media query work. ui::NativeTheme::GetInstanceForWeb()->set_use_dark_colors(is_dark); } #endif } // namespace #if BUILDFLAG(IS_LINUX) class DarkThemeObserver : public ui::NativeThemeObserver { public: DarkThemeObserver() = default; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override { UpdateDarkThemeSetting(); } }; #endif // static ElectronBrowserMainParts* ElectronBrowserMainParts::self_ = nullptr; ElectronBrowserMainParts::ElectronBrowserMainParts() : fake_browser_process_(std::make_unique<BrowserProcessImpl>()), browser_(std::make_unique<Browser>()), node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kBrowser)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) { DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts"; self_ = this; } ElectronBrowserMainParts::~ElectronBrowserMainParts() = default; // static ElectronBrowserMainParts* ElectronBrowserMainParts::Get() { DCHECK(self_); return self_; } bool ElectronBrowserMainParts::SetExitCode(int code) { if (!exit_code_) return false; content::BrowserMainLoop::GetInstance()->SetResultCode(code); *exit_code_ = code; return true; } int ElectronBrowserMainParts::GetExitCode() const { return exit_code_.value_or(content::RESULT_CODE_NORMAL_EXIT); } int ElectronBrowserMainParts::PreEarlyInitialization() { field_trial_list_ = std::make_unique<base::FieldTrialList>(nullptr); #if BUILDFLAG(IS_POSIX) HandleSIGCHLD(); #endif #if BUILDFLAG(IS_LINUX) DetectOzonePlatform(); ui::OzonePlatform::PreEarlyInitialization(); #endif #if BUILDFLAG(IS_MAC) screen_ = std::make_unique<display::ScopedNativeScreen>(); #endif return GetExitCode(); } void ElectronBrowserMainParts::PostEarlyInitialization() { // A workaround was previously needed because there was no ThreadTaskRunner // set. If this check is failing we may need to re-add that workaround DCHECK(base::ThreadTaskRunnerHandle::IsSet()); // The ProxyResolverV8 has setup a complete V8 environment, in order to // avoid conflicts we only initialize our V8 environment after that. js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop()); v8::HandleScope scope(js_env_->isolate()); node_bindings_->Initialize(); // Create the global environment. node::Environment* env = node_bindings_->CreateEnvironment( js_env_->context(), js_env_->platform()); node_env_ = std::make_unique<NodeEnvironment>(env); env->set_trace_sync_io(env->options()->trace_sync_io); // We do not want to crash the main process on unhandled rejections. env->options()->unhandled_rejections = "warn"; // Add Electron extended APIs. electron_bindings_->BindTo(js_env_->isolate(), env->process_object()); // Load everything. node_bindings_->LoadEnvironment(env); // Wrap the uv loop with global env. node_bindings_->set_uv_env(env); // We already initialized the feature list in PreEarlyInitialization(), but // the user JS script would not have had a chance to alter the command-line // switches at that point. Lets reinitialize it here to pick up the // command-line changes. base::FeatureList::ClearInstanceForTesting(); InitializeFeatureList(); // Initialize field trials. InitializeFieldTrials(); // Reinitialize logging now that the app has had a chance to set the app name // and/or user data directory. logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(), /* is_preinit = */ false); // Initialize after user script environment creation. fake_browser_process_->PostEarlyInitialization(); } int ElectronBrowserMainParts::PreCreateThreads() { #if defined(USE_AURA) if (!display::Screen::GetScreen()) { screen_ = views::CreateDesktopScreen(); } #endif if (!views::LayoutProvider::Get()) layout_provider_ = std::make_unique<views::LayoutProvider>(); auto* command_line = base::CommandLine::ForCurrentProcess(); std::string locale = command_line->GetSwitchValueASCII(::switches::kLang); #if BUILDFLAG(IS_MAC) // The browser process only wants to support the language Cocoa will use, // so force the app locale to be overridden with that value. This must // happen before the ResourceBundle is loaded if (locale.empty()) l10n_util::OverrideLocaleWithCocoaLocale(); #elif BUILDFLAG(IS_LINUX) // l10n_util::GetApplicationLocaleInternal uses g_get_language_names(), // which keys off of getenv("LC_ALL"). // We must set this env first to make ui::ResourceBundle accept the custom // locale. auto env = base::Environment::Create(); absl::optional<std::string> lc_all; if (!locale.empty()) { std::string str; if (env->GetVar("LC_ALL", &str)) lc_all.emplace(std::move(str)); env->SetVar("LC_ALL", locale.c_str()); } #endif // Load resources bundle according to locale. std::string loaded_locale = LoadResourceBundle(locale); // Initialize the app locale. std::string app_locale = l10n_util::GetApplicationLocale(loaded_locale); ElectronBrowserClient::SetApplicationLocale(app_locale); fake_browser_process_->SetApplicationLocale(app_locale); #if BUILDFLAG(IS_LINUX) // Reset to the original LC_ALL since we should not be changing it. if (!locale.empty()) { if (lc_all) env->SetVar("LC_ALL", *lc_all); else env->UnSetVar("LC_ALL"); } #endif // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); #if BUILDFLAG(IS_MAC) ui::InitIdleMonitor(); #endif fake_browser_process_->PreCreateThreads(); // Notify observers. Browser::Get()->PreCreateThreads(); return 0; } void ElectronBrowserMainParts::PostCreateThreads() { content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread)); } void ElectronBrowserMainParts::PostDestroyThreads() { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_browser_client_.reset(); extensions::ExtensionsBrowserClient::Set(nullptr); #endif #if BUILDFLAG(IS_LINUX) device::BluetoothAdapterFactory::Shutdown(); bluez::DBusBluezManagerWrapperLinux::Shutdown(); #endif fake_browser_process_->PostDestroyThreads(); } void ElectronBrowserMainParts::ToolkitInitialized() { #if BUILDFLAG(IS_LINUX) auto linux_ui = ui::CreateLinuxUi(); DCHECK(ui::LinuxInputMethodContextFactory::instance()); // Try loading gtk symbols used by Electron. electron::InitializeElectron_gtk(gtk::GetLibGtk()); if (!electron::IsElectron_gtkInitialized()) { electron::UninitializeElectron_gtk(); } electron::InitializeElectron_gdk_pixbuf(gtk::GetLibGdkPixbuf()); CHECK(electron::IsElectron_gdk_pixbufInitialized()) << "Failed to initialize libgdk_pixbuf-2.0.so.0"; // Chromium does not respect GTK dark theme setting, but they may change // in future and this code might be no longer needed. Check the Chromium // issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=998903 UpdateDarkThemeSetting(); // Update the native theme when GTK theme changes. The GetNativeTheme // here returns a NativeThemeGtk, which monitors GTK settings. dark_theme_observer_ = std::make_unique<DarkThemeObserver>(); linux_ui->GetNativeTheme(nullptr)->AddObserver(dark_theme_observer_.get()); ui::LinuxUi::SetInstance(std::move(linux_ui)); // Cursor theme changes are tracked by LinuxUI (via a CursorThemeManager // implementation). Start observing them once it's initialized. ui::CursorFactory::GetInstance()->ObserveThemeChanges(); #endif #if defined(USE_AURA) wm_state_ = std::make_unique<wm::WMState>(); #endif #if BUILDFLAG(IS_WIN) gfx::win::SetAdjustFontCallback(&AdjustUIFont); gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize); #endif #if BUILDFLAG(IS_MAC) views_delegate_ = std::make_unique<ViewsDelegateMac>(); #else views_delegate_ = std::make_unique<ViewsDelegate>(); #endif } int ElectronBrowserMainParts::PreMainMessageLoopRun() { // Run user's main script before most things get initialized, so we can have // a chance to setup everything. node_bindings_->PrepareEmbedThread(); node_bindings_->StartPolling(); // url::Add*Scheme are not threadsafe, this helps prevent data races. url::LockSchemeRegistries(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_client_ = std::make_unique<ElectronExtensionsClient>(); extensions::ExtensionsClient::Set(extensions_client_.get()); // BrowserContextKeyedAPIServiceFactories require an ExtensionsBrowserClient. extensions_browser_client_ = std::make_unique<ElectronExtensionsBrowserClient>(); extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get()); extensions::EnsureBrowserContextKeyedServiceFactoriesBuilt(); extensions::electron::EnsureBrowserContextKeyedServiceFactoriesBuilt(); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckServiceFactory::GetInstance(); #endif content::WebUIControllerFactory::RegisterFactory( ElectronWebUIControllerFactory::GetInstance()); auto* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kRemoteDebuggingPipe)) { // --remote-debugging-pipe auto on_disconnect = base::BindOnce([]() { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce([]() { Browser::Get()->Quit(); })); }); content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler( std::move(on_disconnect)); } else if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) { // --remote-debugging-port DevToolsManagerDelegate::StartHttpHandler(); } #if !BUILDFLAG(IS_MAC) // The corresponding call in macOS is in ElectronApplicationDelegate. Browser::Get()->WillFinishLaunching(); Browser::Get()->DidFinishLaunching(base::Value::Dict()); #endif // Notify observers that main thread message loop was initialized. Browser::Get()->PreMainMessageLoopRun(); return GetExitCode(); } void ElectronBrowserMainParts::WillRunMainMessageLoop( std::unique_ptr<base::RunLoop>& run_loop) { js_env_->OnMessageLoopCreated(); exit_code_ = content::RESULT_CODE_NORMAL_EXIT; Browser::Get()->SetMainMessageLoopQuitClosure( run_loop->QuitWhenIdleClosure()); } void ElectronBrowserMainParts::PostCreateMainMessageLoop() { #if BUILDFLAG(IS_LINUX) auto shutdown_cb = base::BindOnce(base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); ui::OzonePlatform::GetInstance()->PostCreateMainMessageLoop( std::move(shutdown_cb)); bluez::DBusBluezManagerWrapperLinux::Initialize(); // Set up crypt config. This needs to be done before anything starts the // network service, as the raw encryption key needs to be shared with the // network service for encrypted cookie storage. std::string app_name = electron::Browser::Get()->GetName(); const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); std::unique_ptr<os_crypt::Config> config = std::make_unique<os_crypt::Config>(); // Forward to os_crypt the flag to use a specific password store. config->store = command_line.GetSwitchValueASCII(::switches::kPasswordStore); config->product_name = app_name; config->application_name = app_name; config->main_thread_runner = base::ThreadTaskRunnerHandle::Get(); // c.f. // https://source.chromium.org/chromium/chromium/src/+/master:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1 config->should_use_preference = command_line.HasSwitch(::switches::kEnableEncryptionSelection); base::PathService::Get(DIR_SESSION_DATA, &config->user_data_path); OSCrypt::SetConfig(std::move(config)); #endif #if BUILDFLAG(IS_POSIX) // Exit in response to SIGINT, SIGTERM, etc. InstallShutdownSignalHandlers( base::BindOnce(&Browser::Quit, base::Unretained(Browser::Get())), content::GetUIThreadTaskRunner({})); #endif } void ElectronBrowserMainParts::PostMainMessageLoopRun() { #if BUILDFLAG(IS_MAC) FreeAppDelegate(); #endif // Shutdown the DownloadManager before destroying Node to prevent // DownloadItem callbacks from crashing. for (auto& iter : ElectronBrowserContext::browser_context_map()) { auto* download_manager = iter.second.get()->GetDownloadManager(); if (download_manager) { download_manager->Shutdown(); } } // Destroy node platform after all destructors_ are executed, as they may // invoke Node/V8 APIs inside them. node_env_->env()->set_trace_sync_io(false); js_env_->OnMessageLoopDestroying(); node::Stop(node_env_->env()); node_env_.reset(); auto default_context_key = ElectronBrowserContext::PartitionKey("", false); std::unique_ptr<ElectronBrowserContext> default_context = std::move( ElectronBrowserContext::browser_context_map()[default_context_key]); ElectronBrowserContext::browser_context_map().clear(); default_context.reset(); fake_browser_process_->PostMainMessageLoopRun(); content::DevToolsAgentHost::StopRemoteDebuggingPipeHandler(); #if BUILDFLAG(IS_LINUX) ui::OzonePlatform::GetInstance()->PostMainMessageLoopRun(); #endif } #if !BUILDFLAG(IS_MAC) void ElectronBrowserMainParts::PreCreateMainMessageLoop() { PreCreateMainMessageLoopCommon(); } #endif void ElectronBrowserMainParts::PreCreateMainMessageLoopCommon() { #if BUILDFLAG(IS_MAC) InitializeMainNib(); RegisterURLHandler(); #endif media::SetLocalizedStringProvider(MediaStringProvider); #if BUILDFLAG(IS_WIN) auto* local_state = g_browser_process->local_state(); DCHECK(local_state); bool os_crypt_init = OSCrypt::Init(local_state); DCHECK(os_crypt_init); #endif } device::mojom::GeolocationControl* ElectronBrowserMainParts::GetGeolocationControl() { if (!geolocation_control_) { content::GetDeviceService().BindGeolocationControl( geolocation_control_.BindNewPipeAndPassReceiver()); } return geolocation_control_.get(); } #if BUILDFLAG(IS_MAC) device::GeolocationManager* ElectronBrowserMainParts::GetGeolocationManager() { return geolocation_manager_.get(); } #endif IconManager* ElectronBrowserMainParts::GetIconManager() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!icon_manager_.get()) icon_manager_ = std::make_unique<IconManager>(); return icon_manager_.get(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,046
[Bug]: webContents.getUserAgent() is empty since 20.0.0-alpha.6
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.0-alpha.6 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version 20.0.0-alpha.5 ### Expected Behavior `webContents.getUserAgent()` returns a string with a user Agent ### Actual Behavior webContents.getUserAgent() returns an empty string ### Testcase Gist URL https://gist.github.com/33fd4a9ac6db6b28b1dcc5b765edb622 ### Additional Information In the console the user agent is printed in alpha.5, but empty in alpha.6. Looking at the diff between alpha.5 and alpha.6, this PR seems the likely cause: https://github.com/electron/electron/pull/34524 / #34481 It's worth noting that the renderer does have a filled-in userAgent.
https://github.com/electron/electron/issues/35046
https://github.com/electron/electron/pull/35069
8004cb8722c8d52f4cd553bbaea86750149e8ca4
9028bb79a85fedf64230c2f1c6a29ab072c98c20
2022-07-25T14:12:09Z
c++
2022-07-29T15:09:47Z
shell/browser/api/electron_api_web_contents.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_web_contents.h" #include <limits> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/containers/id_map.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/no_destructor.h" #include "base/strings/utf_string_conversions.h" #include "base/task/current_thread.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/views/eye_dropper/eye_dropper.h" #include "chrome/common/pref_names.h" #include "components/embedder_support/user_agent_utils.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/security_state/content/content_utils.h" #include "components/security_state/core/security_state.h" #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck #include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/context_menu_params.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/desktop_streams_registry.h" #include "content/public/browser/download_request_utils.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/service_worker_context.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/referrer_type_converters.h" #include "content/public/common/webplugininfo.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/arguments.h" #include "gin/data_object_builder.h" #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/system/platform_handle.h" #include "ppapi/buildflags/buildflags.h" #include "printing/buildflags/buildflags.h" #include "printing/print_job_constants.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "shell/browser/api/electron_api_browser_window.h" #include "shell/browser/api/electron_api_debugger.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/api/electron_api_web_frame_main.h" #include "shell/browser/api/message_port.h" #include "shell/browser/browser.h" #include "shell/browser/child_web_contents_tracker.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_javascript_dialog_manager.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/file_select_helper.h" #include "shell/browser/native_window.h" #include "shell/browser/session_preferences.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_contents_zoom_controller.h" #include "shell/browser/web_view_guest_delegate.h" #include "shell/browser/web_view_manager.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/color_util.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/base_converter.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/content_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/net_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/language_util.h" #include "shell/common/mouse_util.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "shell/common/v8_value_serializer.h" #include "storage/browser/file_system/isolated_context.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "third_party/blink/public/mojom/frame/find_in_page.mojom.h" #include "third_party/blink/public/mojom/frame/fullscreen.mojom.h" #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" #include "third_party/blink/public/mojom/renderer_preferences.mojom.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/display/screen.h" #include "ui/events/base_event_utils.h" #if BUILDFLAG(ENABLE_OSR) #include "shell/browser/osr/osr_render_widget_host_view.h" #include "shell/browser/osr/osr_web_contents_view.h" #endif #if !BUILDFLAG(IS_MAC) #include "ui/aura/window.h" #else #include "ui/base/cocoa/defaults_utils.h" #endif #if BUILDFLAG(IS_LINUX) #include "ui/linux/linux_ui.h" #endif #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) #include "ui/gfx/font_render_params.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/script_executor.h" #include "extensions/browser/view_type_utils.h" #include "extensions/common/mojom/view_type.mojom.h" #include "shell/browser/extensions/electron_extension_web_contents_observer.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "chrome/browser/printing/print_view_manager_base.h" #include "components/printing/browser/print_manager_utils.h" #include "components/printing/browser/print_to_pdf/pdf_print_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" // nogncheck #include "printing/page_range.h" #include "shell/browser/printing/print_view_manager_electron.h" #if BUILDFLAG(IS_WIN) #include "printing/backend/win_helper.h" #endif #endif #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h" #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck #include "shell/browser/electron_pdf_web_contents_helper_client.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #endif #ifndef MAS_BUILD #include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck #endif namespace gin { #if BUILDFLAG(ENABLE_PRINTING) template <> struct Converter<printing::mojom::MarginType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::MarginType* out) { std::string type; if (ConvertFromV8(isolate, val, &type)) { if (type == "default") { *out = printing::mojom::MarginType::kDefaultMargins; return true; } if (type == "none") { *out = printing::mojom::MarginType::kNoMargins; return true; } if (type == "printableArea") { *out = printing::mojom::MarginType::kPrintableAreaMargins; return true; } if (type == "custom") { *out = printing::mojom::MarginType::kCustomMargins; return true; } } return false; } }; template <> struct Converter<printing::mojom::DuplexMode> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::DuplexMode* out) { std::string mode; if (ConvertFromV8(isolate, val, &mode)) { if (mode == "simplex") { *out = printing::mojom::DuplexMode::kSimplex; return true; } if (mode == "longEdge") { *out = printing::mojom::DuplexMode::kLongEdge; return true; } if (mode == "shortEdge") { *out = printing::mojom::DuplexMode::kShortEdge; return true; } } return false; } }; #endif template <> struct Converter<WindowOpenDisposition> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, WindowOpenDisposition val) { std::string disposition = "other"; switch (val) { case WindowOpenDisposition::CURRENT_TAB: disposition = "default"; break; case WindowOpenDisposition::NEW_FOREGROUND_TAB: disposition = "foreground-tab"; break; case WindowOpenDisposition::NEW_BACKGROUND_TAB: disposition = "background-tab"; break; case WindowOpenDisposition::NEW_POPUP: case WindowOpenDisposition::NEW_WINDOW: disposition = "new-window"; break; case WindowOpenDisposition::SAVE_TO_DISK: disposition = "save-to-disk"; break; default: break; } return gin::ConvertToV8(isolate, disposition); } }; template <> struct Converter<content::SavePageType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, content::SavePageType* out) { std::string save_type; if (!ConvertFromV8(isolate, val, &save_type)) return false; save_type = base::ToLowerASCII(save_type); if (save_type == "htmlonly") { *out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML; } else if (save_type == "htmlcomplete") { *out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML; } else if (save_type == "mhtml") { *out = content::SAVE_PAGE_TYPE_AS_MHTML; } else { return false; } return true; } }; template <> struct Converter<electron::api::WebContents::Type> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, electron::api::WebContents::Type val) { using Type = electron::api::WebContents::Type; std::string type; switch (val) { case Type::kBackgroundPage: type = "backgroundPage"; break; case Type::kBrowserWindow: type = "window"; break; case Type::kBrowserView: type = "browserView"; break; case Type::kRemote: type = "remote"; break; case Type::kWebView: type = "webview"; break; case Type::kOffScreen: type = "offscreen"; break; default: break; } return gin::ConvertToV8(isolate, type); } static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, electron::api::WebContents::Type* out) { using Type = electron::api::WebContents::Type; std::string type; if (!ConvertFromV8(isolate, val, &type)) return false; if (type == "backgroundPage") { *out = Type::kBackgroundPage; } else if (type == "browserView") { *out = Type::kBrowserView; } else if (type == "webview") { *out = Type::kWebView; #if BUILDFLAG(ENABLE_OSR) } else if (type == "offscreen") { *out = Type::kOffScreen; #endif } else { return false; } return true; } }; template <> struct Converter<scoped_refptr<content::DevToolsAgentHost>> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const scoped_refptr<content::DevToolsAgentHost>& val) { gin_helper::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("id", val->GetId()); dict.Set("url", val->GetURL().spec()); return dict.GetHandle(); } }; } // namespace gin namespace electron::api { namespace { base::IDMap<WebContents*>& GetAllWebContents() { static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents; return *s_all_web_contents; } // Called when CapturePage is done. void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); } absl::optional<base::TimeDelta> GetCursorBlinkInterval() { #if BUILDFLAG(IS_MAC) absl::optional<base::TimeDelta> system_value( ui::TextInsertionCaretBlinkPeriodFromDefaults()); if (system_value) return *system_value; #elif BUILDFLAG(IS_LINUX) if (auto* linux_ui = ui::LinuxUi::instance()) return linux_ui->GetCursorBlinkInterval(); #elif BUILDFLAG(IS_WIN) const auto system_msec = ::GetCaretBlinkTime(); if (system_msec != 0) { return (system_msec == INFINITE) ? base::TimeDelta() : base::Milliseconds(system_msec); } #endif return absl::nullopt; } #if BUILDFLAG(ENABLE_PRINTING) // This will return false if no printer with the provided device_name can be // found on the network. We need to check this because Chromium does not do // sanity checking of device_name validity and so will crash on invalid names. bool IsDeviceNameValid(const std::u16string& device_name) { #if BUILDFLAG(IS_MAC) base::ScopedCFTypeRef<CFStringRef> new_printer_id( base::SysUTF16ToCFStringRef(device_name)); PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get()); bool printer_exists = new_printer != nullptr; PMRelease(new_printer); return printer_exists; #else scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name)); #endif } // This function returns a validated device name. // If the user passed one to webContents.print(), we check that it's valid and // return it or fail if the network doesn't recognize it. If the user didn't // pass a device name, we first try to return the system default printer. If one // isn't set, then pull all the printers and use the first one or fail if none // exist. std::pair<std::string, std::u16string> GetDeviceNameToUse( const std::u16string& device_name) { #if BUILDFLAG(IS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ThreadRestrictions::ScopedAllowIO allow_io; #endif if (!device_name.empty()) { if (!IsDeviceNameValid(device_name)) return std::make_pair("Invalid deviceName provided", std::u16string()); return std::make_pair(std::string(), device_name); } scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); std::string printer_name; printing::mojom::ResultCode code = print_backend->GetDefaultPrinterName(printer_name); // We don't want to return if this fails since some devices won't have a // default printer. if (code != printing::mojom::ResultCode::kSuccess) LOG(ERROR) << "Failed to get default printer name"; if (printer_name.empty()) { printing::PrinterList printers; if (print_backend->EnumeratePrinters(printers) != printing::mojom::ResultCode::kSuccess) return std::make_pair("Failed to enumerate printers", std::u16string()); if (printers.empty()) return std::make_pair("No printers available on the network", std::u16string()); printer_name = printers.front().printer_name; } return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name)); } // Copied from // chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54 scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() { // USER_VISIBLE because the result is displayed in the print preview dialog. #if !BUILDFLAG(IS_WIN) static constexpr base::TaskTraits kTraits = { base::MayBlock(), base::TaskPriority::USER_VISIBLE}; #endif #if defined(USE_CUPS) // CUPS is thread safe. return base::ThreadPool::CreateTaskRunner(kTraits); #elif BUILDFLAG(IS_WIN) // Windows drivers are likely not thread-safe and need to be accessed on the // UI thread. return content::GetUIThreadTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); #else // Be conservative on unsupported platforms. return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits); #endif } #endif struct UserDataLink : public base::SupportsUserData::Data { explicit UserDataLink(base::WeakPtr<WebContents> contents) : web_contents(contents) {} base::WeakPtr<WebContents> web_contents; }; const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey; const char kRootName[] = "<root>"; struct FileSystem { FileSystem() = default; FileSystem(const std::string& type, const std::string& file_system_name, const std::string& root_url, const std::string& file_system_path) : type(type), file_system_name(file_system_name), root_url(root_url), file_system_path(file_system_path) {} std::string type; std::string file_system_name; std::string root_url; std::string file_system_path; }; std::string RegisterFileSystem(content::WebContents* web_contents, const base::FilePath& path) { auto* isolated_context = storage::IsolatedContext::GetInstance(); std::string root_name(kRootName); storage::IsolatedContext::ScopedFSHandle file_system = isolated_context->RegisterFileSystemForPath( storage::kFileSystemTypeLocal, std::string(), path, &root_name); content::ChildProcessSecurityPolicy* policy = content::ChildProcessSecurityPolicy::GetInstance(); content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost(); int renderer_id = render_view_host->GetProcess()->GetID(); policy->GrantReadFileSystem(renderer_id, file_system.id()); policy->GrantWriteFileSystem(renderer_id, file_system.id()); policy->GrantCreateFileForFileSystem(renderer_id, file_system.id()); policy->GrantDeleteFromFileSystem(renderer_id, file_system.id()); if (!policy->CanReadFile(renderer_id, path)) policy->GrantReadFile(renderer_id, path); return file_system.id(); } FileSystem CreateFileSystemStruct(content::WebContents* web_contents, const std::string& file_system_id, const std::string& file_system_path, const std::string& type) { const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL(); std::string file_system_name = storage::GetIsolatedFileSystemName(origin, file_system_id); std::string root_url = storage::GetIsolatedFileSystemRootURIString( origin, file_system_id, kRootName); return FileSystem(type, file_system_name, root_url, file_system_path); } base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) { base::Value::Dict value; value.Set("type", file_system.type); value.Set("fileSystemName", file_system.file_system_name); value.Set("rootURL", file_system.root_url); value.Set("fileSystemPath", file_system.file_system_path); return value; } void WriteToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::WriteFile(path, content.data(), content.size()); } void AppendToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::AppendToFile(path, content); } PrefService* GetPrefService(content::WebContents* web_contents) { auto* context = web_contents->GetBrowserContext(); return static_cast<electron::ElectronBrowserContext*>(context)->prefs(); } std::map<std::string, std::string> GetAddedFileSystemPaths( content::WebContents* web_contents) { auto* pref_service = GetPrefService(web_contents); const base::Value* file_system_paths_value = pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; if (file_system_paths_value) { const base::DictionaryValue* file_system_paths_dict; file_system_paths_value->GetAsDictionary(&file_system_paths_dict); for (auto it : file_system_paths_dict->DictItems()) { std::string type = it.second.is_string() ? it.second.GetString() : std::string(); result[it.first] = type; } } return result; } bool IsDevToolsFileSystemAdded(content::WebContents* web_contents, const std::string& file_system_path) { auto file_system_paths = GetAddedFileSystemPaths(web_contents); return file_system_paths.find(file_system_path) != file_system_paths.end(); } void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } } // namespace #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) { switch (view_type) { case extensions::mojom::ViewType::kExtensionBackgroundPage: return WebContents::Type::kBackgroundPage; case extensions::mojom::ViewType::kAppWindow: case extensions::mojom::ViewType::kComponent: case extensions::mojom::ViewType::kExtensionDialog: case extensions::mojom::ViewType::kExtensionPopup: case extensions::mojom::ViewType::kBackgroundContents: case extensions::mojom::ViewType::kExtensionGuest: case extensions::mojom::ViewType::kTabContents: case extensions::mojom::ViewType::kOffscreenDocument: case extensions::mojom::ViewType::kInvalid: return WebContents::Type::kRemote; } } #endif WebContents::WebContents(v8::Isolate* isolate, content::WebContents* web_contents) : content::WebContentsObserver(web_contents), type_(Type::kRemote), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // WebContents created by extension host will have valid ViewType set. extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents); if (view_type != extensions::mojom::ViewType::kInvalid) { InitWithExtensionView(isolate, web_contents, view_type); } extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents); #endif auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); absl::optional<std::string> user_agent_override = GetBrowserContext()->GetUserAgentOverride(); if (user_agent_override) SetUserAgent(*user_agent_override); web_contents->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) : content::WebContentsObserver(web_contents.get()), type_(type), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { DCHECK(type != Type::kRemote) << "Can't take ownership of a remote WebContents"; auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); InitWithSessionAndOptions(isolate, std::move(web_contents), session, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options) : id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { // Read options. options.Get("backgroundThrottling", &background_throttling_); // Get type options.Get("type", &type_); #if BUILDFLAG(ENABLE_OSR) bool b = false; if (options.Get(options::kOffscreen, &b) && b) type_ = Type::kOffScreen; #endif // Init embedder earlier options.Get("embedder", &embedder_); // Whether to enable DevTools. options.Get("devTools", &enable_devtools_); // BrowserViews are not attached to a window initially so they should start // off as hidden. This is also important for compositor recycling. See: // https://github.com/electron/electron/pull/21372 bool initially_shown = type_ != Type::kBrowserView; options.Get(options::kShow, &initially_shown); // Obtain the session. std::string partition; gin::Handle<api::Session> session; if (options.Get("session", &session) && !session.IsEmpty()) { } else if (options.Get("partition", &partition)) { session = Session::FromPartition(isolate, partition); } else { // Use the default session if not specified. session = Session::FromPartition(isolate, ""); } session_.Reset(isolate, session.ToV8()); std::unique_ptr<content::WebContents> web_contents; if (IsGuest()) { scoped_refptr<content::SiteInstance> site_instance = content::SiteInstance::CreateForURL(session->browser_context(), GURL("chrome-guest://fake-host")); content::WebContents::CreateParams params(session->browser_context(), site_instance); guest_delegate_ = std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this); params.guest_delegate = guest_delegate_.get(); #if BUILDFLAG(ENABLE_OSR) if (embedder_ && embedder_->IsOffScreen()) { auto* view = new OffScreenWebContentsView( false, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); } else { #endif web_contents = content::WebContents::Create(params); #if BUILDFLAG(ENABLE_OSR) } } else if (IsOffScreen()) { // webPreferences does not have a transparent option, so if the window needs // to be transparent, that will be set at electron_api_browser_window.cc#L57 // and we then need to pull it back out and check it here. std::string background_color; options.GetHidden(options::kBackgroundColor, &background_color); bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT; content::WebContents::CreateParams params(session->browser_context()); auto* view = new OffScreenWebContentsView( transparent, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); #endif } else { content::WebContents::CreateParams params(session->browser_context()); params.initially_hidden = !initially_shown; web_contents = content::WebContents::Create(params); } InitWithSessionAndOptions(isolate, std::move(web_contents), session, options); } void WebContents::InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options) { WebContentsZoomController::CreateForWebContents(web_contents); zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents); double zoom_factor; if (options.Get(options::kZoomFactor, &zoom_factor)) zoom_controller_->SetDefaultZoomFactor(zoom_factor); } void WebContents::InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> owned_web_contents, gin::Handle<api::Session> session, const gin_helper::Dictionary& options) { Observe(owned_web_contents.get()); InitWithWebContents(std::move(owned_web_contents), session->browser_context(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); auto* prefs = web_contents()->GetMutableRendererPrefs(); // Collect preferred languages from OS and browser process. accept_languages // effects HTTP header, navigator.languages, and CJK fallback font selection. // // Note that an application locale set to the browser process might be // different with the one set to the preference list. // (e.g. overridden with --lang) std::string accept_languages = g_browser_process->GetApplicationLocale() + ","; for (auto const& language : electron::GetPreferredLanguages()) { if (language == g_browser_process->GetApplicationLocale()) continue; accept_languages += language + ","; } accept_languages.pop_back(); prefs->accept_languages = accept_languages; #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) // Update font settings. static const gfx::FontRenderParams params( gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr)); prefs->should_antialias_text = params.antialiasing; prefs->use_subpixel_positioning = params.subpixel_positioning; prefs->hinting = params.hinting; prefs->use_autohinter = params.autohinter; prefs->use_bitmaps = params.use_bitmaps; prefs->subpixel_rendering = params.subpixel_rendering; #endif // Honor the system's cursor blink rate settings if (auto interval = GetCursorBlinkInterval()) prefs->caret_blink_interval = *interval; // Save the preferences in C++. // If there's already a WebContentsPreferences object, we created it as part // of the webContents.setWindowOpenHandler path, so don't overwrite it. if (!WebContentsPreferences::From(web_contents())) { new WebContentsPreferences(web_contents(), options); } // Trigger re-calculation of webkit prefs. web_contents()->NotifyPreferencesChanged(); WebContentsPermissionHelper::CreateForWebContents(web_contents()); InitZoomController(web_contents(), options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents()); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents()); #endif AutofillDriverFactory::CreateForWebContents(web_contents()); absl::optional<std::string> user_agent_override = GetBrowserContext()->GetUserAgentOverride(); if (user_agent_override) SetUserAgent(*user_agent_override); if (IsGuest()) { NativeWindow* owner_window = nullptr; if (embedder_) { // New WebContents's owner_window is the embedder's owner_window. auto* relay = NativeWindowRelay::FromWebContents(embedder_->web_contents()); if (relay) owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); } web_contents()->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void WebContents::InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::mojom::ViewType view_type) { // Must reassign type prior to calling `Init`. type_ = GetTypeFromViewType(view_type); if (type_ == Type::kRemote) return; if (type_ == Type::kBackgroundPage) // non-background-page WebContents are retained by other classes. We need // to pin here to prevent background-page WebContents from being GC'd. // The background page api::WebContents will live until the underlying // content::WebContents is destroyed. Pin(isolate); // Allow toggling DevTools for background pages Observe(web_contents); InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents), GetBrowserContext(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); } #endif void WebContents::InitWithWebContents( std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest) { browser_context_ = browser_context; web_contents->SetDelegate(this); #if BUILDFLAG(ENABLE_PRINTING) PrintViewManagerElectron::CreateForWebContents(web_contents.get()); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) pdf::PDFWebContentsHelper::CreateForWebContentsWithClient( web_contents.get(), std::make_unique<ElectronPDFWebContentsHelperClient>()); #endif // Determine whether the WebContents is offscreen. auto* web_preferences = WebContentsPreferences::From(web_contents.get()); offscreen_ = web_preferences && web_preferences->IsOffscreen(); // Create InspectableWebContents. inspectable_web_contents_ = std::make_unique<InspectableWebContents>( std::move(web_contents), browser_context->prefs(), is_guest); inspectable_web_contents_->SetDelegate(this); } WebContents::~WebContents() { if (!inspectable_web_contents_) { WebContentsDestroyed(); return; } inspectable_web_contents_->GetView()->SetDelegate(nullptr); // This event is only for internal use, which is emitted when WebContents is // being destroyed. Emit("will-destroy"); // For guest view based on OOPIF, the WebContents is released by the embedder // frame, and we need to clear the reference to the memory. bool not_owned_by_this = IsGuest() && attached_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // And background pages are owned by extensions::ExtensionHost. if (type_ == Type::kBackgroundPage) not_owned_by_this = true; #endif if (not_owned_by_this) { inspectable_web_contents_->ReleaseWebContents(); WebContentsDestroyed(); } // InspectableWebContents will be automatically destroyed. } void WebContents::DeleteThisIfAlive() { // It is possible that the FirstWeakCallback has been called but the // SecondWeakCallback has not, in this case the garbage collection of // WebContents has already started and we should not |delete this|. // Calling |GetWrapper| can detect this corner case. auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; delete this; } void WebContents::Destroy() { // The content::WebContents should be destroyed asynchronously when possible // as user may choose to destroy WebContents during an event of it. if (Browser::Get()->is_shutting_down() || IsGuest()) { DeleteThisIfAlive(); } else { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce( [](base::WeakPtr<WebContents> contents) { if (contents) contents->DeleteThisIfAlive(); }, GetWeakPtr())); } } bool WebContents::DidAddMessageToConsole( content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) { return Emit("console-message", static_cast<int32_t>(level), message, line_no, source_id); } void WebContents::OnCreateWindow( const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const std::string& features, const scoped_refptr<network::ResourceRequestBody>& body) { Emit("-new-window", target_url, frame_name, disposition, features, referrer, body); } void WebContents::WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) { ChildWebContentsTracker::CreateForWebContents(new_contents); auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents); tracker->url = params.target_url; tracker->frame_name = params.frame_name; tracker->referrer = params.referrer.To<content::Referrer>(); tracker->raw_features = params.raw_features; tracker->body = params.body; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary dict; gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate), &dict); pending_child_web_preferences_.Reset(); // Associate the preferences passed in via `setWindowOpenHandler` with the // content::WebContents that was just created for the child window. These // preferences will be picked up by the RenderWidgetHost via its call to the // delegate's OverrideWebkitPrefs. new WebContentsPreferences(new_contents, dict); } bool WebContents::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) { bool default_prevented = Emit( "-will-add-new-contents", params.target_url, params.frame_name, params.raw_features, params.disposition, *params.referrer, params.body); // If the app prevented the default, redirect to CreateCustomWebContents, // which always returns nullptr, which will result in the window open being // prevented (window.open() will return null in the renderer). return default_prevented; } void WebContents::SetNextChildWebPreferences( const gin_helper::Dictionary preferences) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); // Store these prefs for when Chrome calls WebContentsCreatedWithFullParams // with the new child contents. pending_child_web_preferences_.Reset(isolate, preferences.GetHandle()); } content::WebContents* WebContents::CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionConfig& partition_config, content::SessionStorageNamespace* session_storage_namespace) { return nullptr; } void WebContents::AddNewContents( content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, 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, initial_rect.x(), initial_rect.y(), initial_rect.width(), initial_rect.height(), tracker->url, tracker->frame_name, tracker->referrer, tracker->raw_features, tracker->body)) { api_web_contents->Destroy(); } } content::WebContents* WebContents::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { auto weak_this = GetWeakPtr(); if (params.disposition != WindowOpenDisposition::CURRENT_TAB) { Emit("-new-window", params.url, "", params.disposition, "", params.referrer, params.post_data); return nullptr; } if (!weak_this || !web_contents()) return nullptr; content::NavigationController::LoadURLParams load_url_params(params.url); load_url_params.referrer = params.referrer; load_url_params.transition_type = params.transition; load_url_params.extra_headers = params.extra_headers; load_url_params.should_replace_current_entry = params.should_replace_current_entry; load_url_params.is_renderer_initiated = params.is_renderer_initiated; load_url_params.started_from_context_menu = params.started_from_context_menu; load_url_params.initiator_origin = params.initiator_origin; load_url_params.source_site_instance = params.source_site_instance; load_url_params.frame_tree_node_id = params.frame_tree_node_id; load_url_params.redirect_chain = params.redirect_chain; load_url_params.has_user_gesture = params.user_gesture; load_url_params.blob_url_loader_factory = params.blob_url_loader_factory; load_url_params.href_translate = params.href_translate; load_url_params.reload_type = params.reload_type; if (params.post_data) { load_url_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; load_url_params.post_data = params.post_data; } source->GetController().LoadURLWithParams(load_url_params); return source; } void WebContents::BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen || type_ == Type::kBrowserView) *proceed_to_fire_unload = proceed; else *proceed_to_fire_unload = true; // Note that Chromium does not emit this for navigations. Emit("before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnSetContentBounds(rect); } void WebContents::CloseContents(content::WebContents* source) { Emit("close"); auto* autofill_driver_factory = AutofillDriverFactory::FromWebContents(web_contents()); if (autofill_driver_factory) { autofill_driver_factory->CloseAllPopups(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); } void WebContents::ActivateContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnActivateContents(); } void WebContents::UpdateTargetURL(content::WebContents* source, const GURL& url) { Emit("update-target-url", url); } bool WebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (type_ == Type::kWebView && embedder_) { // Send the unhandled keyboard events back to the embedder. return embedder_->HandleKeyboardEvent(source, event); } else { return PlatformHandleKeyboardEvent(source, event); } } #if !BUILDFLAG(IS_MAC) // NOTE: The macOS version of this function is found in // electron_api_web_contents_mac.mm, as it requires calling into objective-C // code. bool WebContents::PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { // Escape exits tabbed fullscreen mode. if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { ExitFullscreenModeForTab(source); return true; } // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts()) return false; // Let the NativeWindow handle other parts. if (owner_window()) { owner_window()->HandleKeyboardEvent(source, event); return true; } return false; } #endif content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (exclusive_access_manager_->HandleUserKeyEvent(event)) return content::KeyboardEventProcessingResult::HANDLED; if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kKeyUp) { bool prevent_default = Emit("before-input-event", event); if (prevent_default) { return content::KeyboardEventProcessingResult::HANDLED; } } return content::KeyboardEventProcessingResult::NOT_HANDLED; } void WebContents::ContentsZoomChange(bool zoom_in) { Emit("zoom-changed", zoom_in ? "in" : "out"); } Profile* WebContents::GetProfile() { return nullptr; } bool WebContents::IsFullscreen() const { return owner_window_ && owner_window_->IsFullscreen(); } void WebContents::EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) {} void WebContents::ExitFullscreen() {} void WebContents::UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool 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(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; } exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); SetHtmlApiFullscreen(true); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { if (!owner_window_) return; // This needs to be called before we exit fullscreen on the native window, // or the controller will incorrectly think we weren't fullscreen and bail. exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab( source); SetHtmlApiFullscreen(false); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. Chrome does this indirectly from // `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) { Emit("unresponsive"); } void WebContents::RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) { Emit("responsive"); } bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) { Emit("context-menu", std::make_pair(params, &render_frame_host)); return true; } bool WebContents::OnGoToEntryOffset(int offset) { GoToOffset(offset); return false; } void WebContents::FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { if (!final_update) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate); result.Set("requestId", request_id); result.Set("matches", number_of_matches); result.Set("selectionArea", selection_rect); result.Set("activeMatchOrdinal", active_match_ordinal); result.Set("finalUpdate", final_update); // Deprecate after 2.0 Emit("found-in-page", result.GetHandle()); } void WebContents::RequestExclusivePointerAccess( content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed) { if (allowed) { exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse( web_contents, user_gesture, last_unlocked_by_target); } else { web_contents->GotResponseToLockMouseRequest( blink::mojom::PointerLockResult::kPermissionDenied); } } void WebContents::RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestPointerLockPermission( user_gesture, last_unlocked_by_target, base::BindOnce(&WebContents::RequestExclusivePointerAccess, base::Unretained(this))); } void WebContents::LostMouseLock() { exclusive_access_manager_->mouse_lock_controller()->LostMouseLock(); } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } void WebContents::CancelKeyboardLockRequest( content::WebContents* web_contents) { exclusive_access_manager_->keyboard_lock_controller() ->CancelKeyboardLockRequest(web_contents); } bool WebContents::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckMediaAccessPermission(security_origin, type); } void WebContents::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestMediaAccessPermission(request, std::move(callback)); } content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { if (!dialog_manager_) dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>(); return dialog_manager_.get(); } void WebContents::OnAudioStateChanged(bool audible) { Emit("-audio-state-changed", audible); } void WebContents::BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) { // Do nothing, we override this method just to avoid compilation error since // there are two virtual functions named BeforeUnloadFired. } void WebContents::HandleNewRenderFrame( content::RenderFrameHost* render_frame_host) { auto* rwhv = render_frame_host->GetView(); if (!rwhv) return; // Set the background color of RenderWidgetHostView. auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences) { absl::optional<SkColor> maybe_color = web_preferences->GetBackgroundColor(); web_contents()->SetPageBaseBackgroundColor(maybe_color); bool guest = IsGuest() || type_ == Type::kBrowserView; SkColor color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); SetBackgroundColor(rwhv, color); } if (!background_throttling_) render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false); auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (rwh_impl) rwh_impl->disable_hidden_ = !background_throttling_; auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->MaybeSetupMojoConnection(); } void WebContents::OnBackgroundColorChanged() { absl::optional<SkColor> color = web_contents()->GetBackgroundColor(); if (color.has_value()) { auto* const view = web_contents()->GetRenderWidgetHostView(); static_cast<content::RenderWidgetHostViewBase*>(view) ->SetContentBackgroundColor(color.value()); } } void WebContents::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { HandleNewRenderFrame(render_frame_host); // RenderFrameCreated is called for speculative frames which may not be // used in certain cross-origin navigations. Invoking // RenderFrameHost::GetLifecycleState currently crashes when called for // speculative frames so we need to filter it out for now. Check // https://crbug.com/1183639 for details on when this can be removed. auto* rfh_impl = static_cast<content::RenderFrameHostImpl*>(render_frame_host); if (rfh_impl->lifecycle_state() == content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) { return; } content::RenderFrameHost::LifecycleState lifecycle_state = render_frame_host->GetLifecycleState(); if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.SetGetter("frame", render_frame_host); Emit("frame-created", details); } } void WebContents::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { // A RenderFrameHost can be deleted when: // - A WebContents is removed and its containing frames are disposed. // - An <iframe> is removed from the DOM. // - Cross-origin navigation creates a new RFH in a separate process which // is swapped by content::RenderFrameHostManager. // // WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID // to find an existing instance of WebFrameMain. During a cross-origin // navigation, the deleted RFH will be the old host which was swapped out. In // this special case, we need to also ensure that WebFrameMain's internal RFH // matches before marking it as disposed. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame && web_frame->render_frame_host() == render_frame_host) web_frame->MarkRenderFrameDisposed(); } void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { // During cross-origin navigation, a FrameTreeNode will swap out its RFH. // If an instance of WebFrameMain exists, it will need to have its RFH // swapped as well. // // |old_host| can be a nullptr so we use |new_host| for looking up the // WebFrameMain instance. auto* web_frame = WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId()); if (web_frame) { web_frame->UpdateRenderFrameHost(new_host); } } void WebContents::FrameDeleted(int frame_tree_node_id) { auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id); if (web_frame) web_frame->Destroyed(); } void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) { // This event is necessary for tracking any states with respect to // intermediate render view hosts aka speculative render view hosts. Currently // used by object-registry.js to ref count remote objects. Emit("render-view-deleted", render_view_host->GetProcess()->GetID()); if (web_contents()->GetRenderViewHost() == render_view_host) { // When the RVH that has been deleted is the current RVH it means that the // the web contents are being closed. This is communicated by this event. // Currently tracked by guest-window-manager.ts to destroy the // BrowserWindow. Emit("current-render-view-deleted", render_view_host->GetProcess()->GetID()); } } void WebContents::PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) { auto weak_this = GetWeakPtr(); Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED); // User might destroy WebContents in the crashed event. if (!weak_this || !web_contents()) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.Set("reason", status); details.Set("exitCode", web_contents()->GetCrashedErrorCode()); Emit("render-process-gone", details); } void WebContents::PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) { #if BUILDFLAG(ENABLE_PLUGINS) content::WebPluginInfo info; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->GetPluginInfoByPath(plugin_path, &info); Emit("plugin-crashed", info.name, info.version); #endif // BUILDFLAG(ENABLE_PLUGINS) } void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) { Emit("media-started-playing"); } void WebContents::MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) { Emit("media-paused"); } void WebContents::DidChangeThemeColor() { auto theme_color = web_contents()->GetThemeColor(); if (theme_color) { Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value())); } else { Emit("did-change-theme-color", nullptr); } } void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) { set_fullscreen_frame(rfh); } void WebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { Emit("focus"); } void WebContents::OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) { Emit("blur"); } void WebContents::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->DOMContentLoaded(); if (!render_frame_host->GetParent()) Emit("dom-ready"); } void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); auto weak_this = GetWeakPtr(); Emit("did-frame-finish-load", is_main_frame, frame_process_id, frame_routing_id); // ⚠️WARNING!⚠️ // Emit() triggers JS which can call destroy() on |this|. It's not safe to // assume that |this| points to valid memory at this point. if (is_main_frame && weak_this && web_contents()) Emit("did-finish-load"); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& url, int error_code) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::DidStartLoading() { Emit("did-start-loading"); } void WebContents::DidStopLoading() { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences && web_preferences->ShouldUsePreferredSizeMode()) web_contents()->GetRenderViewHost()->EnablePreferredSizeMode(); Emit("did-stop-loading"); } bool WebContents::EmitNavigationEvent( const std::string& event, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId(); content::FrameTreeNode* frame_tree_node = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id); content::RenderFrameHostManager* render_manager = frame_tree_node->render_manager(); content::RenderFrameHost* frame_host = nullptr; if (render_manager) { frame_host = render_manager->speculative_frame_host(); if (!frame_host) frame_host = render_manager->current_frame_host(); } int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } bool is_same_document = navigation_handle->IsSameDocument(); auto url = navigation_handle->GetURL(); return Emit(event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Message", "channel", channel); // webContents.emit('-ipc-message', new Event(), internal, channel, // arguments); EmitWithSender("-ipc-message", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), internal, channel, std::move(arguments)); } void WebContents::Invoke( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::InvokeCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel); // webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments); EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::OnFirstNonEmptyLayout( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents()->GetPrimaryMainFrame()) { Emit("ready-to-show"); } } void WebContents::ReceivePostMessage( const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto wrapped_ports = MessagePort::EntanglePorts(isolate, std::move(message.ports)); v8::Local<v8::Value> message_value = electron::DeserializeV8Value(isolate, message); EmitWithSender("-ipc-ports", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), false, channel, message_value, std::move(wrapped_ports)); } void WebContents::MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel); // webContents.emit('-ipc-message-sync', new Event(sender, message), internal, // channel, arguments); EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments) { TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel); auto* target_web_contents = FromID(web_contents_id); if (target_web_contents) { content::RenderFrameHost* frame = target_web_contents->MainFrame(); DCHECK(frame); v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate()); gin::Handle<WebFrameMain> web_frame_main = WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame); if (!web_frame_main->CheckRenderFrame()) return; int32_t sender_id = ID(); web_frame_main->GetRendererApi()->Message(false /* internal */, channel, std::move(arguments), sender_id); } } void WebContents::MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel); // webContents.emit('ipc-message-host', new Event(), channel, args); EmitWithSender("ipc-message-host", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), channel, std::move(arguments)); } void WebContents::UpdateDraggableRegions( std::vector<mojom::DraggableRegionPtr> regions) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDraggableRegionsUpdated(regions); } void WebContents::DidStartNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-start-navigation", navigation_handle); } void WebContents::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-redirect-navigation", navigation_handle); } void WebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { // Don't focus content in an inactive window. if (!owner_window()) return; #if BUILDFLAG(IS_MAC) if (!owner_window()->IsActive()) return; #else if (!owner_window()->widget()->IsActive()) return; #endif // Don't focus content after subframe navigations. if (!navigation_handle->IsInMainFrame()) return; // Only focus for top-level contents. if (type_ != Type::kBrowserWindow) return; web_contents()->SetInitialFocus(); } void WebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (owner_window_) { owner_window_->NotifyLayoutWindowControlsOverlay(); } if (!navigation_handle->HasCommitted()) return; bool is_main_frame = navigation_handle->IsInMainFrame(); content::RenderFrameHost* frame_host = navigation_handle->GetRenderFrameHost(); int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } if (!navigation_handle->IsErrorPage()) { // FIXME: All the Emit() calls below could potentially result in |this| // being destroyed (by JS listening for the event and calling // webContents.destroy()). auto url = navigation_handle->GetURL(); bool is_same_document = navigation_handle->IsSameDocument(); if (is_same_document) { Emit("did-navigate-in-page", url, is_main_frame, frame_process_id, frame_routing_id); } else { const net::HttpResponseHeaders* http_response = navigation_handle->GetResponseHeaders(); std::string http_status_text; int http_response_code = -1; if (http_response) { http_status_text = http_response->GetStatusText(); http_response_code = http_response->response_code(); } Emit("did-frame-navigate", url, http_response_code, http_status_text, is_main_frame, frame_process_id, frame_routing_id); if (is_main_frame) { Emit("did-navigate", url, http_response_code, http_status_text); } } if (IsGuest()) Emit("load-commit", url, is_main_frame); } else { auto url = navigation_handle->GetURL(); int code = navigation_handle->GetNetErrorCode(); auto description = net::ErrorToShortString(code); Emit("did-fail-provisional-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); // Do not emit "did-fail-load" for canceled requests. if (code != net::ERR_ABORTED) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "Failed to load URL: " + url.possibly_invalid_spec() + " with error: " + description, "electron"); Emit("did-fail-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); } } content::NavigationEntry* entry = navigation_handle->GetNavigationEntry(); // This check is needed due to an issue in Chromium // Check the Chromium issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=1178663 // If a history entry has been made and the forward/back call has been made, // proceed with setting the new title if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK)) WebContents::TitleWasSet(entry); } void WebContents::TitleWasSet(content::NavigationEntry* entry) { std::u16string final_title; bool explicit_set = true; if (entry) { auto title = entry->GetTitle(); auto url = entry->GetURL(); if (url.SchemeIsFile() && title.empty()) { final_title = base::UTF8ToUTF16(url.ExtractFileName()); explicit_set = false; } else { final_title = title; } } else { final_title = web_contents()->GetTitle(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnPageTitleUpdated(final_title, explicit_set); Emit("page-title-updated", final_title, explicit_set); } void WebContents::DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) { std::set<GURL> unique_urls; for (const auto& iter : urls) { if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon) continue; const GURL& url = iter->icon_url; if (url.is_valid()) unique_urls.insert(url); } Emit("page-favicon-updated", unique_urls); } void WebContents::DevToolsReloadPage() { Emit("devtools-reload-page"); } void WebContents::DevToolsFocused() { Emit("devtools-focused"); } void WebContents::DevToolsOpened() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); DCHECK(inspectable_web_contents_); DCHECK(inspectable_web_contents_->GetDevToolsWebContents()); auto handle = FromOrCreate( isolate, inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_contents_.Reset(isolate, handle.ToV8()); // Set inspected tabID. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "setInspectedTabId", base::Value(ID())); // Inherit owner window in devtools when it doesn't have one. auto* devtools = inspectable_web_contents_->GetDevToolsWebContents(); bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey()); if (owner_window() && !has_window) handle->SetOwnerWindow(devtools, owner_window()); Emit("devtools-opened"); } void WebContents::DevToolsClosed() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); devtools_web_contents_.Reset(); Emit("devtools-closed"); } void WebContents::DevToolsResized() { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDevToolsResized(); } void WebContents::SetOwnerWindow(NativeWindow* owner_window) { SetOwnerWindow(GetWebContents(), owner_window); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } #if BUILDFLAG(ENABLE_OSR) auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); #endif } content::WebContents* WebContents::GetWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetWebContents(); } content::WebContents* WebContents::GetDevToolsWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetDevToolsWebContents(); } void WebContents::WebContentsDestroyed() { // Clear the pointer stored in wrapper. if (GetAllWebContents().Lookup(id_)) GetAllWebContents().Remove(id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; wrapper->SetAlignedPointerInInternalField(0, nullptr); // Tell WebViewGuestDelegate that the WebContents has been destroyed. if (guest_delegate_) guest_delegate_->WillDestroy(); Observe(nullptr); Emit("destroyed"); } void WebContents::NavigationEntryCommitted( const content::LoadCommittedDetails& details) { Emit("navigation-entry-committed", details.entry->GetURL(), details.is_same_document, details.did_replace_entry); } bool WebContents::GetBackgroundThrottling() const { return background_throttling_; } void WebContents::SetBackgroundThrottling(bool allowed) { background_throttling_ = allowed; auto* rfh = web_contents()->GetPrimaryMainFrame(); if (!rfh) return; auto* rwhv = rfh->GetView(); if (!rwhv) return; auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (!rwh_impl) return; rwh_impl->disable_hidden_ = !background_throttling_; web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed); if (rwh_impl->is_hidden()) { rwh_impl->WasShown({}); } } int WebContents::GetProcessID() const { return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents() ->GetPrimaryMainFrame() ->GetProcess() ->GetProcess() .Handle(); return base::GetProcId(process_handle); } WebContents::Type WebContents::GetType() const { return type_; } bool WebContents::Equal(const WebContents* web_contents) const { return ID() == web_contents->ID(); } GURL WebContents::GetURL() const { return web_contents()->GetLastCommittedURL(); } void WebContents::LoadURL(const GURL& url, const gin_helper::Dictionary& options) { if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) { Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL), net::ErrorToShortString(net::ERR_INVALID_URL), url.possibly_invalid_spec(), true); return; } content::NavigationController::LoadURLParams params(url); if (!options.Get("httpReferrer", &params.referrer)) { GURL http_referrer; if (options.Get("httpReferrer", &http_referrer)) params.referrer = content::Referrer(http_referrer.GetAsReferrer(), network::mojom::ReferrerPolicy::kDefault); } std::string user_agent; if (options.Get("userAgent", &user_agent)) SetUserAgent(user_agent); std::string extra_headers; if (options.Get("extraHeaders", &extra_headers)) params.extra_headers = extra_headers; scoped_refptr<network::ResourceRequestBody> body; if (options.Get("postData", &body)) { params.post_data = body; params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; } GURL base_url_for_data_url; if (options.Get("baseURLForDataURL", &base_url_for_data_url)) { params.base_url_for_data_url = base_url_for_data_url; params.load_type = content::NavigationController::LOAD_TYPE_DATA; } bool reload_ignoring_cache = false; if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) && reload_ignoring_cache) { params.reload_type = content::ReloadType::BYPASSING_CACHE; } // Calling LoadURLWithParams() can trigger JS which destroys |this|. auto weak_this = GetWeakPtr(); params.transition_type = ui::PageTransitionFromInt( ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; // Discard non-committed entries to ensure that we don't re-use a pending // entry web_contents()->GetController().DiscardNonCommittedEntries(); web_contents()->GetController().LoadURLWithParams(params); // ⚠️WARNING!⚠️ // LoadURLWithParams() triggers JS events which can call destroy() on |this|. // It's not safe to assume that |this| points to valid memory at this point. if (!weak_this || !web_contents()) return; // Required to make beforeunload handler work. NotifyUserActivation(); } // TODO(MarshallOfSound): Figure out what we need to do with post data here, I // believe the default behavior when we pass "true" is to phone out to the // delegate and then the controller expects this method to be called again with // "false" if the user approves the reload. For now this would result in // ".reload()" calls on POST data domains failing silently. Passing false would // result in them succeeding, but reposting which although more correct could be // considering a breaking change. void WebContents::Reload() { web_contents()->GetController().Reload(content::ReloadType::NORMAL, /* check_for_repost */ true); } void WebContents::ReloadIgnoringCache() { web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE, /* check_for_repost */ true); } void WebContents::DownloadURL(const GURL& url) { auto* browser_context = web_contents()->GetBrowserContext(); auto* download_manager = browser_context->GetDownloadManager(); std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); download_manager->DownloadUrl(std::move(download_params)); } std::u16string WebContents::GetTitle() const { return web_contents()->GetTitle(); } bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } bool WebContents::IsLoadingMainFrame() const { return web_contents()->ShouldShowLoadingUI(); } bool WebContents::IsWaitingForResponse() const { return web_contents()->IsWaitingForResponse(); } void WebContents::Stop() { web_contents()->Stop(); } bool WebContents::CanGoBack() const { return web_contents()->GetController().CanGoBack(); } void WebContents::GoBack() { if (CanGoBack()) web_contents()->GetController().GoBack(); } bool WebContents::CanGoForward() const { return web_contents()->GetController().CanGoForward(); } void WebContents::GoForward() { if (CanGoForward()) web_contents()->GetController().GoForward(); } bool WebContents::CanGoToOffset(int offset) const { return web_contents()->GetController().CanGoToOffset(offset); } void WebContents::GoToOffset(int offset) { if (CanGoToOffset(offset)) web_contents()->GetController().GoToOffset(offset); } bool WebContents::CanGoToIndex(int index) const { return index >= 0 && index < GetHistoryLength(); } void WebContents::GoToIndex(int index) { if (CanGoToIndex(index)) web_contents()->GetController().GoToIndex(index); } int WebContents::GetActiveIndex() const { return web_contents()->GetController().GetCurrentEntryIndex(); } void WebContents::ClearHistory() { // In some rare cases (normally while there is no real history) we are in a // state where we can't prune navigation entries if (web_contents()->GetController().CanPruneAllButLastCommitted()) { web_contents()->GetController().PruneAllButLastCommitted(); } } int WebContents::GetHistoryLength() const { return web_contents()->GetController().GetEntryCount(); } const std::string WebContents::GetWebRTCIPHandlingPolicy() const { return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy; } void WebContents::SetWebRTCIPHandlingPolicy( const std::string& webrtc_ip_handling_policy) { if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy) return; web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy = webrtc_ip_handling_policy; web_contents()->SyncRendererPrefs(); } std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) return std::string(); content::DesktopMediaID media_id( content::DesktopMediaID::TYPE_WEB_CONTENTS, content::DesktopMediaID::kNullId, content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(), frame_host->GetRoutingID())); auto* request_frame_host = request_web_contents->GetPrimaryMainFrame(); if (!request_frame_host) return std::string(); std::string id = content::DesktopStreamsRegistry::GetInstance()->RegisterStream( request_frame_host->GetProcess()->GetID(), request_frame_host->GetRoutingID(), url::Origin::Create(request_frame_host->GetLastCommittedURL() .DeprecatedGetOriginAsURL()), media_id, "", content::kRegistryStreamTypeTab); return id; } bool WebContents::IsCrashed() const { return web_contents()->IsCrashed(); } void WebContents::ForcefullyCrashRenderer() { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); if (!rwh) return; content::RenderProcessHost* rph = rwh->GetProcess(); if (rph) { #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // A generic |CrashDumpHungChildProcess()| is not implemented for Linux. // Instead we send an explicit IPC to crash on the renderer's IO thread. rph->ForceCrash(); #else // Try to generate a crash report for the hung process. #ifndef MAS_BUILD CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { blink::UserAgentOverride ua_override; ua_override.ua_string_override = user_agent; if (!user_agent.empty()) ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata(); web_contents()->SetUserAgentOverride(ua_override, false); } std::string WebContents::GetUserAgent() { return web_contents()->GetUserAgentOverride().ua_string_override; } v8::Local<v8::Promise> WebContents::SavePage( const base::FilePath& full_file_path, const content::SavePageType& save_type) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (!full_file_path.IsAbsolute()) { promise.RejectWithErrorMessage("Path must be absolute"); return handle; } auto* handler = new SavePageHandler(web_contents(), std::move(promise)); handler->Handle(full_file_path, save_type); return handle; } void WebContents::OpenDevTools(gin::Arguments* args) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; std::string state; if (type_ == Type::kWebView || type_ == Type::kBackgroundPage || !owner_window()) { state = "detach"; } bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->ShowDevTools(activate); } void WebContents::CloseDevTools() { if (type_ == Type::kRemote) return; DCHECK(inspectable_web_contents_); inspectable_web_contents_->CloseDevTools(); } bool WebContents::IsDevToolsOpened() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->IsDevToolsViewShowing(); } bool WebContents::IsDevToolsFocused() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetView()->IsDevToolsViewFocused(); } void WebContents::EnableDeviceEmulation( const blink::DeviceEmulationParams& params) { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->EnableDeviceEmulation(params); } } } void WebContents::DisableDeviceEmulation() { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->DisableDeviceEmulation(); } } } void WebContents::ToggleDevTools() { if (IsDevToolsOpened()) CloseDevTools(); else OpenDevTools(nullptr); } void WebContents::InspectElement(int x, int y) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; DCHECK(inspectable_web_contents_); if (!inspectable_web_contents_->GetDevToolsWebContents()) OpenDevTools(nullptr); inspectable_web_contents_->InspectElement(x, y); } void WebContents::InspectSharedWorkerById(const std::string& workerId) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { if (agent_host->GetId() == workerId) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } } std::vector<scoped_refptr<content::DevToolsAgentHost>> WebContents::GetAllSharedWorkers() { std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers; if (type_ == Type::kRemote) return shared_workers; if (!enable_devtools_) return shared_workers; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { shared_workers.push_back(agent_host); } } return shared_workers; } void WebContents::InspectSharedWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::InspectServiceWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeServiceWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::SetIgnoreMenuShortcuts(bool ignore) { auto* web_preferences = WebContentsPreferences::From(web_contents()); DCHECK(web_preferences); web_preferences->SetIgnoreMenuShortcuts(ignore); } void WebContents::SetAudioMuted(bool muted) { web_contents()->SetAudioMuted(muted); } bool WebContents::IsAudioMuted() { return web_contents()->IsAudioMuted(); } bool WebContents::IsCurrentlyAudible() { return web_contents()->IsCurrentlyAudible(); } #if BUILDFLAG(ENABLE_PRINTING) void WebContents::OnGetDeviceNameToUse( base::Value::Dict print_settings, printing::CompletionCallback print_callback, bool silent, // <error, device_name> std::pair<std::string, std::u16string> info) { // The content::WebContents might be already deleted at this point, and the // PrintViewManagerElectron class does not do null check. if (!web_contents()) { if (print_callback) std::move(print_callback).Run(false, "failed"); return; } if (!info.first.empty()) { if (print_callback) std::move(print_callback).Run(false, info.first); return; } // If the user has passed a deviceName use it, otherwise use default printer. print_settings.Set(printing::kSettingDeviceName, info.second); auto* print_view_manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!print_view_manager) return; auto* focused_frame = web_contents()->GetFocusedFrame(); auto* rfh = focused_frame && focused_frame->HasSelection() ? focused_frame : web_contents()->GetPrimaryMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); base::Value::Dict settings; if (args->Length() >= 1 && !args->GetNext(&options)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid print settings specified."); return; } printing::CompletionCallback callback; if (args->Length() == 2 && !args->GetNext(&callback)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid optional callback provided."); return; } // Set optional silent printing bool silent = false; options.Get("silent", &silent); bool print_background = false; options.Get("printBackground", &print_background); settings.Set(printing::kSettingShouldPrintBackgrounds, print_background); // Set custom margin settings gin_helper::Dictionary margins = gin::Dictionary::CreateEmpty(args->isolate()); if (options.Get("margins", &margins)) { printing::mojom::MarginType margin_type = printing::mojom::MarginType::kDefaultMargins; margins.Get("marginType", &margin_type); settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type)); if (margin_type == printing::mojom::MarginType::kCustomMargins) { base::Value::Dict custom_margins; int top = 0; margins.Get("top", &top); custom_margins.Set(printing::kSettingMarginTop, top); int bottom = 0; margins.Get("bottom", &bottom); custom_margins.Set(printing::kSettingMarginBottom, bottom); int left = 0; margins.Get("left", &left); custom_margins.Set(printing::kSettingMarginLeft, left); int right = 0; margins.Get("right", &right); custom_margins.Set(printing::kSettingMarginRight, right); settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins)); } } else { settings.Set( printing::kSettingMarginsType, static_cast<int>(printing::mojom::MarginType::kDefaultMargins)); } // Set whether to print color or greyscale bool print_color = true; options.Get("color", &print_color); auto const color_model = print_color ? printing::mojom::ColorModel::kColor : printing::mojom::ColorModel::kGray; settings.Set(printing::kSettingColor, static_cast<int>(color_model)); // Is the orientation landscape or portrait. bool landscape = false; options.Get("landscape", &landscape); settings.Set(printing::kSettingLandscape, landscape); // We set the default to the system's default printer and only update // if at the Chromium level if the user overrides. // Printer device name as opened by the OS. std::u16string device_name; options.Get("deviceName", &device_name); int scale_factor = 100; options.Get("scaleFactor", &scale_factor); settings.Set(printing::kSettingScaleFactor, scale_factor); int pages_per_sheet = 1; options.Get("pagesPerSheet", &pages_per_sheet); settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet); // True if the user wants to print with collate. bool collate = true; options.Get("collate", &collate); settings.Set(printing::kSettingCollate, collate); // The number of individual copies to print int copies = 1; options.Get("copies", &copies); settings.Set(printing::kSettingCopies, copies); // Strings to be printed as headers and footers if requested by the user. std::string header; options.Get("header", &header); std::string footer; options.Get("footer", &footer); if (!(header.empty() && footer.empty())) { settings.Set(printing::kSettingHeaderFooterEnabled, true); settings.Set(printing::kSettingHeaderFooterTitle, header); settings.Set(printing::kSettingHeaderFooterURL, footer); } else { settings.Set(printing::kSettingHeaderFooterEnabled, false); } // We don't want to allow the user to enable these settings // but we need to set them or a CHECK is hit. settings.Set(printing::kSettingPrinterType, static_cast<int>(printing::mojom::PrinterType::kLocal)); settings.Set(printing::kSettingShouldPrintSelectionOnly, false); settings.Set(printing::kSettingRasterizePdf, false); // Set custom page ranges to print std::vector<gin_helper::Dictionary> page_ranges; if (options.Get("pageRanges", &page_ranges)) { base::Value::List page_range_list; for (auto& range : page_ranges) { int from, to; if (range.Get("from", &from) && range.Get("to", &to)) { base::Value::Dict range; // Chromium uses 1-based page ranges, so increment each by 1. range.Set(printing::kSettingPageRangeFrom, from + 1); range.Set(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range)); } else { continue; } } if (!page_range_list.empty()) settings.Set(printing::kSettingPageRange, std::move(page_range_list)); } // Duplex type user wants to use. printing::mojom::DuplexMode duplex_mode = printing::mojom::DuplexMode::kSimplex; options.Get("duplexMode", &duplex_mode); settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode)); // We've already done necessary parameter sanitization at the // JS level, so we can simply pass this through. base::Value media_size(base::Value::Type::DICTIONARY); if (options.Get("mediaSize", &media_size)) settings.Set(printing::kSettingMediaSize, std::move(media_size)); // Set custom dots per inch (dpi) gin_helper::Dictionary dpi_settings; int dpi = 72; if (options.Get("dpi", &dpi_settings)) { int horizontal = 72; dpi_settings.Get("horizontal", &horizontal); settings.Set(printing::kSettingDpiHorizontal, horizontal); int vertical = 72; dpi_settings.Get("vertical", &vertical); settings.Set(printing::kSettingDpiVertical, vertical); } else { settings.Set(printing::kSettingDpiHorizontal, dpi); settings.Set(printing::kSettingDpiVertical, dpi); } print_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name), base::BindOnce(&WebContents::OnGetDeviceNameToUse, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), silent)); } // Partially duplicated and modified from // headless/lib/browser/protocol/page_handler.cc;l=41 v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); // This allows us to track headless printing calls. auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID); auto landscape = settings.GetDict().FindBool("landscape"); auto display_header_footer = settings.GetDict().FindBool("displayHeaderFooter"); auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds"); auto scale = settings.GetDict().FindDouble("scale"); auto paper_width = settings.GetDict().FindInt("paperWidth"); auto paper_height = settings.GetDict().FindInt("paperHeight"); auto margin_top = settings.GetDict().FindIntByDottedPath("margins.top"); auto margin_bottom = settings.GetDict().FindIntByDottedPath("margins.bottom"); auto margin_left = settings.GetDict().FindIntByDottedPath("margins.left"); auto margin_right = settings.GetDict().FindIntByDottedPath("margins.right"); auto page_ranges = *settings.GetDict().FindString("pageRanges"); auto header_template = *settings.GetDict().FindString("headerTemplate"); auto footer_template = *settings.GetDict().FindString("footerTemplate"); auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize"); absl::variant<printing::mojom::PrintPagesParamsPtr, std::string> print_pages_params = print_to_pdf::GetPrintPagesParams( web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(), landscape, display_header_footer, print_background, scale, paper_width, paper_height, margin_top, margin_bottom, margin_left, margin_right, absl::make_optional(header_template), absl::make_optional(footer_template), prefer_css_page_size); if (absl::holds_alternative<std::string>(print_pages_params)) { auto error = absl::get<std::string>(print_pages_params); promise.RejectWithErrorMessage("Invalid print parameters: " + error); return handle; } auto* manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!manager) { promise.RejectWithErrorMessage("Failed to find print manager"); return handle; } auto params = std::move( absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params)); params->params->document_cookie = unique_id.value_or(0); manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges, std::move(params), base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(), std::move(promise))); return handle; } void WebContents::OnPDFCreated( gin_helper::Promise<v8::Local<v8::Value>> promise, PrintViewManagerElectron::PrintResult print_result, scoped_refptr<base::RefCountedMemory> data) { if (print_result != PrintViewManagerElectron::PrintResult::PRINT_SUCCESS) { promise.RejectWithErrorMessage( "Failed to generate PDF: " + PrintViewManagerElectron::PrintResultToString(print_result)); return; } v8::Isolate* isolate = promise.isolate(); gin_helper::Locker locker(isolate); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope( v8::Local<v8::Context>::New(isolate, promise.GetContext())); v8::Local<v8::Value> buffer = node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()), data->size()) .ToLocalChecked(); promise.Resolve(buffer); } #endif void WebContents::AddWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsAddFileSystem(std::string(), path); } void WebContents::RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsRemoveFileSystem(path); } void WebContents::Undo() { web_contents()->Undo(); } void WebContents::Redo() { web_contents()->Redo(); } void WebContents::Cut() { web_contents()->Cut(); } void WebContents::Copy() { web_contents()->Copy(); } void WebContents::Paste() { web_contents()->Paste(); } void WebContents::PasteAndMatchStyle() { web_contents()->PasteAndMatchStyle(); } void WebContents::Delete() { web_contents()->Delete(); } void WebContents::SelectAll() { web_contents()->SelectAll(); } void WebContents::Unselect() { web_contents()->CollapseSelection(); } void WebContents::Replace(const std::u16string& word) { web_contents()->Replace(word); } void WebContents::ReplaceMisspelling(const std::u16string& word) { web_contents()->ReplaceMisspelling(word); } uint32_t WebContents::FindInPage(gin::Arguments* args) { std::u16string search_text; if (!args->GetNext(&search_text) || search_text.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must provide a non-empty search content"); return 0; } uint32_t request_id = ++find_in_page_request_id_; gin_helper::Dictionary dict; auto options = blink::mojom::FindOptions::New(); if (args->GetNext(&dict)) { dict.Get("forward", &options->forward); dict.Get("matchCase", &options->match_case); dict.Get("findNext", &options->new_session); } web_contents()->Find(request_id, search_text, std::move(options)); return request_id; } void WebContents::StopFindInPage(content::StopFindAction action) { web_contents()->StopFinding(action); } void WebContents::ShowDefinitionForSelection() { #if BUILDFLAG(IS_MAC) auto* const view = web_contents()->GetRenderWidgetHostView(); if (view) view->ShowDefinitionForSelection(); #endif } void WebContents::CopyImageAt(int x, int y) { auto* const host = web_contents()->GetPrimaryMainFrame(); if (host) host->CopyImageAt(x, y); } void WebContents::Focus() { // Focusing on WebContents does not automatically focus the window on macOS // and Linux, do it manually to match the behavior on Windows. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) if (owner_window()) owner_window()->Focus(true); #endif web_contents()->Focus(); } #if !BUILDFLAG(IS_MAC) bool WebContents::IsFocused() const { auto* view = web_contents()->GetRenderWidgetHostView(); if (!view) return false; if (GetType() != Type::kBackgroundPage) { auto* window = web_contents()->GetNativeView()->GetToplevelWindow(); if (window && !window->IsVisible()) return false; } return view->HasFocus(); } #endif void WebContents::SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event) { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); blink::WebInputEvent::Type type = gin::GetWebInputEventType(isolate, input_event); if (blink::WebInputEvent::IsMouseEventType(type)) { blink::WebMouseEvent mouse_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); #endif } else { rwh->ForwardMouseEvent(mouse_event); } return; } } else if (blink::WebInputEvent::IsKeyboardEventType(type)) { content::NativeWebKeyboardEvent keyboard_event( blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow()); if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) { rwh->ForwardKeyboardEvent(keyboard_event); return; } } else if (type == blink::WebInputEvent::Type::kMouseWheel) { blink::WebMouseWheelEvent mouse_wheel_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); #endif } else { // Chromium expects phase info in wheel events (and applies a // DCHECK to verify it). See: https://crbug.com/756524. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); // Send a synthetic wheel event with phaseEnded to finish scrolling. mouse_wheel_event.has_synthetic_phase = true; mouse_wheel_event.delta_x = 0; mouse_wheel_event.delta_y = 0; mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kEventNonBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); } return; } } isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object"))); } void WebContents::BeginFrameSubscription(gin::Arguments* args) { bool only_dirty = false; FrameSubscriber::FrameCaptureCallback callback; if (args->Length() > 1) { if (!args->GetNext(&only_dirty)) { args->ThrowError(); return; } } if (!args->GetNext(&callback)) { args->ThrowError(); return; } frame_subscriber_ = std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty); } void WebContents::EndFrameSubscription() { frame_subscriber_.reset(); } void WebContents::StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args) { base::FilePath file; std::vector<base::FilePath> files; if (!item.Get("files", &files) && item.Get("file", &file)) { files.push_back(file); } v8::Local<v8::Value> icon_value; if (!item.Get("icon", &icon_value)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'icon' parameter is required"); return; } NativeImage* icon = nullptr; if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) || icon->image().IsEmpty()) { return; } // Start dragging. if (!files.empty()) { base::CurrentThread::ScopedNestableTaskAllower allow; DragFileItems(files, icon->image(), web_contents()->GetNativeView()); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must specify either 'file' or 'files' option"); } } v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) { gfx::Rect rect; gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // get rect arguments if they exist args->GetNext(&rect); auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view) { promise.Resolve(gfx::Image()); return handle; } #if !BUILDFLAG(IS_MAC) // If the view's renderer is suspended this may fail on Windows/Linux - // bail if so. See CopyFromSurface in // content/public/browser/render_widget_host_view.h. auto* rfh = web_contents()->GetPrimaryMainFrame(); if (rfh && rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) { promise.Resolve(gfx::Image()); return handle; } #endif // BUILDFLAG(IS_MAC) // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); const float scale = display::Screen::GetScreen() ->GetDisplayNearestView(native_view) .device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, base::BindOnce(&OnCapturePageDone, std::move(promise))); return handle; } void WebContents::IncrementCapturerCount(gin::Arguments* args) { gfx::Size size; bool stay_hidden = false; bool stay_awake = false; // get size arguments if they exist args->GetNext(&size); // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); std::ignore = web_contents() ->IncrementCapturerCount(size, stay_hidden, stay_awake) .Release(); } void WebContents::DecrementCapturerCount(gin::Arguments* args) { bool stay_hidden = false; bool stay_awake = false; // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); web_contents()->DecrementCapturerCount(stay_hidden, stay_awake); } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const content::WebCursor& webcursor) { const ui::Cursor& cursor = webcursor.cursor(); if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor), gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()), cursor.image_scale_factor(), gfx::Size(cursor.custom_bitmap().width(), cursor.custom_bitmap().height()), cursor.custom_hotspot()); } else { Emit("cursor-changed", CursorTypeToString(cursor)); } } bool WebContents::IsGuest() const { return type_ == Type::kWebView; } void WebContents::AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id) { attached_ = true; if (guest_delegate_) guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id); } bool WebContents::IsOffScreen() const { #if BUILDFLAG(ENABLE_OSR) return type_ == Type::kOffScreen; #else return false; #endif } #if BUILDFLAG(ENABLE_OSR) void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) { Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap)); } void WebContents::StartPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(true); } void WebContents::StopPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(false); } bool WebContents::IsPainting() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv && osr_wcv->IsPainting(); } void WebContents::SetFrameRate(int frame_rate) { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetFrameRate(frame_rate); } int WebContents::GetFrameRate() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv ? osr_wcv->GetFrameRate() : 0; } #endif void WebContents::Invalidate() { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); #endif } else { auto* const window = owner_window(); if (window) window->Invalidate(); } } gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) { if (IsOffScreen() && wc == web_contents()) { auto* relay = NativeWindowRelay::FromWebContents(web_contents()); if (relay) { auto* owner_window = relay->GetNativeWindow(); return owner_window ? owner_window->GetSize() : gfx::Size(); } } return gfx::Size(); } void WebContents::SetZoomLevel(double level) { zoom_controller_->SetZoomLevel(level); } double WebContents::GetZoomLevel() const { return zoom_controller_->GetZoomLevel(); } void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) { if (factor < std::numeric_limits<double>::epsilon()) { thrower.ThrowError("'zoomFactor' must be a double greater than 0.0"); return; } auto level = blink::PageZoomFactorToZoomLevel(factor); SetZoomLevel(level); } double WebContents::GetZoomFactor() const { auto level = GetZoomLevel(); return blink::PageZoomLevelToZoomFactor(level); } void WebContents::SetTemporaryZoomLevel(double level) { zoom_controller_->SetTemporaryZoomLevel(level); } void WebContents::DoGetZoomLevel( electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback callback) { std::move(callback).Run(GetZoomLevel()); } std::vector<base::FilePath> WebContents::GetPreloadPaths() const { auto result = SessionPreferences::GetValidPreloads(GetBrowserContext()); if (auto* web_preferences = WebContentsPreferences::From(web_contents())) { base::FilePath preload; if (web_preferences->GetPreloadPath(&preload)) { result.emplace_back(preload); } } return result; } v8::Local<v8::Value> WebContents::GetLastWebPreferences( v8::Isolate* isolate) const { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (!web_preferences) return v8::Null(isolate); return gin::ConvertToV8(isolate, *web_preferences->last_preference()); } v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow( v8::Isolate* isolate) const { if (owner_window()) return BrowserWindow::From(isolate, owner_window()); else return v8::Null(isolate); } v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) { return v8::Local<v8::Value>::New(isolate, session_); } content::WebContents* WebContents::HostWebContents() const { if (!embedder_) return nullptr; return embedder_->web_contents(); } void WebContents::SetEmbedder(const WebContents* embedder) { if (embedder) { NativeWindow* owner_window = nullptr; auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents()); if (relay) { owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); content::RenderWidgetHostView* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->Hide(); rwhv->Show(); } } } void WebContents::SetDevToolsWebContents(const WebContents* devtools) { if (inspectable_web_contents_) inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents()); } v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const { gfx::NativeView ptr = web_contents()->GetNativeView(); auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr), sizeof(gfx::NativeView)); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) { if (devtools_web_contents_.IsEmpty()) return v8::Null(isolate); else return v8::Local<v8::Value>::New(isolate, devtools_web_contents_); } v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) { if (debugger_.IsEmpty()) { auto handle = electron::api::Debugger::Create(isolate, web_contents()); debugger_.Reset(isolate, handle.ToV8()); } return v8::Local<v8::Value>::New(isolate, debugger_); } content::RenderFrameHost* WebContents::MainFrame() { return web_contents()->GetPrimaryMainFrame(); } void WebContents::NotifyUserActivation() { content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame(); if (frame) frame->NotifyUserActivation( blink::mojom::UserActivationNotificationType::kInteraction); } void WebContents::SetImageAnimationPolicy(const std::string& new_policy) { auto* web_preferences = WebContentsPreferences::From(web_contents()); web_preferences->SetImageAnimationPolicy(new_policy); web_contents()->OnWebPreferencesChanged(); } v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("Failed to create memory dump"); return handle; } auto pid = frame_host->GetProcess()->GetProcess().Pid(); v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext()); memory_instrumentation::MemoryInstrumentation::GetInstance() ->RequestGlobalDumpForPid( pid, std::vector<std::string>(), base::BindOnce(&ElectronBindings::DidReceiveMemoryDump, std::move(context), std::move(promise), pid)); return handle; } v8::Local<v8::Promise> WebContents::TakeHeapSnapshot( v8::Isolate* isolate, const base::FilePath& file_path) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); base::ThreadRestrictions::ScopedAllowIO allow_io; base::File file(file_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); if (!file.IsValid()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } if (!frame_host->IsRenderFrameLive()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } // This dance with `base::Owned` is to ensure that the interface stays alive // until the callback is called. Otherwise it would be closed at the end of // this function. auto electron_renderer = std::make_unique<mojo::Remote<mojom::ElectronRenderer>>(); frame_host->GetRemoteInterfaces()->GetInterface( electron_renderer->BindNewPipeAndPassReceiver()); auto* raw_ptr = electron_renderer.get(); (*raw_ptr)->TakeHeapSnapshot( mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())), base::BindOnce( [](mojo::Remote<mojom::ElectronRenderer>* ep, gin_helper::Promise<void> promise, bool success) { if (success) { promise.Resolve(); } else { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } void WebContents::UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) { Emit("preferred-size-changed", pref_size); } bool WebContents::CanOverscrollContent() { return false; } std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) { return ShowEyeDropper(frame, listener); } void WebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener), params); } void WebContents::EnumerateDirectory( content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path); } bool WebContents::IsFullscreenForTabOrPending( const content::WebContents* source) { bool transition_fs = owner_window() ? owner_window()->fullscreen_transition_state() != NativeWindow::FullScreenTransitionState::NONE : false; return html_fullscreen_ || transition_fs; } bool WebContents::TakeFocus(content::WebContents* source, bool reverse) { if (source && source->GetOutermostWebContents() == source) { // If this is the outermost web contents and the user has tabbed or // shift + tabbed through all the elements, reset the focus back to // the first or last element so that it doesn't stay in the body. source->FocusThroughTabTraversal(reverse); return true; } return false; } content::PictureInPictureResult WebContents::EnterPictureInPicture( content::WebContents* web_contents) { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) return PictureInPictureWindowManager::GetInstance() ->EnterVideoPictureInPicture(web_contents); #else return content::PictureInPictureResult::kNotSupported; #endif } void WebContents::ExitPictureInPicture() { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); #endif } void WebContents::DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) { base::FilePath path; auto it = saved_files_.find(url); if (it != saved_files_.end() && !save_as) { path = it->second; } else { file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.title = url; settings.default_path = base::FilePath::FromUTF8Unsafe(url); if (!file_dialog::ShowSaveDialogSync(settings, &path)) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "canceledSaveURL", base::Value(url)); return; } } saved_files_[url] = path; // Notify DevTools. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "savedURL", base::Value(url), base::Value(path.AsUTF8Unsafe())); file_task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteToFile, path, content)); } void WebContents::DevToolsAppendToFile(const std::string& url, const std::string& content) { auto it = saved_files_.find(url); if (it == saved_files_.end()) return; // Notify DevTools. inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL", base::Value(url)); file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&AppendToFile, it->second, content)); } void WebContents::DevToolsRequestFileSystems() { auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); if (file_system_paths.empty()) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List())); return; } std::vector<FileSystem> file_systems; for (const auto& file_system_path : file_system_paths) { base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path.first); std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id, file_system_path.first, file_system_path.second); file_systems.push_back(file_system); } base::Value::List file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(std::move(file_system_value))); } void WebContents::DevToolsAddFileSystem( const std::string& type, const base::FilePath& file_system_path) { base::FilePath path = file_system_path; if (path.empty()) { std::vector<base::FilePath> paths; file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY; if (!file_dialog::ShowOpenDialogSync(settings, &paths)) return; path = paths[0]; } std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe())) return; FileSystem file_system = CreateFileSystemStruct( GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type); base::Value::Dict file_system_value = CreateFileSystemValue(file_system); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->SetKey(path.AsUTF8Unsafe(), base::Value(type)); std::string error = ""; // No error inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemAdded", base::Value(error), base::Value(std::move(file_system_value))); } void WebContents::DevToolsRemoveFileSystem( const base::FilePath& file_system_path) { if (!inspectable_web_contents_) return; std::string path = file_system_path.AsUTF8Unsafe(); storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath( file_system_path); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->RemoveKey(path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemRemoved", base::Value(path)); } void WebContents::DevToolsIndexPath( int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsIndexingDone(request_id, file_system_path); return; } if (devtools_indexing_jobs_.count(request_id) != 0) return; std::vector<std::string> excluded_folders; std::unique_ptr<base::Value> parsed_excluded_folders = base::JSONReader::ReadDeprecated(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetListDeprecated()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsSearchCompleted(request_id, file_system_path, std::vector<std::string>()); return; } devtools_file_system_indexer_->SearchInPath( file_system_path, query, base::BindRepeating(&WebContents::OnDevToolsSearchCompleted, weak_factory_.GetWeakPtr(), request_id, file_system_path)); } void WebContents::DevToolsSetEyeDropperActive(bool active) { auto* web_contents = GetWebContents(); if (!web_contents) return; if (active) { eye_dropper_ = std::make_unique<DevToolsEyeDropper>( web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper, base::Unretained(this))); } else { eye_dropper_.reset(); } } void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) { base::Value::Dict color; color.Set("r", r); color.Set("g", g); color.Set("b", b); color.Set("a", a); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color))); } #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel WebContents::GetDevToolsWindowIcon() { return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{}; } #endif #if BUILDFLAG(IS_LINUX) void WebContents::GetDevToolsWindowWMClass(std::string* name, std::string* class_name) { *class_name = Browser::Get()->GetName(); *name = base::ToLowerASCII(*class_name); } #endif void WebContents::OnDevToolsIndexingWorkCalculated( int request_id, const std::string& file_system_path, int total_work) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id), base::Value(file_system_path), base::Value(total_work)); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingWorked", base::Value(request_id), base::Value(file_system_path), base::Value(worked)); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone", base::Value(request_id), base::Value(file_system_path)); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::Value::List file_paths_value; for (const auto& file_path : file_paths) file_paths_value.Append(file_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "searchCompleted", base::Value(request_id), base::Value(file_system_path), base::Value(std::move(file_paths_value))); } void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) { // Window is already in fullscreen mode, save the state. if (enter_fullscreen && owner_window_->IsFullscreen()) { native_fullscreen_ = true; UpdateHtmlApiFullscreen(true); return; } // Exit html fullscreen state but not window's fullscreen mode. if (!enter_fullscreen && native_fullscreen_) { UpdateHtmlApiFullscreen(false); return; } // Set fullscreen on window if allowed. auto* web_preferences = WebContentsPreferences::From(GetWebContents()); bool html_fullscreenable = web_preferences ? !web_preferences->ShouldDisableHtmlFullscreenWindowResize() : true; if (html_fullscreenable) owner_window_->SetFullScreen(enter_fullscreen); UpdateHtmlApiFullscreen(enter_fullscreen); native_fullscreen_ = false; } void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) { if (fullscreen == is_html_fullscreen()) return; html_fullscreen_ = fullscreen; // Notify renderer of the html fullscreen change. web_contents() ->GetRenderViewHost() ->GetWidget() ->SynchronizeVisualProperties(); // The embedder WebContents is separated from the frame tree of webview, so // we must manually sync their fullscreen states. if (embedder_) embedder_->SetHtmlApiFullscreen(fullscreen); if (fullscreen) { Emit("enter-html-full-screen"); owner_window_->NotifyWindowEnterHtmlFullScreen(); } else { Emit("leave-html-full-screen"); owner_window_->NotifyWindowLeaveHtmlFullScreen(); } // Make sure all child webviews quit html fullscreen. if (!fullscreen && !IsGuest()) { auto* manager = WebViewManager::GetWebViewManager(web_contents()); manager->ForEachGuest( web_contents(), base::BindRepeating([](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); api_web_contents->SetHtmlApiFullscreen(false); return false; })); } } // static v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = "WebContents"; templ->Set( gin::StringToSymbol(isolate, "isDestroyed"), gin::CreateFunctionTemplate( isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed), options)); // We use gin_helper::ObjectTemplateBuilder instead of // gin::ObjectTemplateBuilder here to handle the fact that WebContents is // destroyable. return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("getBackgroundThrottling", &WebContents::GetBackgroundThrottling) .SetMethod("setBackgroundThrottling", &WebContents::SetBackgroundThrottling) .SetMethod("getProcessId", &WebContents::GetProcessID) .SetMethod("getOSProcessId", &WebContents::GetOSProcessID) .SetMethod("equal", &WebContents::Equal) .SetMethod("_loadURL", &WebContents::LoadURL) .SetMethod("reload", &WebContents::Reload) .SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache) .SetMethod("downloadURL", &WebContents::DownloadURL) .SetMethod("getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) .SetMethod("stop", &WebContents::Stop) .SetMethod("canGoBack", &WebContents::CanGoBack) .SetMethod("goBack", &WebContents::GoBack) .SetMethod("canGoForward", &WebContents::CanGoForward) .SetMethod("goForward", &WebContents::GoForward) .SetMethod("canGoToOffset", &WebContents::CanGoToOffset) .SetMethod("goToOffset", &WebContents::GoToOffset) .SetMethod("canGoToIndex", &WebContents::CanGoToIndex) .SetMethod("goToIndex", &WebContents::GoToIndex) .SetMethod("getActiveIndex", &WebContents::GetActiveIndex) .SetMethod("clearHistory", &WebContents::ClearHistory) .SetMethod("length", &WebContents::GetHistoryLength) .SetMethod("isCrashed", &WebContents::IsCrashed) .SetMethod("forcefullyCrashRenderer", &WebContents::ForcefullyCrashRenderer) .SetMethod("setUserAgent", &WebContents::SetUserAgent) .SetMethod("getUserAgent", &WebContents::GetUserAgent) .SetMethod("savePage", &WebContents::SavePage) .SetMethod("openDevTools", &WebContents::OpenDevTools) .SetMethod("closeDevTools", &WebContents::CloseDevTools) .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened) .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused) .SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation) .SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation) .SetMethod("toggleDevTools", &WebContents::ToggleDevTools) .SetMethod("inspectElement", &WebContents::InspectElement) .SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts) .SetMethod("setAudioMuted", &WebContents::SetAudioMuted) .SetMethod("isAudioMuted", &WebContents::IsAudioMuted) .SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible) .SetMethod("undo", &WebContents::Undo) .SetMethod("redo", &WebContents::Redo) .SetMethod("cut", &WebContents::Cut) .SetMethod("copy", &WebContents::Copy) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("replace", &WebContents::Replace) .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling) .SetMethod("findInPage", &WebContents::FindInPage) .SetMethod("stopFindInPage", &WebContents::StopFindInPage) .SetMethod("focus", &WebContents::Focus) .SetMethod("isFocused", &WebContents::IsFocused) .SetMethod("sendInputEvent", &WebContents::SendInputEvent) .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("startDrag", &WebContents::StartDrag) .SetMethod("attachToIframe", &WebContents::AttachToIframe) .SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame) .SetMethod("isOffscreen", &WebContents::IsOffScreen) #if BUILDFLAG(ENABLE_OSR) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) #endif .SetMethod("invalidate", &WebContents::Invalidate) .SetMethod("setZoomLevel", &WebContents::SetZoomLevel) .SetMethod("getZoomLevel", &WebContents::GetZoomLevel) .SetMethod("setZoomFactor", &WebContents::SetZoomFactor) .SetMethod("getZoomFactor", &WebContents::GetZoomFactor) .SetMethod("getType", &WebContents::GetType) .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths) .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker) .SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker) .SetMethod("inspectSharedWorkerById", &WebContents::InspectSharedWorkerById) .SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers) #if BUILDFLAG(ENABLE_PRINTING) .SetMethod("_print", &WebContents::Print) .SetMethod("_printToPDF", &WebContents::PrintToPDF) #endif .SetMethod("_setNextChildWebPreferences", &WebContents::SetNextChildWebPreferences) .SetMethod("addWorkSpace", &WebContents::AddWorkSpace) .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("showDefinitionForSelection", &WebContents::ShowDefinitionForSelection) .SetMethod("copyImageAt", &WebContents::CopyImageAt) .SetMethod("capturePage", &WebContents::CapturePage) .SetMethod("setEmbedder", &WebContents::SetEmbedder) .SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents) .SetMethod("getNativeView", &WebContents::GetNativeView) .SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount) .SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount) .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot) .SetMethod("setImageAnimationPolicy", &WebContents::SetImageAnimationPolicy) .SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo) .SetProperty("id", &WebContents::ID) .SetProperty("session", &WebContents::Session) .SetProperty("hostWebContents", &WebContents::HostWebContents) .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents) .SetProperty("debugger", &WebContents::Debugger) .SetProperty("mainFrame", &WebContents::MainFrame) .Build(); } const char* WebContents::GetTypeName() { return "WebContents"; } ElectronBrowserContext* WebContents::GetBrowserContext() const { return static_cast<ElectronBrowserContext*>( web_contents()->GetBrowserContext()); } // static gin::Handle<WebContents> WebContents::New( v8::Isolate* isolate, const gin_helper::Dictionary& options) { gin::Handle<WebContents> handle = gin::CreateHandle(isolate, new WebContents(isolate, options)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static gin::Handle<WebContents> WebContents::CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) { gin::Handle<WebContents> handle = gin::CreateHandle( isolate, new WebContents(isolate, std::move(web_contents), type)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static WebContents* WebContents::From(content::WebContents* web_contents) { if (!web_contents) return nullptr; auto* data = static_cast<UserDataLink*>( web_contents->GetUserData(kElectronApiWebContentsKey)); return data ? data->web_contents.get() : nullptr; } // static gin::Handle<WebContents> WebContents::FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents) { WebContents* api_web_contents = From(web_contents); if (!api_web_contents) { api_web_contents = new WebContents(isolate, web_contents); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, api_web_contents, "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } } return gin::CreateHandle(isolate, api_web_contents); } // static gin::Handle<WebContents> WebContents::CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences) { // Check if webPreferences has |webContents| option. gin::Handle<WebContents> web_contents; if (web_preferences.GetHidden("webContents", &web_contents) && !web_contents.IsEmpty()) { // Set webPreferences from options if using an existing webContents. // These preferences will be used when the webContent launches new // render processes. auto* existing_preferences = WebContentsPreferences::From(web_contents->web_contents()); gin_helper::Dictionary web_preferences_dict; if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(), &web_preferences_dict)) { existing_preferences->SetFromDictionary(web_preferences_dict); absl::optional<SkColor> color = existing_preferences->GetBackgroundColor(); web_contents->web_contents()->SetPageBaseBackgroundColor(color); // Because web preferences don't recognize transparency, // only set rwhv background color if a color exists auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView(); if (rwhv && color.has_value()) SetBackgroundColor(rwhv, color.value()); } } else { // Create one if not. web_contents = WebContents::New(isolate, web_preferences); } return web_contents; } // static WebContents* WebContents::FromID(int32_t id) { return GetAllWebContents().Lookup(id); } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace electron::api namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) { WebContents* contents = WebContents::FromID(id); return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } gin::Handle<WebContents> WebContentsFromDevToolsTargetID( v8::Isolate* isolate, std::string target_id) { auto agent_host = content::DevToolsAgentHost::GetForId(target_id); WebContents* contents = agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr; return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8( v8::Isolate* isolate) { std::vector<gin::Handle<WebContents>> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue())); } return list; } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); dict.SetMethod("fromId", &WebContentsFromID); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
35,046
[Bug]: webContents.getUserAgent() is empty since 20.0.0-alpha.6
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.0-alpha.6 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version 20.0.0-alpha.5 ### Expected Behavior `webContents.getUserAgent()` returns a string with a user Agent ### Actual Behavior webContents.getUserAgent() returns an empty string ### Testcase Gist URL https://gist.github.com/33fd4a9ac6db6b28b1dcc5b765edb622 ### Additional Information In the console the user agent is printed in alpha.5, but empty in alpha.6. Looking at the diff between alpha.5 and alpha.6, this PR seems the likely cause: https://github.com/electron/electron/pull/34524 / #34481 It's worth noting that the renderer does have a filled-in userAgent.
https://github.com/electron/electron/issues/35046
https://github.com/electron/electron/pull/35069
8004cb8722c8d52f4cd553bbaea86750149e8ca4
9028bb79a85fedf64230c2f1c6a29ab072c98c20
2022-07-25T14:12:09Z
c++
2022-07-29T15:09:47Z
shell/browser/electron_browser_context.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_context.h" #include <memory> #include <utility> #include "base/barrier_closure.h" #include "base/base_paths.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/no_destructor.h" #include "base/path_service.h" #include "base/strings/escape.h" #include "base/strings/string_util.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/prefs/json_pref_store.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/pref_service_factory.h" #include "components/prefs/value_map_pref_store.h" #include "components/proxy_config/pref_proxy_config_tracker_impl.h" #include "components/proxy_config/proxy_config_pref_names.h" #include "content/browser/blob_storage/chrome_blob_storage_context.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/cors_origin_pattern_setter.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "services/network/public/mojom/network_context.mojom.h" #include "shell/browser/cookie_change_notifier.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_download_manager_delegate.h" #include "shell/browser/electron_permission_manager.h" #include "shell/browser/net/resolve_proxy_helper.h" #include "shell/browser/pref_store_delegate.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/special_storage_policy.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/zoom_level_delegate.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/options_switches.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/browser/extension_pref_store.h" #include "extensions/browser/extension_pref_value_map_factory.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/pref_names.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extension_system.h" #include "shell/browser/extensions/electron_extension_system_factory.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "components/pref_registry/pref_registry_syncable.h" #include "components/user_prefs/user_prefs.h" #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "base/i18n/rtl.h" #include "components/language/core/browser/language_prefs.h" #include "components/spellcheck/browser/pref_names.h" #include "components/spellcheck/common/spellcheck_common.h" #endif using content::BrowserThread; namespace electron { namespace { // Convert string to lower case and escape it. std::string MakePartitionName(const std::string& input) { return base::EscapePath(base::ToLowerASCII(input)); } } // namespace // static ElectronBrowserContext::BrowserContextMap& ElectronBrowserContext::browser_context_map() { static base::NoDestructor<ElectronBrowserContext::BrowserContextMap> browser_context_map; return *browser_context_map; } ElectronBrowserContext::ElectronBrowserContext(const std::string& partition, bool in_memory, base::Value::Dict options) : storage_policy_(base::MakeRefCounted<SpecialStoragePolicy>()), protocol_registry_(base::WrapUnique(new ProtocolRegistry)), in_memory_(in_memory), ssl_config_(network::mojom::SSLConfig::New()) { // Read options. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); use_cache_ = !command_line->HasSwitch(switches::kDisableHttpCache); if (auto use_cache_opt = options.FindBool("cache")) { use_cache_ = use_cache_opt.value(); } base::StringToInt(command_line->GetSwitchValueASCII(switches::kDiskCacheSize), &max_cache_size_); base::PathService::Get(DIR_SESSION_DATA, &path_); if (!in_memory && !partition.empty()) path_ = path_.Append(FILE_PATH_LITERAL("Partitions")) .Append(base::FilePath::FromUTF8Unsafe( MakePartitionName(partition))); BrowserContextDependencyManager::GetInstance()->MarkBrowserContextLive(this); // Initialize Pref Registry. InitPrefs(); cookie_change_notifier_ = std::make_unique<CookieChangeNotifier>(this); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { BrowserContextDependencyManager::GetInstance() ->CreateBrowserContextServices(this); extension_system_ = static_cast<extensions::ElectronExtensionSystem*>( extensions::ExtensionSystem::Get(this)); extension_system_->InitForRegularProfile(true /* extensions_enabled */); extension_system_->FinishInitialization(); } #endif } ElectronBrowserContext::~ElectronBrowserContext() { DCHECK_CURRENTLY_ON(BrowserThread::UI); NotifyWillBeDestroyed(); // Notify any keyed services of browser context destruction. BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices( this); ShutdownStoragePartitions(); BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, std::move(resource_context_)); } void ElectronBrowserContext::InitPrefs() { auto prefs_path = GetPath().Append(FILE_PATH_LITERAL("Preferences")); base::ThreadRestrictions::ScopedAllowIO allow_io; PrefServiceFactory prefs_factory; scoped_refptr<JsonPrefStore> pref_store = base::MakeRefCounted<JsonPrefStore>(prefs_path); pref_store->ReadPrefs(); // Synchronous. prefs_factory.set_user_prefs(pref_store); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { auto* ext_pref_store = new ExtensionPrefStore( ExtensionPrefValueMapFactory::GetForBrowserContext(this), IsOffTheRecord()); prefs_factory.set_extension_prefs(ext_pref_store); } #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) auto registry = base::MakeRefCounted<user_prefs::PrefRegistrySyncable>(); #else auto registry = base::MakeRefCounted<PrefRegistrySimple>(); #endif registry->RegisterFilePathPref(prefs::kSelectFileLastDirectory, base::FilePath()); base::FilePath download_dir; base::PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_dir); registry->RegisterFilePathPref(prefs::kDownloadDefaultDirectory, download_dir); registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths); InspectableWebContents::RegisterPrefs(registry.get()); MediaDeviceIDSalt::RegisterPrefs(registry.get()); ZoomLevelDelegate::RegisterPrefs(registry.get()); PrefProxyConfigTrackerImpl::RegisterPrefs(registry.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) extensions::ExtensionPrefs::RegisterProfilePrefs(registry.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) BrowserContextDependencyManager::GetInstance() ->RegisterProfilePrefsForServices(registry.get()); language::LanguagePrefs::RegisterProfilePrefs(registry.get()); #endif prefs_ = prefs_factory.Create( registry.get(), std::make_unique<PrefStoreDelegate>(weak_factory_.GetWeakPtr())); prefs_->UpdateCommandLinePrefStore(new ValueMapPrefStore); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) user_prefs::UserPrefs::Set(this, prefs_.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) auto* current_dictionaries = prefs()->Get(spellcheck::prefs::kSpellCheckDictionaries); // No configured dictionaries, the default will be en-US if (current_dictionaries->GetListDeprecated().empty()) { std::string default_code = spellcheck::GetCorrespondingSpellCheckLanguage( base::i18n::GetConfiguredLocale()); if (!default_code.empty()) { base::Value::List language_codes; language_codes.Append(default_code); prefs()->Set(spellcheck::prefs::kSpellCheckDictionaries, base::Value(std::move(language_codes))); } } #endif } void ElectronBrowserContext::SetUserAgent(const std::string& user_agent) { user_agent_ = user_agent; } base::FilePath ElectronBrowserContext::GetPath() { return path_; } bool ElectronBrowserContext::IsOffTheRecord() { return in_memory_; } bool ElectronBrowserContext::CanUseHttpCache() const { return use_cache_; } int ElectronBrowserContext::GetMaxCacheSize() const { return max_cache_size_; } content::ResourceContext* ElectronBrowserContext::GetResourceContext() { if (!resource_context_) resource_context_ = std::make_unique<content::ResourceContext>(); return resource_context_.get(); } std::string ElectronBrowserContext::GetMediaDeviceIDSalt() { if (!media_device_id_salt_.get()) media_device_id_salt_ = std::make_unique<MediaDeviceIDSalt>(prefs_.get()); return media_device_id_salt_->GetSalt(); } std::unique_ptr<content::ZoomLevelDelegate> ElectronBrowserContext::CreateZoomLevelDelegate( const base::FilePath& partition_path) { if (!IsOffTheRecord()) { return std::make_unique<ZoomLevelDelegate>(prefs(), partition_path); } return std::unique_ptr<content::ZoomLevelDelegate>(); } content::DownloadManagerDelegate* ElectronBrowserContext::GetDownloadManagerDelegate() { if (!download_manager_delegate_.get()) { auto* download_manager = this->GetDownloadManager(); download_manager_delegate_ = std::make_unique<ElectronDownloadManagerDelegate>(download_manager); } return download_manager_delegate_.get(); } content::BrowserPluginGuestManager* ElectronBrowserContext::GetGuestManager() { if (!guest_manager_) guest_manager_ = std::make_unique<WebViewManager>(); return guest_manager_.get(); } content::PlatformNotificationService* ElectronBrowserContext::GetPlatformNotificationService() { return ElectronBrowserClient::Get()->GetPlatformNotificationService(); } content::PermissionControllerDelegate* ElectronBrowserContext::GetPermissionControllerDelegate() { if (!permission_manager_.get()) permission_manager_ = std::make_unique<ElectronPermissionManager>(); return permission_manager_.get(); } storage::SpecialStoragePolicy* ElectronBrowserContext::GetSpecialStoragePolicy() { return storage_policy_.get(); } std::string ElectronBrowserContext::GetUserAgent() const { return user_agent_.value_or(ElectronBrowserClient::Get()->GetUserAgent()); } absl::optional<std::string> ElectronBrowserContext::GetUserAgentOverride() const { return user_agent_; } predictors::PreconnectManager* ElectronBrowserContext::GetPreconnectManager() { if (!preconnect_manager_.get()) { preconnect_manager_ = std::make_unique<predictors::PreconnectManager>(nullptr, this); } return preconnect_manager_.get(); } scoped_refptr<network::SharedURLLoaderFactory> ElectronBrowserContext::GetURLLoaderFactory() { if (url_loader_factory_) return url_loader_factory_; mojo::PendingRemote<network::mojom::URLLoaderFactory> network_factory_remote; mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver = network_factory_remote.InitWithNewPipeAndPassReceiver(); // Consult the embedder. mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient> header_client; static_cast<content::ContentBrowserClient*>(ElectronBrowserClient::Get()) ->WillCreateURLLoaderFactory( this, nullptr, -1, content::ContentBrowserClient::URLLoaderFactoryType::kNavigation, url::Origin(), absl::nullopt, ukm::kInvalidSourceIdObj, &factory_receiver, &header_client, nullptr, nullptr, nullptr); network::mojom::URLLoaderFactoryParamsPtr params = network::mojom::URLLoaderFactoryParams::New(); params->header_client = std::move(header_client); params->process_id = network::mojom::kBrowserProcessId; params->is_trusted = true; params->is_corb_enabled = false; // The tests of net module would fail if this setting is true, it seems that // the non-NetworkService implementation always has web security enabled. params->disable_web_security = false; auto* storage_partition = GetDefaultStoragePartition(); storage_partition->GetNetworkContext()->CreateURLLoaderFactory( std::move(factory_receiver), std::move(params)); url_loader_factory_ = base::MakeRefCounted<network::WrapperSharedURLLoaderFactory>( std::move(network_factory_remote)); return url_loader_factory_; } content::PushMessagingService* ElectronBrowserContext::GetPushMessagingService() { return nullptr; } content::SSLHostStateDelegate* ElectronBrowserContext::GetSSLHostStateDelegate() { return nullptr; } content::BackgroundFetchDelegate* ElectronBrowserContext::GetBackgroundFetchDelegate() { return nullptr; } content::BackgroundSyncController* ElectronBrowserContext::GetBackgroundSyncController() { return nullptr; } content::BrowsingDataRemoverDelegate* ElectronBrowserContext::GetBrowsingDataRemoverDelegate() { return nullptr; } content::ClientHintsControllerDelegate* ElectronBrowserContext::GetClientHintsControllerDelegate() { return nullptr; } content::StorageNotificationService* ElectronBrowserContext::GetStorageNotificationService() { return nullptr; } ResolveProxyHelper* ElectronBrowserContext::GetResolveProxyHelper() { if (!resolve_proxy_helper_) { resolve_proxy_helper_ = base::MakeRefCounted<ResolveProxyHelper>(this); } return resolve_proxy_helper_.get(); } network::mojom::SSLConfigPtr ElectronBrowserContext::GetSSLConfig() { return ssl_config_.Clone(); } void ElectronBrowserContext::SetSSLConfig(network::mojom::SSLConfigPtr config) { ssl_config_ = std::move(config); if (ssl_config_client_) { ssl_config_client_->OnSSLConfigUpdated(ssl_config_.Clone()); } } void ElectronBrowserContext::SetSSLConfigClient( mojo::Remote<network::mojom::SSLConfigClient> client) { ssl_config_client_ = std::move(client); } void ElectronBrowserContext::GrantDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { granted_devices_[permission_type][origin].push_back( std::make_unique<base::Value>(device.Clone())); } void ElectronBrowserContext::RevokeDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return; for (auto it = origin_devices_it->second.begin(); it != origin_devices_it->second.end();) { if (DoesDeviceMatch(device, it->get(), permission_type)) { it = origin_devices_it->second.erase(it); } else { ++it; } } } bool ElectronBrowserContext::DoesDeviceMatch( const base::Value& device, const base::Value* device_to_compare, blink::PermissionType permission_type) { if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::HID)) { if (device.GetDict().FindInt(kHidVendorIdKey) != device_to_compare->GetDict().FindInt(kHidVendorIdKey) || device.GetDict().FindInt(kHidProductIdKey) != device_to_compare->GetDict().FindInt(kHidProductIdKey)) { return false; } const auto* serial_number = device_to_compare->GetDict().FindString(kHidSerialNumberKey); const auto* device_serial_number = device.GetDict().FindString(kHidSerialNumberKey); if (serial_number && device_serial_number && *device_serial_number == *serial_number) return true; } else if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::SERIAL)) { #if BUILDFLAG(IS_WIN) const auto* instance_id = device.GetDict().FindString(kDeviceInstanceIdKey); const auto* port_instance_id = device_to_compare->GetDict().FindString(kDeviceInstanceIdKey); if (instance_id && port_instance_id && *instance_id == *port_instance_id) return true; #else const auto* serial_number = device.GetDict().FindString(kSerialNumberKey); const auto* port_serial_number = device_to_compare->GetDict().FindString(kSerialNumberKey); if (device.GetDict().FindInt(kVendorIdKey) != device_to_compare->GetDict().FindInt(kVendorIdKey) || device.GetDict().FindInt(kProductIdKey) != device_to_compare->GetDict().FindInt(kProductIdKey) || (serial_number && port_serial_number && *port_serial_number != *serial_number)) { return false; } #if BUILDFLAG(IS_MAC) const auto* usb_driver_key = device.GetDict().FindString(kUsbDriverKey); const auto* port_usb_driver_key = device_to_compare->GetDict().FindString(kUsbDriverKey); if (usb_driver_key && port_usb_driver_key && *usb_driver_key != *port_usb_driver_key) { return false; } #endif // BUILDFLAG(IS_MAC) return true; #endif // BUILDFLAG(IS_WIN) } return false; } bool ElectronBrowserContext::CheckDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return false; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return false; for (const auto& device_to_compare : origin_devices_it->second) { if (DoesDeviceMatch(device, device_to_compare.get(), permission_type)) return true; } return false; } // static ElectronBrowserContext* ElectronBrowserContext::From( const std::string& partition, bool in_memory, base::Value::Dict options) { PartitionKey key(partition, in_memory); ElectronBrowserContext* browser_context = browser_context_map()[key].get(); if (browser_context) { return browser_context; } auto* new_context = new ElectronBrowserContext(partition, in_memory, std::move(options)); browser_context_map()[key] = std::unique_ptr<ElectronBrowserContext>(new_context); return new_context; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,046
[Bug]: webContents.getUserAgent() is empty since 20.0.0-alpha.6
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.0-alpha.6 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version 20.0.0-alpha.5 ### Expected Behavior `webContents.getUserAgent()` returns a string with a user Agent ### Actual Behavior webContents.getUserAgent() returns an empty string ### Testcase Gist URL https://gist.github.com/33fd4a9ac6db6b28b1dcc5b765edb622 ### Additional Information In the console the user agent is printed in alpha.5, but empty in alpha.6. Looking at the diff between alpha.5 and alpha.6, this PR seems the likely cause: https://github.com/electron/electron/pull/34524 / #34481 It's worth noting that the renderer does have a filled-in userAgent.
https://github.com/electron/electron/issues/35046
https://github.com/electron/electron/pull/35069
8004cb8722c8d52f4cd553bbaea86750149e8ca4
9028bb79a85fedf64230c2f1c6a29ab072c98c20
2022-07-25T14:12:09Z
c++
2022-07-29T15:09:47Z
shell/browser/electron_browser_context.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_ELECTRON_BROWSER_CONTEXT_H_ #define ELECTRON_SHELL_BROWSER_ELECTRON_BROWSER_CONTEXT_H_ #include <map> #include <memory> #include <string> #include <vector> #include "base/memory/weak_ptr.h" #include "chrome/browser/predictors/preconnect_manager.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/resource_context.h" #include "electron/buildflags/buildflags.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/network/public/mojom/network_context.mojom.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" #include "shell/browser/media/media_device_id_salt.h" #include "third_party/blink/public/common/permissions/permission_utils.h" class PrefService; class ValueMapPrefStore; namespace network { class SharedURLLoaderFactory; } namespace storage { class SpecialStoragePolicy; } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) namespace extensions { class ElectronExtensionSystem; } #endif namespace electron { using DevicePermissionMap = std::map<blink::PermissionType, std::map<url::Origin, std::vector<std::unique_ptr<base::Value>>>>; class ElectronDownloadManagerDelegate; class ElectronPermissionManager; class CookieChangeNotifier; class ResolveProxyHelper; class WebViewManager; class ProtocolRegistry; class ElectronBrowserContext : public content::BrowserContext { public: // disable copy ElectronBrowserContext(const ElectronBrowserContext&) = delete; ElectronBrowserContext& operator=(const ElectronBrowserContext&) = delete; // partition_id => browser_context struct PartitionKey { std::string partition; bool in_memory; PartitionKey(const std::string& partition, bool in_memory) : partition(partition), in_memory(in_memory) {} bool operator<(const PartitionKey& other) const { if (partition == other.partition) return in_memory < other.in_memory; return partition < other.partition; } bool operator==(const PartitionKey& other) const { return (partition == other.partition) && (in_memory == other.in_memory); } }; using BrowserContextMap = std::map<PartitionKey, std::unique_ptr<ElectronBrowserContext>>; // Get or create the BrowserContext according to its |partition| and // |in_memory|. The |options| will be passed to constructor when there is no // existing BrowserContext. static ElectronBrowserContext* From(const std::string& partition, bool in_memory, base::Value::Dict options = {}); static BrowserContextMap& browser_context_map(); void SetUserAgent(const std::string& user_agent); std::string GetUserAgent() const; absl::optional<std::string> GetUserAgentOverride() const; bool CanUseHttpCache() const; int GetMaxCacheSize() const; ResolveProxyHelper* GetResolveProxyHelper(); predictors::PreconnectManager* GetPreconnectManager(); scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory(); // content::BrowserContext: base::FilePath GetPath() override; bool IsOffTheRecord() override; content::ResourceContext* GetResourceContext() override; std::unique_ptr<content::ZoomLevelDelegate> CreateZoomLevelDelegate( const base::FilePath& partition_path) override; content::PushMessagingService* GetPushMessagingService() override; content::SSLHostStateDelegate* GetSSLHostStateDelegate() override; content::BackgroundFetchDelegate* GetBackgroundFetchDelegate() override; content::BackgroundSyncController* GetBackgroundSyncController() override; content::BrowsingDataRemoverDelegate* GetBrowsingDataRemoverDelegate() override; std::string GetMediaDeviceIDSalt() override; content::DownloadManagerDelegate* GetDownloadManagerDelegate() override; content::BrowserPluginGuestManager* GetGuestManager() override; content::PlatformNotificationService* GetPlatformNotificationService() override; content::PermissionControllerDelegate* GetPermissionControllerDelegate() override; storage::SpecialStoragePolicy* GetSpecialStoragePolicy() override; content::ClientHintsControllerDelegate* GetClientHintsControllerDelegate() override; content::StorageNotificationService* GetStorageNotificationService() override; CookieChangeNotifier* cookie_change_notifier() const { return cookie_change_notifier_.get(); } PrefService* prefs() const { return prefs_.get(); } void set_in_memory_pref_store(ValueMapPrefStore* pref_store) { in_memory_pref_store_ = pref_store; } ValueMapPrefStore* in_memory_pref_store() const { return in_memory_pref_store_; } base::WeakPtr<ElectronBrowserContext> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ElectronExtensionSystem* extension_system() { // Guard usages of extension_system() with !IsOffTheRecord() // There is no extension system for in-memory sessions DCHECK(!IsOffTheRecord()); return extension_system_; } #endif ProtocolRegistry* protocol_registry() const { return protocol_registry_.get(); } void SetSSLConfig(network::mojom::SSLConfigPtr config); network::mojom::SSLConfigPtr GetSSLConfig(); void SetSSLConfigClient(mojo::Remote<network::mojom::SSLConfigClient> client); ~ElectronBrowserContext() override; // Grants |origin| access to |device|. // To be used in place of ObjectPermissionContextBase::GrantObjectPermission. void GrantDevicePermission(const url::Origin& origin, const base::Value& device, blink::PermissionType permissionType); // Revokes |origin| access to |device|. // To be used in place of ObjectPermissionContextBase::RevokeObjectPermission. void RevokeDevicePermission(const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type); // Returns the list of devices that |origin| has been granted permission to // access. To be used in place of // ObjectPermissionContextBase::GetGrantedObjects. bool CheckDevicePermission(const url::Origin& origin, const base::Value& device, blink::PermissionType permissionType); private: ElectronBrowserContext(const std::string& partition, bool in_memory, base::Value::Dict options); // Initialize pref registry. void InitPrefs(); bool DoesDeviceMatch(const base::Value& device, const base::Value* device_to_compare, blink::PermissionType permission_type); ValueMapPrefStore* in_memory_pref_store_ = nullptr; std::unique_ptr<content::ResourceContext> resource_context_; std::unique_ptr<CookieChangeNotifier> cookie_change_notifier_; std::unique_ptr<PrefService> prefs_; std::unique_ptr<ElectronDownloadManagerDelegate> download_manager_delegate_; std::unique_ptr<WebViewManager> guest_manager_; std::unique_ptr<ElectronPermissionManager> permission_manager_; std::unique_ptr<MediaDeviceIDSalt> media_device_id_salt_; scoped_refptr<ResolveProxyHelper> resolve_proxy_helper_; scoped_refptr<storage::SpecialStoragePolicy> storage_policy_; std::unique_ptr<predictors::PreconnectManager> preconnect_manager_; std::unique_ptr<ProtocolRegistry> protocol_registry_; absl::optional<std::string> user_agent_; base::FilePath path_; bool in_memory_ = false; bool use_cache_ = true; int max_cache_size_ = 0; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // Owned by the KeyedService system. extensions::ElectronExtensionSystem* extension_system_; #endif // Shared URLLoaderFactory. scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; network::mojom::SSLConfigPtr ssl_config_; mojo::Remote<network::mojom::SSLConfigClient> ssl_config_client_; // In-memory cache that holds objects that have been granted permissions. DevicePermissionMap granted_devices_; base::WeakPtrFactory<ElectronBrowserContext> weak_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_ELECTRON_BROWSER_CONTEXT_H_
closed
electron/electron
https://github.com/electron/electron
35,046
[Bug]: webContents.getUserAgent() is empty since 20.0.0-alpha.6
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.0-alpha.6 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version 20.0.0-alpha.5 ### Expected Behavior `webContents.getUserAgent()` returns a string with a user Agent ### Actual Behavior webContents.getUserAgent() returns an empty string ### Testcase Gist URL https://gist.github.com/33fd4a9ac6db6b28b1dcc5b765edb622 ### Additional Information In the console the user agent is printed in alpha.5, but empty in alpha.6. Looking at the diff between alpha.5 and alpha.6, this PR seems the likely cause: https://github.com/electron/electron/pull/34524 / #34481 It's worth noting that the renderer does have a filled-in userAgent.
https://github.com/electron/electron/issues/35046
https://github.com/electron/electron/pull/35069
8004cb8722c8d52f4cd553bbaea86750149e8ca4
9028bb79a85fedf64230c2f1c6a29ab072c98c20
2022-07-25T14:12:09Z
c++
2022-07-29T15:09:47Z
spec-main/api-web-contents-spec.ts
import { expect } from 'chai'; import { AddressInfo } from 'net'; import * as path from 'path'; import * as fs from 'fs'; import * as http from 'http'; import { BrowserWindow, ipcMain, webContents, session, WebContents, app, BrowserView } from 'electron/main'; import { emittedOnce } from './events-helpers'; import { closeAllWindows } from './window-helpers'; import { ifdescribe, delay, defer } from './spec-helpers'; const pdfjs = require('pdfjs-dist'); const fixturesPath = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixturesPath = path.resolve(__dirname, 'fixtures'); const features = process._linkedBinding('electron_common_features'); describe('webContents module', () => { describe('getAllWebContents() API', () => { afterEach(closeAllWindows); it('returns an array of web contents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html')); await emittedOnce(w.webContents, 'did-attach-webview'); w.webContents.openDevTools(); await emittedOnce(w.webContents, 'devtools-opened'); const all = webContents.getAllWebContents().sort((a, b) => { return a.id - b.id; }); expect(all).to.have.length(3); expect(all[0].getType()).to.equal('window'); expect(all[all.length - 2].getType()).to.equal('webview'); expect(all[all.length - 1].getType()).to.equal('remote'); }); }); describe('fromId()', () => { it('returns undefined for an unknown id', () => { expect(webContents.fromId(12345)).to.be.undefined(); }); }); describe('fromDevToolsTargetId()', () => { it('returns WebContents for attached DevTools target', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); try { await w.webContents.debugger.attach('1.3'); const { targetInfo } = await w.webContents.debugger.sendCommand('Target.getTargetInfo'); expect(webContents.fromDevToolsTargetId(targetInfo.targetId)).to.equal(w.webContents); } finally { await w.webContents.debugger.detach(); } }); it('returns undefined for an unknown id', () => { expect(webContents.fromDevToolsTargetId('nope')).to.be.undefined(); }); }); describe('will-prevent-unload event', function () { afterEach(closeAllWindows); it('does not emit if beforeunload returns undefined in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('does not emit if beforeunload returns undefined in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); view.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits if beforeunload returns false in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'will-prevent-unload'); }); it('emits if beforeunload returns false in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(view.webContents, 'will-prevent-unload'); }); it('supports calling preventDefault on will-prevent-unload events in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', event => event.preventDefault()); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); }); describe('webContents.send(channel, args...)', () => { afterEach(closeAllWindows); it('throws an error when the channel is missing', () => { const w = new BrowserWindow({ show: false }); expect(() => { (w.webContents.send as any)(); }).to.throw('Missing required channel argument'); expect(() => { w.webContents.send(null as any); }).to.throw('Missing required channel argument'); }); it('does not block node async APIs when sent before document is ready', (done) => { // Please reference https://github.com/electron/electron/issues/19368 if // this test fails. ipcMain.once('async-node-api-done', () => { done(); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, sandbox: false, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html')); setTimeout(() => { w.webContents.send('test'); }, 50); }); }); ifdescribe(features.isPrintingEnabled())('webContents.print()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('throws when invalid settings are passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print(true); }).to.throw('webContents.print(): Invalid print settings specified.'); }); it('throws when an invalid callback is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({}, true); }).to.throw('webContents.print(): Invalid optional callback provided.'); }); it('fails when an invalid deviceName is passed', (done) => { w.webContents.print({ deviceName: 'i-am-a-nonexistent-printer' }, (success, reason) => { expect(success).to.equal(false); expect(reason).to.match(/Invalid deviceName provided/); done(); }); }); it('throws when an invalid pageSize is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({ pageSize: 'i-am-a-bad-pagesize' }, () => {}); }).to.throw('Unsupported pageSize: i-am-a-bad-pagesize'); }); it('throws when an invalid custom pageSize is passed', () => { expect(() => { w.webContents.print({ pageSize: { width: 100, height: 200 } }); }).to.throw('height and width properties must be minimum 352 microns.'); }); it('does not crash with custom margins', () => { expect(() => { w.webContents.print({ silent: true, margins: { marginType: 'custom', top: 1, bottom: 1, left: 1, right: 1 } }); }).to.not.throw(); }); }); describe('webContents.executeJavaScript', () => { describe('in about:blank', () => { const expected = 'hello, world!'; const expectedErrorMsg = 'woops!'; const code = `(() => "${expected}")()`; const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`; const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`; const errorTypes = new Set([ Error, ReferenceError, EvalError, RangeError, SyntaxError, TypeError, URIError ]); let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false } }); await w.loadURL('about:blank'); }); after(closeAllWindows); it('resolves the returned promise with the result', async () => { const result = await w.webContents.executeJavaScript(code); expect(result).to.equal(expected); }); it('resolves the returned promise with the result if the code returns an asynchronous promise', async () => { const result = await w.webContents.executeJavaScript(asyncCode); expect(result).to.equal(expected); }); it('rejects the returned promise if an async error is thrown', async () => { await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg); }); it('rejects the returned promise with an error if an Error.prototype is thrown', async () => { for (const error of errorTypes) { await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`)) .to.eventually.be.rejectedWith(error); } }); }); describe('on a real page', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('works after page load and during subframe load', async () => { await w.loadURL(serverUrl); // initiate a sub-frame load, then try and execute script during it await w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/slow' document.body.appendChild(iframe) null // don't return the iframe `); await w.webContents.executeJavaScript('console.log(\'hello\')'); }); it('executes after page load', async () => { const executeJavaScript = w.webContents.executeJavaScript('(() => "test")()'); w.loadURL(serverUrl); const result = await executeJavaScript; expect(result).to.equal('test'); }); }); }); describe('webContents.executeJavaScriptInIsolatedWorld', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadURL('about:blank'); }); it('resolves the returned promise with the result', async () => { await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X = 123' }]); const isolatedResult = await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X' }]); const mainWorldResult = await w.webContents.executeJavaScript('window.X'); expect(isolatedResult).to.equal(123); expect(mainWorldResult).to.equal(undefined); }); }); describe('loadURL() promise API', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('resolves when done loading', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('resolves when done loading a file URL', async () => { await expect(w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'))).to.eventually.be.fulfilled(); }); it('rejects when failing to load a file URL', async () => { await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FILE_NOT_FOUND'); }); // Temporarily disable on WOA until // https://github.com/electron/electron/issues/20008 is resolved const testFn = (process.platform === 'win32' && process.arch === 'arm64' ? it.skip : it); testFn('rejects when loading fails due to DNS not resolved', async () => { await expect(w.loadURL('https://err.name.not.resolved')).to.eventually.be.rejected() .and.have.property('code', 'ERR_NAME_NOT_RESOLVED'); }); it('rejects when navigation is cancelled due to a bad scheme', async () => { await expect(w.loadURL('bad-scheme://foo')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FAILED'); }); it('sets appropriate error information on rejection', async () => { let err: any; try { await w.loadURL('file:non-existent'); } catch (e) { err = e; } expect(err).not.to.be.null(); expect(err.code).to.eql('ERR_FILE_NOT_FOUND'); expect(err.errno).to.eql(-6); expect(err.url).to.eql(process.platform === 'win32' ? 'file://non-existent/' : 'file:///non-existent'); }); it('rejects if the load is aborted', async () => { const s = http.createServer(() => { /* never complete the request */ }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = expect(w.loadURL(`http://127.0.0.1:${port}`)).to.eventually.be.rejectedWith(Error, /ERR_ABORTED/); // load a different file before the first load completes, causing the // first load to be aborted. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); await p; s.close(); }); it("doesn't reject when a subframe fails to load", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="http://err.name.not.resolved"></iframe>'); resp = res; // don't end the response yet }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = new Promise<void>(resolve => { w.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.end(); await main; s.close(); }); it("doesn't resolve when a subframe loads", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="about:blank"></iframe>'); resp = res; // don't end the response yet }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = new Promise<void>(resolve => { w.webContents.on('did-frame-finish-load', (event, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.destroy(); // cause the main request to fail await expect(main).to.eventually.be.rejected() .and.have.property('errno', -355); // ERR_INCOMPLETE_CHUNKED_ENCODING s.close(); }); }); describe('getFocusedWebContents() API', () => { afterEach(closeAllWindows); const testFn = (process.platform === 'win32' && process.arch === 'arm64' ? it.skip : it); testFn('returns the focused web contents', async () => { const w = new BrowserWindow({ show: true }); await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.id); const devToolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.openDevTools(); await devToolsOpened; expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.devToolsWebContents!.id); const devToolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.id); }); it('does not crash when called on a detached dev tools window', async () => { const w = new BrowserWindow({ show: true }); w.webContents.openDevTools({ mode: 'detach' }); w.webContents.inspectElement(100, 100); // For some reason we have to wait for two focused events...? await emittedOnce(w.webContents, 'devtools-focused'); expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); // Work around https://github.com/electron/electron/issues/19985 await delay(); const devToolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); }); }); describe('setDevToolsWebContents() API', () => { afterEach(closeAllWindows); it('sets arbitrary webContents as devtools', async () => { const w = new BrowserWindow({ show: false }); const devtools = new BrowserWindow({ show: false }); const promise = emittedOnce(devtools.webContents, 'dom-ready'); w.webContents.setDevToolsWebContents(devtools.webContents); w.webContents.openDevTools(); await promise; expect(devtools.webContents.getURL().startsWith('devtools://devtools')).to.be.true(); const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name'); expect(result).to.equal('InspectorFrontendHostImpl'); devtools.destroy(); }); }); describe('isFocused() API', () => { it('returns false when the window is hidden', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(w.isVisible()).to.be.false(); expect(w.webContents.isFocused()).to.be.false(); }); }); describe('isCurrentlyAudible() API', () => { afterEach(closeAllWindows); it('returns whether audio is playing', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await w.webContents.executeJavaScript(` window.context = new AudioContext // Start in suspended state, because of the // new web audio api policy. context.suspend() window.oscillator = context.createOscillator() oscillator.connect(context.destination) oscillator.start() `); let p = emittedOnce(w.webContents, '-audio-state-changed'); w.webContents.executeJavaScript('context.resume()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.true(); p = emittedOnce(w.webContents, '-audio-state-changed'); w.webContents.executeJavaScript('oscillator.stop()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.false(); }); }); describe('openDevTools() API', () => { afterEach(closeAllWindows); it('can show window with activation', async () => { const w = new BrowserWindow({ show: false }); const focused = emittedOnce(w, 'focus'); w.show(); await focused; expect(w.isFocused()).to.be.true(); const blurred = emittedOnce(w, 'blur'); w.webContents.openDevTools({ mode: 'detach', activate: true }); await Promise.all([ emittedOnce(w.webContents, 'devtools-opened'), emittedOnce(w.webContents, 'devtools-focused') ]); await blurred; expect(w.isFocused()).to.be.false(); }); it('can show window without activation', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: false }); await devtoolsOpened; expect(w.webContents.isDevToolsOpened()).to.be.true(); }); }); describe('before-input-event event', () => { afterEach(closeAllWindows); it('can prevent document keyboard events', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); const keyDown = new Promise(resolve => { ipcMain.once('keydown', (event, key) => resolve(key)); }); w.webContents.once('before-input-event', (event, input) => { if (input.key === 'a') event.preventDefault(); }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' }); expect(await keyDown).to.equal('b'); }); it('has the correct properties', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testBeforeInput = async (opts: any) => { const modifiers = []; if (opts.shift) modifiers.push('shift'); if (opts.control) modifiers.push('control'); if (opts.alt) modifiers.push('alt'); if (opts.meta) modifiers.push('meta'); if (opts.isAutoRepeat) modifiers.push('isAutoRepeat'); const p = emittedOnce(w.webContents, 'before-input-event'); w.webContents.sendInputEvent({ type: opts.type, keyCode: opts.keyCode, modifiers: modifiers as any }); const [, input] = await p; expect(input.type).to.equal(opts.type); expect(input.key).to.equal(opts.key); expect(input.code).to.equal(opts.code); expect(input.isAutoRepeat).to.equal(opts.isAutoRepeat); expect(input.shift).to.equal(opts.shift); expect(input.control).to.equal(opts.control); expect(input.alt).to.equal(opts.alt); expect(input.meta).to.equal(opts.meta); }; await testBeforeInput({ type: 'keyDown', key: 'A', code: 'KeyA', keyCode: 'a', shift: true, control: true, alt: true, meta: true, isAutoRepeat: true }); await testBeforeInput({ type: 'keyUp', key: '.', code: 'Period', keyCode: '.', shift: false, control: true, alt: true, meta: false, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: '!', code: 'Digit1', keyCode: '1', shift: true, control: false, alt: false, meta: true, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: 'Tab', code: 'Tab', keyCode: 'Tab', shift: false, control: true, alt: false, meta: false, isAutoRepeat: true }); }); }); // On Mac, zooming isn't done with the mouse wheel. ifdescribe(process.platform !== 'darwin')('zoom-changed', () => { afterEach(closeAllWindows); it('is emitted with the correct zoom-in info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: 1, wheelTicksX: 0, wheelTicksY: 1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await emittedOnce(w.webContents, 'zoom-changed'); expect(zoomDirection).to.equal('in'); }; await testZoomChanged(); }); it('is emitted with the correct zoom-out info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: -1, wheelTicksX: 0, wheelTicksY: -1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await emittedOnce(w.webContents, 'zoom-changed'); expect(zoomDirection).to.equal('out'); }; await testZoomChanged(); }); }); describe('sendInputEvent(event)', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); }); afterEach(closeAllWindows); it('can send keydown events', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can send keydown events with modifiers', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); it('can send keydown events with special keys', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab', modifiers: ['alt'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Tab'); expect(code).to.equal('Tab'); expect(keyCode).to.equal(9); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.true(); }); it('can send char events', async () => { const keypress = emittedOnce(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can send char events with modifiers', async () => { const keypress = emittedOnce(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); }); describe('insertCSS', () => { afterEach(closeAllWindows); it('supports inserting CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.webContents.insertCSS('body { background-repeat: round; }'); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('round'); }); it('supports removing inserted CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); const key = await w.webContents.insertCSS('body { background-repeat: round; }'); await w.webContents.removeInsertedCSS(key); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('repeat'); }); }); describe('inspectElement()', () => { afterEach(closeAllWindows); it('supports inspecting an element in the devtools', (done) => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.once('devtools-opened', () => { done(); }); w.webContents.inspectElement(10, 10); }); }); describe('startDrag({file, icon})', () => { it('throws errors for a missing file or a missing/empty icon', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.startDrag({ icon: path.join(fixturesPath, 'assets', 'logo.png') } as any); }).to.throw('Must specify either \'file\' or \'files\' option'); expect(() => { w.webContents.startDrag({ file: __filename } as any); }).to.throw('\'icon\' parameter is required'); expect(() => { w.webContents.startDrag({ file: __filename, icon: path.join(mainFixturesPath, 'blank.png') }); }).to.throw(/Failed to load image from path (.+)/); }); }); describe('focus APIs', () => { describe('focus()', () => { afterEach(closeAllWindows); it('does not blur the focused window when the web contents is hidden', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.show(); await w.loadURL('about:blank'); w.focus(); const child = new BrowserWindow({ show: false }); child.loadURL('about:blank'); child.webContents.focus(); const currentFocused = w.isFocused(); const childFocused = child.isFocused(); child.close(); expect(currentFocused).to.be.true(); expect(childFocused).to.be.false(); }); }); const moveFocusToDevTools = async (win: BrowserWindow) => { const devToolsOpened = emittedOnce(win.webContents, 'devtools-opened'); win.webContents.openDevTools({ mode: 'right' }); await devToolsOpened; win.webContents.devToolsWebContents!.focus(); }; describe('focus event', () => { afterEach(closeAllWindows); it('is triggered when web contents is focused', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await moveFocusToDevTools(w); const focusPromise = emittedOnce(w.webContents, 'focus'); w.webContents.focus(); await expect(focusPromise).to.eventually.be.fulfilled(); }); it('is triggered when BrowserWindow is focused', async () => { const window1 = new BrowserWindow({ show: false }); const window2 = new BrowserWindow({ show: false }); await Promise.all([ window1.loadURL('about:blank'), window2.loadURL('about:blank') ]); const focusPromise1 = emittedOnce(window1.webContents, 'focus'); const focusPromise2 = emittedOnce(window2.webContents, 'focus'); window1.showInactive(); window2.showInactive(); window1.focus(); await expect(focusPromise1).to.eventually.be.fulfilled(); window2.focus(); await expect(focusPromise2).to.eventually.be.fulfilled(); }); }); describe('blur event', () => { afterEach(closeAllWindows); it('is triggered when web contents is blurred', async () => { const w = new BrowserWindow({ show: true }); await w.loadURL('about:blank'); w.webContents.focus(); const blurPromise = emittedOnce(w.webContents, 'blur'); await moveFocusToDevTools(w); await expect(blurPromise).to.eventually.be.fulfilled(); }); }); }); describe('getOSProcessId()', () => { afterEach(closeAllWindows); it('returns a valid process id', async () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getOSProcessId()).to.equal(0); await w.loadURL('about:blank'); expect(w.webContents.getOSProcessId()).to.be.above(0); }); }); describe('getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns a valid stream id', () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getMediaSourceId(w.webContents)).to.be.a('string').that.is.not.empty(); }); }); describe('userAgent APIs', () => { it('can set the user agent (functions)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.getUserAgent(); w.webContents.setUserAgent('my-user-agent'); expect(w.webContents.getUserAgent()).to.equal('my-user-agent'); w.webContents.setUserAgent(userAgent); expect(w.webContents.getUserAgent()).to.equal(userAgent); }); it('can set the user agent (properties)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.userAgent; w.webContents.userAgent = 'my-user-agent'; expect(w.webContents.userAgent).to.equal('my-user-agent'); w.webContents.userAgent = userAgent; expect(w.webContents.userAgent).to.equal(userAgent); }); }); describe('audioMuted APIs', () => { it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.setAudioMuted(true); expect(w.webContents.isAudioMuted()).to.be.true(); w.webContents.setAudioMuted(false); expect(w.webContents.isAudioMuted()).to.be.false(); }); it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.audioMuted = true; expect(w.webContents.audioMuted).to.be.true(); w.webContents.audioMuted = false; expect(w.webContents.audioMuted).to.be.false(); }); }); describe('zoom api', () => { const hostZoomMap: Record<string, number> = { host1: 0.3, host2: 0.7, host3: 0.2 }; before(() => { const protocol = session.defaultSession.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { const response = `<script> const {ipcRenderer} = require('electron') ipcRenderer.send('set-zoom', window.location.hostname) ipcRenderer.on(window.location.hostname + '-zoom-set', () => { ipcRenderer.send(window.location.hostname + '-zoom-level') }) </script>`; callback({ data: response, mimeType: 'text/html' }); }); }); after(() => { const protocol = session.defaultSession.protocol; protocol.unregisterProtocol(standardScheme); }); afterEach(closeAllWindows); it('throws on an invalid zoomFactor', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { w.webContents.setZoomFactor(0.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); expect(() => { w.webContents.setZoomFactor(-2.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); }); it('can set the correct zoom level (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.getZoomLevel(); expect(zoomLevel).to.eql(0.0); w.webContents.setZoomLevel(0.5); const newZoomLevel = w.webContents.getZoomLevel(); expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.setZoomLevel(0); } }); it('can set the correct zoom level (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.eql(0.0); w.webContents.zoomLevel = 0.5; const newZoomLevel = w.webContents.zoomLevel; expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.zoomLevel = 0; } }); it('can set the correct zoom factor (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.getZoomFactor(); expect(zoomFactor).to.eql(1.0); w.webContents.setZoomFactor(0.5); const newZoomFactor = w.webContents.getZoomFactor(); expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.setZoomFactor(1.0); } }); it('can set the correct zoom factor (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.zoomFactor; expect(zoomFactor).to.eql(1.0); w.webContents.zoomFactor = 0.5; const newZoomFactor = w.webContents.zoomFactor; expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.zoomFactor = 1.0; } }); it('can persist zoom level across navigation', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let finalNavigation = false; ipcMain.on('set-zoom', (e, host) => { const zoomLevel = hostZoomMap[host]; if (!finalNavigation) w.webContents.zoomLevel = zoomLevel; e.sender.send(`${host}-zoom-set`); }); ipcMain.on('host1-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host1; expect(zoomLevel).to.equal(expectedZoomLevel); if (finalNavigation) { done(); } else { w.loadURL(`${standardScheme}://host2`); } } catch (e) { done(e); } }); ipcMain.once('host2-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host2; expect(zoomLevel).to.equal(expectedZoomLevel); finalNavigation = true; w.webContents.goBack(); } catch (e) { done(e); } }); w.loadURL(`${standardScheme}://host1`); }); it('can propagate zoom level across same session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false }); defer(() => { w2.setClosable(true); w2.close(); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel1).to.equal(zoomLevel2); }); it('cannot propagate zoom level across different session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false, webPreferences: { partition: 'temp' } }); const protocol = w2.webContents.session.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { callback('hello'); }); defer(() => { w2.setClosable(true); w2.close(); protocol.unregisterProtocol(standardScheme); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); it('can persist when it contains iframe', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { setTimeout(() => { res.end(); }, 200); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; const content = `<iframe src=${url}></iframe>`; w.webContents.on('did-frame-finish-load', (e, isMainFrame) => { if (!isMainFrame) { try { const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(2.0); w.webContents.zoomLevel = 0; done(); } catch (e) { done(e); } finally { server.close(); } } }); w.webContents.on('dom-ready', () => { w.webContents.zoomLevel = 2.0; }); w.loadURL(`data:text/html,${content}`); }); }); it('cannot propagate when used with webframe', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const w2 = new BrowserWindow({ show: false }); const temporaryZoomSet = emittedOnce(ipcMain, 'temporary-zoom-set'); w.loadFile(path.join(fixturesPath, 'pages', 'webframe-zoom.html')); await temporaryZoomSet; const finalZoomLevel = w.webContents.getZoomLevel(); await w2.loadFile(path.join(fixturesPath, 'pages', 'c.html')); const zoomLevel1 = w.webContents.zoomLevel; const zoomLevel2 = w2.webContents.zoomLevel; w2.setClosable(true); w2.close(); expect(zoomLevel1).to.equal(finalZoomLevel); expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); describe('with unique domains', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before((done) => { server = http.createServer((req, res) => { setTimeout(() => res.end('hey'), 0); }); server.listen(0, '127.0.0.1', () => { serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; crossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('cannot persist zoom level after navigation with webFrame', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const source = ` const {ipcRenderer, webFrame} = require('electron') webFrame.setZoomLevel(0.6) ipcRenderer.send('zoom-level-set', webFrame.getZoomLevel()) `; const zoomLevelPromise = emittedOnce(ipcMain, 'zoom-level-set'); await w.loadURL(serverUrl); await w.webContents.executeJavaScript(source); let [, zoomLevel] = await zoomLevelPromise; expect(zoomLevel).to.equal(0.6); const loadPromise = emittedOnce(w.webContents, 'did-finish-load'); await w.loadURL(crossSiteUrl); await loadPromise; zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(0); }); }); }); describe('webrtc ip policy api', () => { afterEach(closeAllWindows); it('can set and get webrtc ip policies', () => { const w = new BrowserWindow({ show: false }); const policies = [ 'default', 'default_public_interface_only', 'default_public_and_private_interfaces', 'disable_non_proxied_udp' ]; policies.forEach((policy) => { w.webContents.setWebRTCIPHandlingPolicy(policy as any); expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy); }); }); }); describe('render view deleted events', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before((done) => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${crossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else if (req.url === '/first-window-open') { res.end(`<html><script>window.open('${serverUrl}/second-window-open', 'first child');</script></html>`); } else if (req.url === '/second-window-open') { res.end('<html><script>window.open(\'wrong://url\', \'second child\');</script></html>'); } else { res.end(); } }; setTimeout(respond, 0); }); server.listen(0, '127.0.0.1', () => { serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; crossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); afterEach(closeAllWindows); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; w.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); w.webContents.on('did-finish-load', () => { w.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('current-render-view-deleted was emitted'); }); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const parentWindow = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; let childWindow: BrowserWindow | null = null; const destroyed = emittedOnce(parentWindow.webContents, 'destroyed'); const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; const childWindowCreated = new Promise<void>((resolve) => { app.once('browser-window-created', (event, window) => { childWindow = window; window.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); resolve(); }); }); parentWindow.loadURL(`${serverUrl}/first-window-open`); await childWindowCreated; childWindow!.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); parentWindow.close(); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('child window was destroyed'); }); it('emits current-render-view-deleted if the current RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; w.webContents.on('current-render-view-deleted' as any, () => { currentRenderViewDeletedEmitted = true; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.true('current-render-view-deleted wasn\'t emitted'); }); it('emits render-view-deleted if any RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let rvhDeletedCount = 0; w.webContents.on('render-view-deleted' as any, () => { rvhDeletedCount++; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; const expectedRenderViewDeletedEventCount = 1; expect(rvhDeletedCount).to.equal(expectedRenderViewDeletedEventCount, 'render-view-deleted wasn\'t emitted the expected nr. of times'); }); }); describe('setIgnoreMenuShortcuts(ignore)', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.setIgnoreMenuShortcuts(true); w.webContents.setIgnoreMenuShortcuts(false); }).to.not.throw(); }); }); const crashPrefs = [ { nodeIntegration: true }, { sandbox: true } ]; const nicePrefs = (o: any) => { let s = ''; for (const key of Object.keys(o)) { s += `${key}=${o[key]}, `; } return `(${s.slice(0, s.length - 2)})`; }; for (const prefs of crashPrefs) { describe(`crash with webPreferences ${nicePrefs(prefs)}`, () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); it('isCrashed() is false by default', () => { expect(w.webContents.isCrashed()).to.equal(false); }); it('forcefullyCrashRenderer() crashes the process with reason=killed||crashed', async () => { expect(w.webContents.isCrashed()).to.equal(false); const crashEvent = emittedOnce(w.webContents, 'render-process-gone'); w.webContents.forcefullyCrashRenderer(); const [, details] = await crashEvent; expect(details.reason === 'killed' || details.reason === 'crashed').to.equal(true, 'reason should be killed || crashed'); expect(w.webContents.isCrashed()).to.equal(true); }); it('a crashed process is recoverable with reload()', async () => { expect(w.webContents.isCrashed()).to.equal(false); w.webContents.forcefullyCrashRenderer(); w.webContents.reload(); expect(w.webContents.isCrashed()).to.equal(false); }); }); } // Destroying webContents in its event listener is going to crash when // Electron is built in Debug mode. describe('destroy()', () => { let server: http.Server; let serverUrl: string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/200': response.end(); break; default: done('unsupported endpoint'); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', url: '/200' }, { name: 'dom-ready', url: '/200' }, { name: 'did-stop-loading', url: '/200' }, { name: 'did-finish-load', url: '/200' }, // FIXME: Multiple Emit calls inside an observer assume that object // will be alive till end of the observer. Synchronous `destroy` api // violates this contract and crashes. { name: 'did-frame-finish-load', url: '/200' }, { name: 'did-fail-load', url: '/net-error' } ]; for (const e of events) { it(`should not crash when invoked synchronously inside ${e.name} handler`, async function () { // This test is flaky on Windows CI and we don't know why, but the // purpose of this test is to make sure Electron does not crash so it // is fine to retry this test for a few times. this.retries(3); const contents = (webContents as any).create() as WebContents; const originalEmit = contents.emit.bind(contents); contents.emit = (...args) => { return originalEmit(...args); }; contents.once(e.name as any, () => (contents as any).destroy()); const destroyed = emittedOnce(contents, 'destroyed'); contents.loadURL(serverUrl + e.url); await destroyed; }); } }); describe('did-change-theme-color event', () => { afterEach(closeAllWindows); it('is triggered with correct theme color', (done) => { const w = new BrowserWindow({ show: true }); let count = 0; w.webContents.on('did-change-theme-color', (e, color) => { try { if (count === 0) { count += 1; expect(color).to.equal('#FFEEDD'); w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); } else if (count === 1) { expect(color).to.be.null(); done(); } } catch (e) { done(e); } }); w.loadFile(path.join(fixturesPath, 'pages', 'theme-color.html')); }); }); describe('console-message event', () => { afterEach(closeAllWindows); it('is triggered with correct log message', (done) => { const w = new BrowserWindow({ show: true }); w.webContents.on('console-message', (e, level, message) => { // Don't just assert as Chromium might emit other logs that we should ignore. if (message === 'a') { done(); } }); w.loadFile(path.join(fixturesPath, 'pages', 'a.html')); }); }); describe('ipc-message event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends an asynchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); w.webContents.executeJavaScript(` require('electron').ipcRenderer.send('message', 'Hello World!') `); const [, channel, message] = await emittedOnce(w.webContents, 'ipc-message'); expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); }); }); describe('ipc-message-sync event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends a synchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); const promise: Promise<[string, string]> = new Promise(resolve => { w.webContents.once('ipc-message-sync', (event, channel, arg) => { event.returnValue = 'foobar' as any; resolve([channel, arg]); }); }); const result = await w.webContents.executeJavaScript(` require('electron').ipcRenderer.sendSync('message', 'Hello World!') `); const [channel, message] = await promise; expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); expect(result).to.equal('foobar'); }); }); describe('referrer', () => { afterEach(closeAllWindows); it('propagates referrer information to new target=_blank windows', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } finally { server.close(); } } res.end('<a id="a" href="/should_have_referrer" target="_blank">link</a>'); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/'; w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url); expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin'); return { action: 'allow' }; }); w.webContents.executeJavaScript('a.click()'); }); w.loadURL(url); }); }); // TODO(jeremy): window.open() in a real browser passes the referrer, but // our hacked-up window.open() shim doesn't. It should. xit('propagates referrer information to windows opened with window.open', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } } res.end(''); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/'; w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url); expect(details.referrer.policy).to.equal('no-referrer-when-downgrade'); return { action: 'allow' }; }); w.webContents.executeJavaScript('window.open(location.href + "should_have_referrer")'); }); w.loadURL(url); }); }); }); describe('webframe messages in sandboxed contents', () => { afterEach(closeAllWindows); it('responds to executeJavaScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const result = await w.webContents.executeJavaScript('37 + 5'); expect(result).to.equal(42); }); }); describe('preload-error event', () => { afterEach(closeAllWindows); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('is triggered when unhandled exception is thrown', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-exception.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('Hello World!'); }); it('is triggered on syntax errors', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-syntax.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('foobar is not defined'); }); it('is triggered when preload script loading fails', async () => { const preload = path.join(fixturesPath, 'module', 'preload-invalid.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.contain('preload-invalid.js'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('takeHeapSnapshot()', () => { afterEach(closeAllWindows); it('works with sandboxed renderers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot'); const cleanup = () => { try { fs.unlinkSync(filePath); } catch (e) { // ignore error } }; try { await w.webContents.takeHeapSnapshot(filePath); const stats = fs.statSync(filePath); expect(stats.size).not.to.be.equal(0); } finally { cleanup(); } }); it('fails with invalid file path', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const promise = w.webContents.takeHeapSnapshot(''); return expect(promise).to.be.eventually.rejectedWith(Error, 'takeHeapSnapshot failed'); }); }); describe('setBackgroundThrottling()', () => { afterEach(closeAllWindows); it('does not crash when allowing', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(true); }); it('does not crash when called via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); (w as any).setBackgroundThrottling(true); }); it('does not crash when disallowing', () => { const w = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: true } }); w.webContents.setBackgroundThrottling(false); }); }); describe('getBackgroundThrottling()', () => { afterEach(closeAllWindows); it('works via getter', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); expect(w.webContents.getBackgroundThrottling()).to.equal(false); w.webContents.setBackgroundThrottling(true); expect(w.webContents.getBackgroundThrottling()).to.equal(true); }); it('works via property', () => { const w = new BrowserWindow({ show: false }); w.webContents.backgroundThrottling = false; expect(w.webContents.backgroundThrottling).to.equal(false); w.webContents.backgroundThrottling = true; expect(w.webContents.backgroundThrottling).to.equal(true); }); it('works via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); (w as any).setBackgroundThrottling(false); expect((w as any).getBackgroundThrottling()).to.equal(false); (w as any).setBackgroundThrottling(true); expect((w as any).getBackgroundThrottling()).to.equal(true); }); }); ifdescribe(features.isPrintingEnabled())('getPrinters()', () => { afterEach(closeAllWindows); it('can get printer list', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const printers = w.webContents.getPrinters(); expect(printers).to.be.an('array'); }); }); ifdescribe(features.isPrintingEnabled())('getPrintersAsync()', () => { afterEach(closeAllWindows); it('can get printer list', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const printers = await w.webContents.getPrintersAsync(); expect(printers).to.be.an('array'); }); }); ifdescribe(features.isPrintingEnabled())('printToPDF()', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); }); afterEach(closeAllWindows); it('rejects on incorrectly typed parameters', async () => { const badTypes = { landscape: [], displayHeaderFooter: '123', printBackground: 2, scale: 'not-a-number', pageSize: 'IAmAPageSize', margins: 'terrible', pageRanges: { oops: 'im-not-the-right-key' }, headerTemplate: [1, 2, 3], footerTemplate: [4, 5, 6], preferCSSPageSize: 'no' }; // These will hard crash in Chromium unless we type-check for (const [key, value] of Object.entries(badTypes)) { const param = { [key]: value }; await expect(w.webContents.printToPDF(param)).to.eventually.be.rejected(); } }); it('can print to PDF', async () => { const data = await w.webContents.printToPDF({}); expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); }); it('does not crash when called multiple times in parallel', async () => { const promises = []; for (let i = 0; i < 3; i++) { promises.push(w.webContents.printToPDF({})); } const results = await Promise.all(promises); for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); it('does not crash when called multiple times in sequence', async () => { const results = []; for (let i = 0; i < 3; i++) { const result = await w.webContents.printToPDF({}); results.push(result); } for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); describe('using a large document', () => { beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf.html')); }); afterEach(closeAllWindows); it('respects custom settings', async () => { const data = await w.webContents.printToPDF({ pageRanges: '1-3', landscape: true }); const doc = await pdfjs.getDocument(data).promise; // Check that correct # of pages are rendered. expect(doc.numPages).to.equal(3); // Check that PDF is generated in landscape mode. const firstPage = await doc.getPage(1); const { width, height } = firstPage.getViewport({ scale: 100 }); expect(width).to.be.greaterThan(height); }); }); }); describe('PictureInPicture video', () => { afterEach(closeAllWindows); it('works as expected', async function () { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html')); if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) { this.skip(); } const result = await w.webContents.executeJavaScript( `runTest(${features.isPictureInPictureEnabled()})`, true); expect(result).to.be.true(); }); }); describe('Shared Workers', () => { afterEach(closeAllWindows); it('can get multiple shared workers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = emittedOnce(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); expect(sharedWorkers).to.have.lengthOf(2); expect(sharedWorkers[0].url).to.contain('shared-worker'); expect(sharedWorkers[1].url).to.contain('shared-worker'); }); it('can inspect a specific shared worker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = emittedOnce(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); const devtoolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.inspectSharedWorkerById(sharedWorkers[0].id); await devtoolsOpened; const devtoolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devtoolsClosed; }); }); describe('login event', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; let serverPort: number; let proxyServer: http.Server; let proxyServerPort: number; before((done) => { server = http.createServer((request, response) => { if (request.url === '/no-auth') { return response.end('ok'); } if (request.headers.authorization) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers.authorization); } response .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }) .end('401'); }).listen(0, '127.0.0.1', () => { serverPort = (server.address() as AddressInfo).port; serverUrl = `http://127.0.0.1:${serverPort}`; done(); }); }); before((done) => { proxyServer = http.createServer((request, response) => { if (request.headers['proxy-authorization']) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers['proxy-authorization']); } response .writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }) .end(); }).listen(0, '127.0.0.1', () => { proxyServerPort = (proxyServer.address() as AddressInfo).port; done(); }); }); afterEach(async () => { await session.defaultSession.clearAuthCache(); }); after(() => { server.close(); proxyServer.close(); }); it('is emitted when navigating', async () => { const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(serverUrl + '/'); expect(eventAuthInfo.isProxy).to.be.false(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(serverPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('is emitted when a proxy requests authorization', async () => { const customSession = session.fromPartition(`${Math.random()}`); await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' }); const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(`${serverUrl}/no-auth`); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`); expect(eventAuthInfo.isProxy).to.be.true(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(proxyServerPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('cancels authentication when callback is called with no arguments', async () => { const w = new BrowserWindow({ show: false }); w.webContents.on('login', (event, request, authInfo, cb) => { event.preventDefault(); cb(); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal('401'); }); }); describe('page-title-updated event', () => { afterEach(closeAllWindows); it('is emitted with a full title for pages with no navigation', async () => { const bw = new BrowserWindow({ show: false }); await bw.loadURL('about:blank'); bw.webContents.executeJavaScript('child = window.open("", "", "show=no"); null'); const [, child] = await emittedOnce(app, 'web-contents-created'); bw.webContents.executeJavaScript('child.document.title = "new title"'); const [, title] = await emittedOnce(child, 'page-title-updated'); expect(title).to.equal('new title'); }); }); describe('crashed event', () => { it('does not crash main process when destroying WebContents in it', (done) => { const contents = (webContents as any).create({ nodeIntegration: true }); contents.once('crashed', () => { contents.destroy(); done(); }); contents.loadURL('about:blank').then(() => contents.forcefullyCrashRenderer()); }); }); describe('context-menu event', () => { afterEach(closeAllWindows); it('emits when right-clicked in page', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const promise = emittedOnce(w.webContents, 'context-menu'); // Simulate right-click to create context-menu event. const opts = { x: 0, y: 0, button: 'right' as any }; w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' }); w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' }); const [, params] = await promise; expect(params.pageURL).to.equal(w.webContents.getURL()); expect(params.frame).to.be.an('object'); expect(params.x).to.be.a('number'); expect(params.y).to.be.a('number'); }); }); it('emits a cancelable event before creating a child webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); w.webContents.on('-will-add-new-contents' as any, (event: any, url: any) => { expect(url).to.equal('about:blank'); event.preventDefault(); }); let wasCalled = false; w.webContents.on('new-window' as any, () => { wasCalled = true; }); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('window.open(\'about:blank\')'); await new Promise((resolve) => { process.nextTick(resolve); }); expect(wasCalled).to.equal(false); await closeAllWindows(); }); });
closed
electron/electron
https://github.com/electron/electron
35,046
[Bug]: webContents.getUserAgent() is empty since 20.0.0-alpha.6
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.0-alpha.6 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version 20.0.0-alpha.5 ### Expected Behavior `webContents.getUserAgent()` returns a string with a user Agent ### Actual Behavior webContents.getUserAgent() returns an empty string ### Testcase Gist URL https://gist.github.com/33fd4a9ac6db6b28b1dcc5b765edb622 ### Additional Information In the console the user agent is printed in alpha.5, but empty in alpha.6. Looking at the diff between alpha.5 and alpha.6, this PR seems the likely cause: https://github.com/electron/electron/pull/34524 / #34481 It's worth noting that the renderer does have a filled-in userAgent.
https://github.com/electron/electron/issues/35046
https://github.com/electron/electron/pull/35069
8004cb8722c8d52f4cd553bbaea86750149e8ca4
9028bb79a85fedf64230c2f1c6a29ab072c98c20
2022-07-25T14:12:09Z
c++
2022-07-29T15:09:47Z
shell/browser/api/electron_api_web_contents.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_web_contents.h" #include <limits> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/containers/id_map.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/no_destructor.h" #include "base/strings/utf_string_conversions.h" #include "base/task/current_thread.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/views/eye_dropper/eye_dropper.h" #include "chrome/common/pref_names.h" #include "components/embedder_support/user_agent_utils.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/security_state/content/content_utils.h" #include "components/security_state/core/security_state.h" #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck #include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/context_menu_params.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/desktop_streams_registry.h" #include "content/public/browser/download_request_utils.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/service_worker_context.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/referrer_type_converters.h" #include "content/public/common/webplugininfo.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/arguments.h" #include "gin/data_object_builder.h" #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/system/platform_handle.h" #include "ppapi/buildflags/buildflags.h" #include "printing/buildflags/buildflags.h" #include "printing/print_job_constants.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "shell/browser/api/electron_api_browser_window.h" #include "shell/browser/api/electron_api_debugger.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/api/electron_api_web_frame_main.h" #include "shell/browser/api/message_port.h" #include "shell/browser/browser.h" #include "shell/browser/child_web_contents_tracker.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_javascript_dialog_manager.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/file_select_helper.h" #include "shell/browser/native_window.h" #include "shell/browser/session_preferences.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_contents_zoom_controller.h" #include "shell/browser/web_view_guest_delegate.h" #include "shell/browser/web_view_manager.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/color_util.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/base_converter.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/content_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/net_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/language_util.h" #include "shell/common/mouse_util.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "shell/common/v8_value_serializer.h" #include "storage/browser/file_system/isolated_context.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "third_party/blink/public/mojom/frame/find_in_page.mojom.h" #include "third_party/blink/public/mojom/frame/fullscreen.mojom.h" #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" #include "third_party/blink/public/mojom/renderer_preferences.mojom.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/display/screen.h" #include "ui/events/base_event_utils.h" #if BUILDFLAG(ENABLE_OSR) #include "shell/browser/osr/osr_render_widget_host_view.h" #include "shell/browser/osr/osr_web_contents_view.h" #endif #if !BUILDFLAG(IS_MAC) #include "ui/aura/window.h" #else #include "ui/base/cocoa/defaults_utils.h" #endif #if BUILDFLAG(IS_LINUX) #include "ui/linux/linux_ui.h" #endif #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) #include "ui/gfx/font_render_params.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/script_executor.h" #include "extensions/browser/view_type_utils.h" #include "extensions/common/mojom/view_type.mojom.h" #include "shell/browser/extensions/electron_extension_web_contents_observer.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "chrome/browser/printing/print_view_manager_base.h" #include "components/printing/browser/print_manager_utils.h" #include "components/printing/browser/print_to_pdf/pdf_print_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" // nogncheck #include "printing/page_range.h" #include "shell/browser/printing/print_view_manager_electron.h" #if BUILDFLAG(IS_WIN) #include "printing/backend/win_helper.h" #endif #endif #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h" #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck #include "shell/browser/electron_pdf_web_contents_helper_client.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #endif #ifndef MAS_BUILD #include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck #endif namespace gin { #if BUILDFLAG(ENABLE_PRINTING) template <> struct Converter<printing::mojom::MarginType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::MarginType* out) { std::string type; if (ConvertFromV8(isolate, val, &type)) { if (type == "default") { *out = printing::mojom::MarginType::kDefaultMargins; return true; } if (type == "none") { *out = printing::mojom::MarginType::kNoMargins; return true; } if (type == "printableArea") { *out = printing::mojom::MarginType::kPrintableAreaMargins; return true; } if (type == "custom") { *out = printing::mojom::MarginType::kCustomMargins; return true; } } return false; } }; template <> struct Converter<printing::mojom::DuplexMode> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::DuplexMode* out) { std::string mode; if (ConvertFromV8(isolate, val, &mode)) { if (mode == "simplex") { *out = printing::mojom::DuplexMode::kSimplex; return true; } if (mode == "longEdge") { *out = printing::mojom::DuplexMode::kLongEdge; return true; } if (mode == "shortEdge") { *out = printing::mojom::DuplexMode::kShortEdge; return true; } } return false; } }; #endif template <> struct Converter<WindowOpenDisposition> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, WindowOpenDisposition val) { std::string disposition = "other"; switch (val) { case WindowOpenDisposition::CURRENT_TAB: disposition = "default"; break; case WindowOpenDisposition::NEW_FOREGROUND_TAB: disposition = "foreground-tab"; break; case WindowOpenDisposition::NEW_BACKGROUND_TAB: disposition = "background-tab"; break; case WindowOpenDisposition::NEW_POPUP: case WindowOpenDisposition::NEW_WINDOW: disposition = "new-window"; break; case WindowOpenDisposition::SAVE_TO_DISK: disposition = "save-to-disk"; break; default: break; } return gin::ConvertToV8(isolate, disposition); } }; template <> struct Converter<content::SavePageType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, content::SavePageType* out) { std::string save_type; if (!ConvertFromV8(isolate, val, &save_type)) return false; save_type = base::ToLowerASCII(save_type); if (save_type == "htmlonly") { *out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML; } else if (save_type == "htmlcomplete") { *out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML; } else if (save_type == "mhtml") { *out = content::SAVE_PAGE_TYPE_AS_MHTML; } else { return false; } return true; } }; template <> struct Converter<electron::api::WebContents::Type> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, electron::api::WebContents::Type val) { using Type = electron::api::WebContents::Type; std::string type; switch (val) { case Type::kBackgroundPage: type = "backgroundPage"; break; case Type::kBrowserWindow: type = "window"; break; case Type::kBrowserView: type = "browserView"; break; case Type::kRemote: type = "remote"; break; case Type::kWebView: type = "webview"; break; case Type::kOffScreen: type = "offscreen"; break; default: break; } return gin::ConvertToV8(isolate, type); } static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, electron::api::WebContents::Type* out) { using Type = electron::api::WebContents::Type; std::string type; if (!ConvertFromV8(isolate, val, &type)) return false; if (type == "backgroundPage") { *out = Type::kBackgroundPage; } else if (type == "browserView") { *out = Type::kBrowserView; } else if (type == "webview") { *out = Type::kWebView; #if BUILDFLAG(ENABLE_OSR) } else if (type == "offscreen") { *out = Type::kOffScreen; #endif } else { return false; } return true; } }; template <> struct Converter<scoped_refptr<content::DevToolsAgentHost>> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const scoped_refptr<content::DevToolsAgentHost>& val) { gin_helper::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("id", val->GetId()); dict.Set("url", val->GetURL().spec()); return dict.GetHandle(); } }; } // namespace gin namespace electron::api { namespace { base::IDMap<WebContents*>& GetAllWebContents() { static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents; return *s_all_web_contents; } // Called when CapturePage is done. void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); } absl::optional<base::TimeDelta> GetCursorBlinkInterval() { #if BUILDFLAG(IS_MAC) absl::optional<base::TimeDelta> system_value( ui::TextInsertionCaretBlinkPeriodFromDefaults()); if (system_value) return *system_value; #elif BUILDFLAG(IS_LINUX) if (auto* linux_ui = ui::LinuxUi::instance()) return linux_ui->GetCursorBlinkInterval(); #elif BUILDFLAG(IS_WIN) const auto system_msec = ::GetCaretBlinkTime(); if (system_msec != 0) { return (system_msec == INFINITE) ? base::TimeDelta() : base::Milliseconds(system_msec); } #endif return absl::nullopt; } #if BUILDFLAG(ENABLE_PRINTING) // This will return false if no printer with the provided device_name can be // found on the network. We need to check this because Chromium does not do // sanity checking of device_name validity and so will crash on invalid names. bool IsDeviceNameValid(const std::u16string& device_name) { #if BUILDFLAG(IS_MAC) base::ScopedCFTypeRef<CFStringRef> new_printer_id( base::SysUTF16ToCFStringRef(device_name)); PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get()); bool printer_exists = new_printer != nullptr; PMRelease(new_printer); return printer_exists; #else scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name)); #endif } // This function returns a validated device name. // If the user passed one to webContents.print(), we check that it's valid and // return it or fail if the network doesn't recognize it. If the user didn't // pass a device name, we first try to return the system default printer. If one // isn't set, then pull all the printers and use the first one or fail if none // exist. std::pair<std::string, std::u16string> GetDeviceNameToUse( const std::u16string& device_name) { #if BUILDFLAG(IS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ThreadRestrictions::ScopedAllowIO allow_io; #endif if (!device_name.empty()) { if (!IsDeviceNameValid(device_name)) return std::make_pair("Invalid deviceName provided", std::u16string()); return std::make_pair(std::string(), device_name); } scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); std::string printer_name; printing::mojom::ResultCode code = print_backend->GetDefaultPrinterName(printer_name); // We don't want to return if this fails since some devices won't have a // default printer. if (code != printing::mojom::ResultCode::kSuccess) LOG(ERROR) << "Failed to get default printer name"; if (printer_name.empty()) { printing::PrinterList printers; if (print_backend->EnumeratePrinters(printers) != printing::mojom::ResultCode::kSuccess) return std::make_pair("Failed to enumerate printers", std::u16string()); if (printers.empty()) return std::make_pair("No printers available on the network", std::u16string()); printer_name = printers.front().printer_name; } return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name)); } // Copied from // chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54 scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() { // USER_VISIBLE because the result is displayed in the print preview dialog. #if !BUILDFLAG(IS_WIN) static constexpr base::TaskTraits kTraits = { base::MayBlock(), base::TaskPriority::USER_VISIBLE}; #endif #if defined(USE_CUPS) // CUPS is thread safe. return base::ThreadPool::CreateTaskRunner(kTraits); #elif BUILDFLAG(IS_WIN) // Windows drivers are likely not thread-safe and need to be accessed on the // UI thread. return content::GetUIThreadTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); #else // Be conservative on unsupported platforms. return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits); #endif } #endif struct UserDataLink : public base::SupportsUserData::Data { explicit UserDataLink(base::WeakPtr<WebContents> contents) : web_contents(contents) {} base::WeakPtr<WebContents> web_contents; }; const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey; const char kRootName[] = "<root>"; struct FileSystem { FileSystem() = default; FileSystem(const std::string& type, const std::string& file_system_name, const std::string& root_url, const std::string& file_system_path) : type(type), file_system_name(file_system_name), root_url(root_url), file_system_path(file_system_path) {} std::string type; std::string file_system_name; std::string root_url; std::string file_system_path; }; std::string RegisterFileSystem(content::WebContents* web_contents, const base::FilePath& path) { auto* isolated_context = storage::IsolatedContext::GetInstance(); std::string root_name(kRootName); storage::IsolatedContext::ScopedFSHandle file_system = isolated_context->RegisterFileSystemForPath( storage::kFileSystemTypeLocal, std::string(), path, &root_name); content::ChildProcessSecurityPolicy* policy = content::ChildProcessSecurityPolicy::GetInstance(); content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost(); int renderer_id = render_view_host->GetProcess()->GetID(); policy->GrantReadFileSystem(renderer_id, file_system.id()); policy->GrantWriteFileSystem(renderer_id, file_system.id()); policy->GrantCreateFileForFileSystem(renderer_id, file_system.id()); policy->GrantDeleteFromFileSystem(renderer_id, file_system.id()); if (!policy->CanReadFile(renderer_id, path)) policy->GrantReadFile(renderer_id, path); return file_system.id(); } FileSystem CreateFileSystemStruct(content::WebContents* web_contents, const std::string& file_system_id, const std::string& file_system_path, const std::string& type) { const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL(); std::string file_system_name = storage::GetIsolatedFileSystemName(origin, file_system_id); std::string root_url = storage::GetIsolatedFileSystemRootURIString( origin, file_system_id, kRootName); return FileSystem(type, file_system_name, root_url, file_system_path); } base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) { base::Value::Dict value; value.Set("type", file_system.type); value.Set("fileSystemName", file_system.file_system_name); value.Set("rootURL", file_system.root_url); value.Set("fileSystemPath", file_system.file_system_path); return value; } void WriteToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::WriteFile(path, content.data(), content.size()); } void AppendToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::AppendToFile(path, content); } PrefService* GetPrefService(content::WebContents* web_contents) { auto* context = web_contents->GetBrowserContext(); return static_cast<electron::ElectronBrowserContext*>(context)->prefs(); } std::map<std::string, std::string> GetAddedFileSystemPaths( content::WebContents* web_contents) { auto* pref_service = GetPrefService(web_contents); const base::Value* file_system_paths_value = pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; if (file_system_paths_value) { const base::DictionaryValue* file_system_paths_dict; file_system_paths_value->GetAsDictionary(&file_system_paths_dict); for (auto it : file_system_paths_dict->DictItems()) { std::string type = it.second.is_string() ? it.second.GetString() : std::string(); result[it.first] = type; } } return result; } bool IsDevToolsFileSystemAdded(content::WebContents* web_contents, const std::string& file_system_path) { auto file_system_paths = GetAddedFileSystemPaths(web_contents); return file_system_paths.find(file_system_path) != file_system_paths.end(); } void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } } // namespace #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) { switch (view_type) { case extensions::mojom::ViewType::kExtensionBackgroundPage: return WebContents::Type::kBackgroundPage; case extensions::mojom::ViewType::kAppWindow: case extensions::mojom::ViewType::kComponent: case extensions::mojom::ViewType::kExtensionDialog: case extensions::mojom::ViewType::kExtensionPopup: case extensions::mojom::ViewType::kBackgroundContents: case extensions::mojom::ViewType::kExtensionGuest: case extensions::mojom::ViewType::kTabContents: case extensions::mojom::ViewType::kOffscreenDocument: case extensions::mojom::ViewType::kInvalid: return WebContents::Type::kRemote; } } #endif WebContents::WebContents(v8::Isolate* isolate, content::WebContents* web_contents) : content::WebContentsObserver(web_contents), type_(Type::kRemote), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // WebContents created by extension host will have valid ViewType set. extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents); if (view_type != extensions::mojom::ViewType::kInvalid) { InitWithExtensionView(isolate, web_contents, view_type); } extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents); #endif auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); absl::optional<std::string> user_agent_override = GetBrowserContext()->GetUserAgentOverride(); if (user_agent_override) SetUserAgent(*user_agent_override); web_contents->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) : content::WebContentsObserver(web_contents.get()), type_(type), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { DCHECK(type != Type::kRemote) << "Can't take ownership of a remote WebContents"; auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); InitWithSessionAndOptions(isolate, std::move(web_contents), session, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options) : id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { // Read options. options.Get("backgroundThrottling", &background_throttling_); // Get type options.Get("type", &type_); #if BUILDFLAG(ENABLE_OSR) bool b = false; if (options.Get(options::kOffscreen, &b) && b) type_ = Type::kOffScreen; #endif // Init embedder earlier options.Get("embedder", &embedder_); // Whether to enable DevTools. options.Get("devTools", &enable_devtools_); // BrowserViews are not attached to a window initially so they should start // off as hidden. This is also important for compositor recycling. See: // https://github.com/electron/electron/pull/21372 bool initially_shown = type_ != Type::kBrowserView; options.Get(options::kShow, &initially_shown); // Obtain the session. std::string partition; gin::Handle<api::Session> session; if (options.Get("session", &session) && !session.IsEmpty()) { } else if (options.Get("partition", &partition)) { session = Session::FromPartition(isolate, partition); } else { // Use the default session if not specified. session = Session::FromPartition(isolate, ""); } session_.Reset(isolate, session.ToV8()); std::unique_ptr<content::WebContents> web_contents; if (IsGuest()) { scoped_refptr<content::SiteInstance> site_instance = content::SiteInstance::CreateForURL(session->browser_context(), GURL("chrome-guest://fake-host")); content::WebContents::CreateParams params(session->browser_context(), site_instance); guest_delegate_ = std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this); params.guest_delegate = guest_delegate_.get(); #if BUILDFLAG(ENABLE_OSR) if (embedder_ && embedder_->IsOffScreen()) { auto* view = new OffScreenWebContentsView( false, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); } else { #endif web_contents = content::WebContents::Create(params); #if BUILDFLAG(ENABLE_OSR) } } else if (IsOffScreen()) { // webPreferences does not have a transparent option, so if the window needs // to be transparent, that will be set at electron_api_browser_window.cc#L57 // and we then need to pull it back out and check it here. std::string background_color; options.GetHidden(options::kBackgroundColor, &background_color); bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT; content::WebContents::CreateParams params(session->browser_context()); auto* view = new OffScreenWebContentsView( transparent, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); #endif } else { content::WebContents::CreateParams params(session->browser_context()); params.initially_hidden = !initially_shown; web_contents = content::WebContents::Create(params); } InitWithSessionAndOptions(isolate, std::move(web_contents), session, options); } void WebContents::InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options) { WebContentsZoomController::CreateForWebContents(web_contents); zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents); double zoom_factor; if (options.Get(options::kZoomFactor, &zoom_factor)) zoom_controller_->SetDefaultZoomFactor(zoom_factor); } void WebContents::InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> owned_web_contents, gin::Handle<api::Session> session, const gin_helper::Dictionary& options) { Observe(owned_web_contents.get()); InitWithWebContents(std::move(owned_web_contents), session->browser_context(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); auto* prefs = web_contents()->GetMutableRendererPrefs(); // Collect preferred languages from OS and browser process. accept_languages // effects HTTP header, navigator.languages, and CJK fallback font selection. // // Note that an application locale set to the browser process might be // different with the one set to the preference list. // (e.g. overridden with --lang) std::string accept_languages = g_browser_process->GetApplicationLocale() + ","; for (auto const& language : electron::GetPreferredLanguages()) { if (language == g_browser_process->GetApplicationLocale()) continue; accept_languages += language + ","; } accept_languages.pop_back(); prefs->accept_languages = accept_languages; #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) // Update font settings. static const gfx::FontRenderParams params( gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr)); prefs->should_antialias_text = params.antialiasing; prefs->use_subpixel_positioning = params.subpixel_positioning; prefs->hinting = params.hinting; prefs->use_autohinter = params.autohinter; prefs->use_bitmaps = params.use_bitmaps; prefs->subpixel_rendering = params.subpixel_rendering; #endif // Honor the system's cursor blink rate settings if (auto interval = GetCursorBlinkInterval()) prefs->caret_blink_interval = *interval; // Save the preferences in C++. // If there's already a WebContentsPreferences object, we created it as part // of the webContents.setWindowOpenHandler path, so don't overwrite it. if (!WebContentsPreferences::From(web_contents())) { new WebContentsPreferences(web_contents(), options); } // Trigger re-calculation of webkit prefs. web_contents()->NotifyPreferencesChanged(); WebContentsPermissionHelper::CreateForWebContents(web_contents()); InitZoomController(web_contents(), options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents()); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents()); #endif AutofillDriverFactory::CreateForWebContents(web_contents()); absl::optional<std::string> user_agent_override = GetBrowserContext()->GetUserAgentOverride(); if (user_agent_override) SetUserAgent(*user_agent_override); if (IsGuest()) { NativeWindow* owner_window = nullptr; if (embedder_) { // New WebContents's owner_window is the embedder's owner_window. auto* relay = NativeWindowRelay::FromWebContents(embedder_->web_contents()); if (relay) owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); } web_contents()->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void WebContents::InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::mojom::ViewType view_type) { // Must reassign type prior to calling `Init`. type_ = GetTypeFromViewType(view_type); if (type_ == Type::kRemote) return; if (type_ == Type::kBackgroundPage) // non-background-page WebContents are retained by other classes. We need // to pin here to prevent background-page WebContents from being GC'd. // The background page api::WebContents will live until the underlying // content::WebContents is destroyed. Pin(isolate); // Allow toggling DevTools for background pages Observe(web_contents); InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents), GetBrowserContext(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); } #endif void WebContents::InitWithWebContents( std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest) { browser_context_ = browser_context; web_contents->SetDelegate(this); #if BUILDFLAG(ENABLE_PRINTING) PrintViewManagerElectron::CreateForWebContents(web_contents.get()); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) pdf::PDFWebContentsHelper::CreateForWebContentsWithClient( web_contents.get(), std::make_unique<ElectronPDFWebContentsHelperClient>()); #endif // Determine whether the WebContents is offscreen. auto* web_preferences = WebContentsPreferences::From(web_contents.get()); offscreen_ = web_preferences && web_preferences->IsOffscreen(); // Create InspectableWebContents. inspectable_web_contents_ = std::make_unique<InspectableWebContents>( std::move(web_contents), browser_context->prefs(), is_guest); inspectable_web_contents_->SetDelegate(this); } WebContents::~WebContents() { if (!inspectable_web_contents_) { WebContentsDestroyed(); return; } inspectable_web_contents_->GetView()->SetDelegate(nullptr); // This event is only for internal use, which is emitted when WebContents is // being destroyed. Emit("will-destroy"); // For guest view based on OOPIF, the WebContents is released by the embedder // frame, and we need to clear the reference to the memory. bool not_owned_by_this = IsGuest() && attached_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // And background pages are owned by extensions::ExtensionHost. if (type_ == Type::kBackgroundPage) not_owned_by_this = true; #endif if (not_owned_by_this) { inspectable_web_contents_->ReleaseWebContents(); WebContentsDestroyed(); } // InspectableWebContents will be automatically destroyed. } void WebContents::DeleteThisIfAlive() { // It is possible that the FirstWeakCallback has been called but the // SecondWeakCallback has not, in this case the garbage collection of // WebContents has already started and we should not |delete this|. // Calling |GetWrapper| can detect this corner case. auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; delete this; } void WebContents::Destroy() { // The content::WebContents should be destroyed asynchronously when possible // as user may choose to destroy WebContents during an event of it. if (Browser::Get()->is_shutting_down() || IsGuest()) { DeleteThisIfAlive(); } else { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce( [](base::WeakPtr<WebContents> contents) { if (contents) contents->DeleteThisIfAlive(); }, GetWeakPtr())); } } bool WebContents::DidAddMessageToConsole( content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) { return Emit("console-message", static_cast<int32_t>(level), message, line_no, source_id); } void WebContents::OnCreateWindow( const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const std::string& features, const scoped_refptr<network::ResourceRequestBody>& body) { Emit("-new-window", target_url, frame_name, disposition, features, referrer, body); } void WebContents::WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) { ChildWebContentsTracker::CreateForWebContents(new_contents); auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents); tracker->url = params.target_url; tracker->frame_name = params.frame_name; tracker->referrer = params.referrer.To<content::Referrer>(); tracker->raw_features = params.raw_features; tracker->body = params.body; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary dict; gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate), &dict); pending_child_web_preferences_.Reset(); // Associate the preferences passed in via `setWindowOpenHandler` with the // content::WebContents that was just created for the child window. These // preferences will be picked up by the RenderWidgetHost via its call to the // delegate's OverrideWebkitPrefs. new WebContentsPreferences(new_contents, dict); } bool WebContents::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) { bool default_prevented = Emit( "-will-add-new-contents", params.target_url, params.frame_name, params.raw_features, params.disposition, *params.referrer, params.body); // If the app prevented the default, redirect to CreateCustomWebContents, // which always returns nullptr, which will result in the window open being // prevented (window.open() will return null in the renderer). return default_prevented; } void WebContents::SetNextChildWebPreferences( const gin_helper::Dictionary preferences) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); // Store these prefs for when Chrome calls WebContentsCreatedWithFullParams // with the new child contents. pending_child_web_preferences_.Reset(isolate, preferences.GetHandle()); } content::WebContents* WebContents::CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionConfig& partition_config, content::SessionStorageNamespace* session_storage_namespace) { return nullptr; } void WebContents::AddNewContents( content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, 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, initial_rect.x(), initial_rect.y(), initial_rect.width(), initial_rect.height(), tracker->url, tracker->frame_name, tracker->referrer, tracker->raw_features, tracker->body)) { api_web_contents->Destroy(); } } content::WebContents* WebContents::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { auto weak_this = GetWeakPtr(); if (params.disposition != WindowOpenDisposition::CURRENT_TAB) { Emit("-new-window", params.url, "", params.disposition, "", params.referrer, params.post_data); return nullptr; } if (!weak_this || !web_contents()) return nullptr; content::NavigationController::LoadURLParams load_url_params(params.url); load_url_params.referrer = params.referrer; load_url_params.transition_type = params.transition; load_url_params.extra_headers = params.extra_headers; load_url_params.should_replace_current_entry = params.should_replace_current_entry; load_url_params.is_renderer_initiated = params.is_renderer_initiated; load_url_params.started_from_context_menu = params.started_from_context_menu; load_url_params.initiator_origin = params.initiator_origin; load_url_params.source_site_instance = params.source_site_instance; load_url_params.frame_tree_node_id = params.frame_tree_node_id; load_url_params.redirect_chain = params.redirect_chain; load_url_params.has_user_gesture = params.user_gesture; load_url_params.blob_url_loader_factory = params.blob_url_loader_factory; load_url_params.href_translate = params.href_translate; load_url_params.reload_type = params.reload_type; if (params.post_data) { load_url_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; load_url_params.post_data = params.post_data; } source->GetController().LoadURLWithParams(load_url_params); return source; } void WebContents::BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen || type_ == Type::kBrowserView) *proceed_to_fire_unload = proceed; else *proceed_to_fire_unload = true; // Note that Chromium does not emit this for navigations. Emit("before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnSetContentBounds(rect); } void WebContents::CloseContents(content::WebContents* source) { Emit("close"); auto* autofill_driver_factory = AutofillDriverFactory::FromWebContents(web_contents()); if (autofill_driver_factory) { autofill_driver_factory->CloseAllPopups(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); } void WebContents::ActivateContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnActivateContents(); } void WebContents::UpdateTargetURL(content::WebContents* source, const GURL& url) { Emit("update-target-url", url); } bool WebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (type_ == Type::kWebView && embedder_) { // Send the unhandled keyboard events back to the embedder. return embedder_->HandleKeyboardEvent(source, event); } else { return PlatformHandleKeyboardEvent(source, event); } } #if !BUILDFLAG(IS_MAC) // NOTE: The macOS version of this function is found in // electron_api_web_contents_mac.mm, as it requires calling into objective-C // code. bool WebContents::PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { // Escape exits tabbed fullscreen mode. if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { ExitFullscreenModeForTab(source); return true; } // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts()) return false; // Let the NativeWindow handle other parts. if (owner_window()) { owner_window()->HandleKeyboardEvent(source, event); return true; } return false; } #endif content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (exclusive_access_manager_->HandleUserKeyEvent(event)) return content::KeyboardEventProcessingResult::HANDLED; if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kKeyUp) { bool prevent_default = Emit("before-input-event", event); if (prevent_default) { return content::KeyboardEventProcessingResult::HANDLED; } } return content::KeyboardEventProcessingResult::NOT_HANDLED; } void WebContents::ContentsZoomChange(bool zoom_in) { Emit("zoom-changed", zoom_in ? "in" : "out"); } Profile* WebContents::GetProfile() { return nullptr; } bool WebContents::IsFullscreen() const { return owner_window_ && owner_window_->IsFullscreen(); } void WebContents::EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) {} void WebContents::ExitFullscreen() {} void WebContents::UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool 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(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; } exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); SetHtmlApiFullscreen(true); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { if (!owner_window_) return; // This needs to be called before we exit fullscreen on the native window, // or the controller will incorrectly think we weren't fullscreen and bail. exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab( source); SetHtmlApiFullscreen(false); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. Chrome does this indirectly from // `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) { Emit("unresponsive"); } void WebContents::RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) { Emit("responsive"); } bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) { Emit("context-menu", std::make_pair(params, &render_frame_host)); return true; } bool WebContents::OnGoToEntryOffset(int offset) { GoToOffset(offset); return false; } void WebContents::FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { if (!final_update) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate); result.Set("requestId", request_id); result.Set("matches", number_of_matches); result.Set("selectionArea", selection_rect); result.Set("activeMatchOrdinal", active_match_ordinal); result.Set("finalUpdate", final_update); // Deprecate after 2.0 Emit("found-in-page", result.GetHandle()); } void WebContents::RequestExclusivePointerAccess( content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed) { if (allowed) { exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse( web_contents, user_gesture, last_unlocked_by_target); } else { web_contents->GotResponseToLockMouseRequest( blink::mojom::PointerLockResult::kPermissionDenied); } } void WebContents::RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestPointerLockPermission( user_gesture, last_unlocked_by_target, base::BindOnce(&WebContents::RequestExclusivePointerAccess, base::Unretained(this))); } void WebContents::LostMouseLock() { exclusive_access_manager_->mouse_lock_controller()->LostMouseLock(); } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } void WebContents::CancelKeyboardLockRequest( content::WebContents* web_contents) { exclusive_access_manager_->keyboard_lock_controller() ->CancelKeyboardLockRequest(web_contents); } bool WebContents::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckMediaAccessPermission(security_origin, type); } void WebContents::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestMediaAccessPermission(request, std::move(callback)); } content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { if (!dialog_manager_) dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>(); return dialog_manager_.get(); } void WebContents::OnAudioStateChanged(bool audible) { Emit("-audio-state-changed", audible); } void WebContents::BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) { // Do nothing, we override this method just to avoid compilation error since // there are two virtual functions named BeforeUnloadFired. } void WebContents::HandleNewRenderFrame( content::RenderFrameHost* render_frame_host) { auto* rwhv = render_frame_host->GetView(); if (!rwhv) return; // Set the background color of RenderWidgetHostView. auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences) { absl::optional<SkColor> maybe_color = web_preferences->GetBackgroundColor(); web_contents()->SetPageBaseBackgroundColor(maybe_color); bool guest = IsGuest() || type_ == Type::kBrowserView; SkColor color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); SetBackgroundColor(rwhv, color); } if (!background_throttling_) render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false); auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (rwh_impl) rwh_impl->disable_hidden_ = !background_throttling_; auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->MaybeSetupMojoConnection(); } void WebContents::OnBackgroundColorChanged() { absl::optional<SkColor> color = web_contents()->GetBackgroundColor(); if (color.has_value()) { auto* const view = web_contents()->GetRenderWidgetHostView(); static_cast<content::RenderWidgetHostViewBase*>(view) ->SetContentBackgroundColor(color.value()); } } void WebContents::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { HandleNewRenderFrame(render_frame_host); // RenderFrameCreated is called for speculative frames which may not be // used in certain cross-origin navigations. Invoking // RenderFrameHost::GetLifecycleState currently crashes when called for // speculative frames so we need to filter it out for now. Check // https://crbug.com/1183639 for details on when this can be removed. auto* rfh_impl = static_cast<content::RenderFrameHostImpl*>(render_frame_host); if (rfh_impl->lifecycle_state() == content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) { return; } content::RenderFrameHost::LifecycleState lifecycle_state = render_frame_host->GetLifecycleState(); if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.SetGetter("frame", render_frame_host); Emit("frame-created", details); } } void WebContents::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { // A RenderFrameHost can be deleted when: // - A WebContents is removed and its containing frames are disposed. // - An <iframe> is removed from the DOM. // - Cross-origin navigation creates a new RFH in a separate process which // is swapped by content::RenderFrameHostManager. // // WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID // to find an existing instance of WebFrameMain. During a cross-origin // navigation, the deleted RFH will be the old host which was swapped out. In // this special case, we need to also ensure that WebFrameMain's internal RFH // matches before marking it as disposed. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame && web_frame->render_frame_host() == render_frame_host) web_frame->MarkRenderFrameDisposed(); } void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { // During cross-origin navigation, a FrameTreeNode will swap out its RFH. // If an instance of WebFrameMain exists, it will need to have its RFH // swapped as well. // // |old_host| can be a nullptr so we use |new_host| for looking up the // WebFrameMain instance. auto* web_frame = WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId()); if (web_frame) { web_frame->UpdateRenderFrameHost(new_host); } } void WebContents::FrameDeleted(int frame_tree_node_id) { auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id); if (web_frame) web_frame->Destroyed(); } void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) { // This event is necessary for tracking any states with respect to // intermediate render view hosts aka speculative render view hosts. Currently // used by object-registry.js to ref count remote objects. Emit("render-view-deleted", render_view_host->GetProcess()->GetID()); if (web_contents()->GetRenderViewHost() == render_view_host) { // When the RVH that has been deleted is the current RVH it means that the // the web contents are being closed. This is communicated by this event. // Currently tracked by guest-window-manager.ts to destroy the // BrowserWindow. Emit("current-render-view-deleted", render_view_host->GetProcess()->GetID()); } } void WebContents::PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) { auto weak_this = GetWeakPtr(); Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED); // User might destroy WebContents in the crashed event. if (!weak_this || !web_contents()) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.Set("reason", status); details.Set("exitCode", web_contents()->GetCrashedErrorCode()); Emit("render-process-gone", details); } void WebContents::PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) { #if BUILDFLAG(ENABLE_PLUGINS) content::WebPluginInfo info; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->GetPluginInfoByPath(plugin_path, &info); Emit("plugin-crashed", info.name, info.version); #endif // BUILDFLAG(ENABLE_PLUGINS) } void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) { Emit("media-started-playing"); } void WebContents::MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) { Emit("media-paused"); } void WebContents::DidChangeThemeColor() { auto theme_color = web_contents()->GetThemeColor(); if (theme_color) { Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value())); } else { Emit("did-change-theme-color", nullptr); } } void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) { set_fullscreen_frame(rfh); } void WebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { Emit("focus"); } void WebContents::OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) { Emit("blur"); } void WebContents::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->DOMContentLoaded(); if (!render_frame_host->GetParent()) Emit("dom-ready"); } void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); auto weak_this = GetWeakPtr(); Emit("did-frame-finish-load", is_main_frame, frame_process_id, frame_routing_id); // ⚠️WARNING!⚠️ // Emit() triggers JS which can call destroy() on |this|. It's not safe to // assume that |this| points to valid memory at this point. if (is_main_frame && weak_this && web_contents()) Emit("did-finish-load"); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& url, int error_code) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::DidStartLoading() { Emit("did-start-loading"); } void WebContents::DidStopLoading() { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences && web_preferences->ShouldUsePreferredSizeMode()) web_contents()->GetRenderViewHost()->EnablePreferredSizeMode(); Emit("did-stop-loading"); } bool WebContents::EmitNavigationEvent( const std::string& event, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId(); content::FrameTreeNode* frame_tree_node = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id); content::RenderFrameHostManager* render_manager = frame_tree_node->render_manager(); content::RenderFrameHost* frame_host = nullptr; if (render_manager) { frame_host = render_manager->speculative_frame_host(); if (!frame_host) frame_host = render_manager->current_frame_host(); } int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } bool is_same_document = navigation_handle->IsSameDocument(); auto url = navigation_handle->GetURL(); return Emit(event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Message", "channel", channel); // webContents.emit('-ipc-message', new Event(), internal, channel, // arguments); EmitWithSender("-ipc-message", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), internal, channel, std::move(arguments)); } void WebContents::Invoke( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::InvokeCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel); // webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments); EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::OnFirstNonEmptyLayout( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents()->GetPrimaryMainFrame()) { Emit("ready-to-show"); } } void WebContents::ReceivePostMessage( const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto wrapped_ports = MessagePort::EntanglePorts(isolate, std::move(message.ports)); v8::Local<v8::Value> message_value = electron::DeserializeV8Value(isolate, message); EmitWithSender("-ipc-ports", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), false, channel, message_value, std::move(wrapped_ports)); } void WebContents::MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel); // webContents.emit('-ipc-message-sync', new Event(sender, message), internal, // channel, arguments); EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments) { TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel); auto* target_web_contents = FromID(web_contents_id); if (target_web_contents) { content::RenderFrameHost* frame = target_web_contents->MainFrame(); DCHECK(frame); v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate()); gin::Handle<WebFrameMain> web_frame_main = WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame); if (!web_frame_main->CheckRenderFrame()) return; int32_t sender_id = ID(); web_frame_main->GetRendererApi()->Message(false /* internal */, channel, std::move(arguments), sender_id); } } void WebContents::MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel); // webContents.emit('ipc-message-host', new Event(), channel, args); EmitWithSender("ipc-message-host", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), channel, std::move(arguments)); } void WebContents::UpdateDraggableRegions( std::vector<mojom::DraggableRegionPtr> regions) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDraggableRegionsUpdated(regions); } void WebContents::DidStartNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-start-navigation", navigation_handle); } void WebContents::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-redirect-navigation", navigation_handle); } void WebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { // Don't focus content in an inactive window. if (!owner_window()) return; #if BUILDFLAG(IS_MAC) if (!owner_window()->IsActive()) return; #else if (!owner_window()->widget()->IsActive()) return; #endif // Don't focus content after subframe navigations. if (!navigation_handle->IsInMainFrame()) return; // Only focus for top-level contents. if (type_ != Type::kBrowserWindow) return; web_contents()->SetInitialFocus(); } void WebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (owner_window_) { owner_window_->NotifyLayoutWindowControlsOverlay(); } if (!navigation_handle->HasCommitted()) return; bool is_main_frame = navigation_handle->IsInMainFrame(); content::RenderFrameHost* frame_host = navigation_handle->GetRenderFrameHost(); int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } if (!navigation_handle->IsErrorPage()) { // FIXME: All the Emit() calls below could potentially result in |this| // being destroyed (by JS listening for the event and calling // webContents.destroy()). auto url = navigation_handle->GetURL(); bool is_same_document = navigation_handle->IsSameDocument(); if (is_same_document) { Emit("did-navigate-in-page", url, is_main_frame, frame_process_id, frame_routing_id); } else { const net::HttpResponseHeaders* http_response = navigation_handle->GetResponseHeaders(); std::string http_status_text; int http_response_code = -1; if (http_response) { http_status_text = http_response->GetStatusText(); http_response_code = http_response->response_code(); } Emit("did-frame-navigate", url, http_response_code, http_status_text, is_main_frame, frame_process_id, frame_routing_id); if (is_main_frame) { Emit("did-navigate", url, http_response_code, http_status_text); } } if (IsGuest()) Emit("load-commit", url, is_main_frame); } else { auto url = navigation_handle->GetURL(); int code = navigation_handle->GetNetErrorCode(); auto description = net::ErrorToShortString(code); Emit("did-fail-provisional-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); // Do not emit "did-fail-load" for canceled requests. if (code != net::ERR_ABORTED) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "Failed to load URL: " + url.possibly_invalid_spec() + " with error: " + description, "electron"); Emit("did-fail-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); } } content::NavigationEntry* entry = navigation_handle->GetNavigationEntry(); // This check is needed due to an issue in Chromium // Check the Chromium issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=1178663 // If a history entry has been made and the forward/back call has been made, // proceed with setting the new title if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK)) WebContents::TitleWasSet(entry); } void WebContents::TitleWasSet(content::NavigationEntry* entry) { std::u16string final_title; bool explicit_set = true; if (entry) { auto title = entry->GetTitle(); auto url = entry->GetURL(); if (url.SchemeIsFile() && title.empty()) { final_title = base::UTF8ToUTF16(url.ExtractFileName()); explicit_set = false; } else { final_title = title; } } else { final_title = web_contents()->GetTitle(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnPageTitleUpdated(final_title, explicit_set); Emit("page-title-updated", final_title, explicit_set); } void WebContents::DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) { std::set<GURL> unique_urls; for (const auto& iter : urls) { if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon) continue; const GURL& url = iter->icon_url; if (url.is_valid()) unique_urls.insert(url); } Emit("page-favicon-updated", unique_urls); } void WebContents::DevToolsReloadPage() { Emit("devtools-reload-page"); } void WebContents::DevToolsFocused() { Emit("devtools-focused"); } void WebContents::DevToolsOpened() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); DCHECK(inspectable_web_contents_); DCHECK(inspectable_web_contents_->GetDevToolsWebContents()); auto handle = FromOrCreate( isolate, inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_contents_.Reset(isolate, handle.ToV8()); // Set inspected tabID. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "setInspectedTabId", base::Value(ID())); // Inherit owner window in devtools when it doesn't have one. auto* devtools = inspectable_web_contents_->GetDevToolsWebContents(); bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey()); if (owner_window() && !has_window) handle->SetOwnerWindow(devtools, owner_window()); Emit("devtools-opened"); } void WebContents::DevToolsClosed() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); devtools_web_contents_.Reset(); Emit("devtools-closed"); } void WebContents::DevToolsResized() { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDevToolsResized(); } void WebContents::SetOwnerWindow(NativeWindow* owner_window) { SetOwnerWindow(GetWebContents(), owner_window); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } #if BUILDFLAG(ENABLE_OSR) auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); #endif } content::WebContents* WebContents::GetWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetWebContents(); } content::WebContents* WebContents::GetDevToolsWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetDevToolsWebContents(); } void WebContents::WebContentsDestroyed() { // Clear the pointer stored in wrapper. if (GetAllWebContents().Lookup(id_)) GetAllWebContents().Remove(id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; wrapper->SetAlignedPointerInInternalField(0, nullptr); // Tell WebViewGuestDelegate that the WebContents has been destroyed. if (guest_delegate_) guest_delegate_->WillDestroy(); Observe(nullptr); Emit("destroyed"); } void WebContents::NavigationEntryCommitted( const content::LoadCommittedDetails& details) { Emit("navigation-entry-committed", details.entry->GetURL(), details.is_same_document, details.did_replace_entry); } bool WebContents::GetBackgroundThrottling() const { return background_throttling_; } void WebContents::SetBackgroundThrottling(bool allowed) { background_throttling_ = allowed; auto* rfh = web_contents()->GetPrimaryMainFrame(); if (!rfh) return; auto* rwhv = rfh->GetView(); if (!rwhv) return; auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (!rwh_impl) return; rwh_impl->disable_hidden_ = !background_throttling_; web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed); if (rwh_impl->is_hidden()) { rwh_impl->WasShown({}); } } int WebContents::GetProcessID() const { return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents() ->GetPrimaryMainFrame() ->GetProcess() ->GetProcess() .Handle(); return base::GetProcId(process_handle); } WebContents::Type WebContents::GetType() const { return type_; } bool WebContents::Equal(const WebContents* web_contents) const { return ID() == web_contents->ID(); } GURL WebContents::GetURL() const { return web_contents()->GetLastCommittedURL(); } void WebContents::LoadURL(const GURL& url, const gin_helper::Dictionary& options) { if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) { Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL), net::ErrorToShortString(net::ERR_INVALID_URL), url.possibly_invalid_spec(), true); return; } content::NavigationController::LoadURLParams params(url); if (!options.Get("httpReferrer", &params.referrer)) { GURL http_referrer; if (options.Get("httpReferrer", &http_referrer)) params.referrer = content::Referrer(http_referrer.GetAsReferrer(), network::mojom::ReferrerPolicy::kDefault); } std::string user_agent; if (options.Get("userAgent", &user_agent)) SetUserAgent(user_agent); std::string extra_headers; if (options.Get("extraHeaders", &extra_headers)) params.extra_headers = extra_headers; scoped_refptr<network::ResourceRequestBody> body; if (options.Get("postData", &body)) { params.post_data = body; params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; } GURL base_url_for_data_url; if (options.Get("baseURLForDataURL", &base_url_for_data_url)) { params.base_url_for_data_url = base_url_for_data_url; params.load_type = content::NavigationController::LOAD_TYPE_DATA; } bool reload_ignoring_cache = false; if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) && reload_ignoring_cache) { params.reload_type = content::ReloadType::BYPASSING_CACHE; } // Calling LoadURLWithParams() can trigger JS which destroys |this|. auto weak_this = GetWeakPtr(); params.transition_type = ui::PageTransitionFromInt( ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; // Discard non-committed entries to ensure that we don't re-use a pending // entry web_contents()->GetController().DiscardNonCommittedEntries(); web_contents()->GetController().LoadURLWithParams(params); // ⚠️WARNING!⚠️ // LoadURLWithParams() triggers JS events which can call destroy() on |this|. // It's not safe to assume that |this| points to valid memory at this point. if (!weak_this || !web_contents()) return; // Required to make beforeunload handler work. NotifyUserActivation(); } // TODO(MarshallOfSound): Figure out what we need to do with post data here, I // believe the default behavior when we pass "true" is to phone out to the // delegate and then the controller expects this method to be called again with // "false" if the user approves the reload. For now this would result in // ".reload()" calls on POST data domains failing silently. Passing false would // result in them succeeding, but reposting which although more correct could be // considering a breaking change. void WebContents::Reload() { web_contents()->GetController().Reload(content::ReloadType::NORMAL, /* check_for_repost */ true); } void WebContents::ReloadIgnoringCache() { web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE, /* check_for_repost */ true); } void WebContents::DownloadURL(const GURL& url) { auto* browser_context = web_contents()->GetBrowserContext(); auto* download_manager = browser_context->GetDownloadManager(); std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); download_manager->DownloadUrl(std::move(download_params)); } std::u16string WebContents::GetTitle() const { return web_contents()->GetTitle(); } bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } bool WebContents::IsLoadingMainFrame() const { return web_contents()->ShouldShowLoadingUI(); } bool WebContents::IsWaitingForResponse() const { return web_contents()->IsWaitingForResponse(); } void WebContents::Stop() { web_contents()->Stop(); } bool WebContents::CanGoBack() const { return web_contents()->GetController().CanGoBack(); } void WebContents::GoBack() { if (CanGoBack()) web_contents()->GetController().GoBack(); } bool WebContents::CanGoForward() const { return web_contents()->GetController().CanGoForward(); } void WebContents::GoForward() { if (CanGoForward()) web_contents()->GetController().GoForward(); } bool WebContents::CanGoToOffset(int offset) const { return web_contents()->GetController().CanGoToOffset(offset); } void WebContents::GoToOffset(int offset) { if (CanGoToOffset(offset)) web_contents()->GetController().GoToOffset(offset); } bool WebContents::CanGoToIndex(int index) const { return index >= 0 && index < GetHistoryLength(); } void WebContents::GoToIndex(int index) { if (CanGoToIndex(index)) web_contents()->GetController().GoToIndex(index); } int WebContents::GetActiveIndex() const { return web_contents()->GetController().GetCurrentEntryIndex(); } void WebContents::ClearHistory() { // In some rare cases (normally while there is no real history) we are in a // state where we can't prune navigation entries if (web_contents()->GetController().CanPruneAllButLastCommitted()) { web_contents()->GetController().PruneAllButLastCommitted(); } } int WebContents::GetHistoryLength() const { return web_contents()->GetController().GetEntryCount(); } const std::string WebContents::GetWebRTCIPHandlingPolicy() const { return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy; } void WebContents::SetWebRTCIPHandlingPolicy( const std::string& webrtc_ip_handling_policy) { if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy) return; web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy = webrtc_ip_handling_policy; web_contents()->SyncRendererPrefs(); } std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) return std::string(); content::DesktopMediaID media_id( content::DesktopMediaID::TYPE_WEB_CONTENTS, content::DesktopMediaID::kNullId, content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(), frame_host->GetRoutingID())); auto* request_frame_host = request_web_contents->GetPrimaryMainFrame(); if (!request_frame_host) return std::string(); std::string id = content::DesktopStreamsRegistry::GetInstance()->RegisterStream( request_frame_host->GetProcess()->GetID(), request_frame_host->GetRoutingID(), url::Origin::Create(request_frame_host->GetLastCommittedURL() .DeprecatedGetOriginAsURL()), media_id, "", content::kRegistryStreamTypeTab); return id; } bool WebContents::IsCrashed() const { return web_contents()->IsCrashed(); } void WebContents::ForcefullyCrashRenderer() { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); if (!rwh) return; content::RenderProcessHost* rph = rwh->GetProcess(); if (rph) { #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // A generic |CrashDumpHungChildProcess()| is not implemented for Linux. // Instead we send an explicit IPC to crash on the renderer's IO thread. rph->ForceCrash(); #else // Try to generate a crash report for the hung process. #ifndef MAS_BUILD CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { blink::UserAgentOverride ua_override; ua_override.ua_string_override = user_agent; if (!user_agent.empty()) ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata(); web_contents()->SetUserAgentOverride(ua_override, false); } std::string WebContents::GetUserAgent() { return web_contents()->GetUserAgentOverride().ua_string_override; } v8::Local<v8::Promise> WebContents::SavePage( const base::FilePath& full_file_path, const content::SavePageType& save_type) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (!full_file_path.IsAbsolute()) { promise.RejectWithErrorMessage("Path must be absolute"); return handle; } auto* handler = new SavePageHandler(web_contents(), std::move(promise)); handler->Handle(full_file_path, save_type); return handle; } void WebContents::OpenDevTools(gin::Arguments* args) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; std::string state; if (type_ == Type::kWebView || type_ == Type::kBackgroundPage || !owner_window()) { state = "detach"; } bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->ShowDevTools(activate); } void WebContents::CloseDevTools() { if (type_ == Type::kRemote) return; DCHECK(inspectable_web_contents_); inspectable_web_contents_->CloseDevTools(); } bool WebContents::IsDevToolsOpened() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->IsDevToolsViewShowing(); } bool WebContents::IsDevToolsFocused() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetView()->IsDevToolsViewFocused(); } void WebContents::EnableDeviceEmulation( const blink::DeviceEmulationParams& params) { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->EnableDeviceEmulation(params); } } } void WebContents::DisableDeviceEmulation() { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->DisableDeviceEmulation(); } } } void WebContents::ToggleDevTools() { if (IsDevToolsOpened()) CloseDevTools(); else OpenDevTools(nullptr); } void WebContents::InspectElement(int x, int y) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; DCHECK(inspectable_web_contents_); if (!inspectable_web_contents_->GetDevToolsWebContents()) OpenDevTools(nullptr); inspectable_web_contents_->InspectElement(x, y); } void WebContents::InspectSharedWorkerById(const std::string& workerId) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { if (agent_host->GetId() == workerId) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } } std::vector<scoped_refptr<content::DevToolsAgentHost>> WebContents::GetAllSharedWorkers() { std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers; if (type_ == Type::kRemote) return shared_workers; if (!enable_devtools_) return shared_workers; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { shared_workers.push_back(agent_host); } } return shared_workers; } void WebContents::InspectSharedWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::InspectServiceWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeServiceWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::SetIgnoreMenuShortcuts(bool ignore) { auto* web_preferences = WebContentsPreferences::From(web_contents()); DCHECK(web_preferences); web_preferences->SetIgnoreMenuShortcuts(ignore); } void WebContents::SetAudioMuted(bool muted) { web_contents()->SetAudioMuted(muted); } bool WebContents::IsAudioMuted() { return web_contents()->IsAudioMuted(); } bool WebContents::IsCurrentlyAudible() { return web_contents()->IsCurrentlyAudible(); } #if BUILDFLAG(ENABLE_PRINTING) void WebContents::OnGetDeviceNameToUse( base::Value::Dict print_settings, printing::CompletionCallback print_callback, bool silent, // <error, device_name> std::pair<std::string, std::u16string> info) { // The content::WebContents might be already deleted at this point, and the // PrintViewManagerElectron class does not do null check. if (!web_contents()) { if (print_callback) std::move(print_callback).Run(false, "failed"); return; } if (!info.first.empty()) { if (print_callback) std::move(print_callback).Run(false, info.first); return; } // If the user has passed a deviceName use it, otherwise use default printer. print_settings.Set(printing::kSettingDeviceName, info.second); auto* print_view_manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!print_view_manager) return; auto* focused_frame = web_contents()->GetFocusedFrame(); auto* rfh = focused_frame && focused_frame->HasSelection() ? focused_frame : web_contents()->GetPrimaryMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); base::Value::Dict settings; if (args->Length() >= 1 && !args->GetNext(&options)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid print settings specified."); return; } printing::CompletionCallback callback; if (args->Length() == 2 && !args->GetNext(&callback)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid optional callback provided."); return; } // Set optional silent printing bool silent = false; options.Get("silent", &silent); bool print_background = false; options.Get("printBackground", &print_background); settings.Set(printing::kSettingShouldPrintBackgrounds, print_background); // Set custom margin settings gin_helper::Dictionary margins = gin::Dictionary::CreateEmpty(args->isolate()); if (options.Get("margins", &margins)) { printing::mojom::MarginType margin_type = printing::mojom::MarginType::kDefaultMargins; margins.Get("marginType", &margin_type); settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type)); if (margin_type == printing::mojom::MarginType::kCustomMargins) { base::Value::Dict custom_margins; int top = 0; margins.Get("top", &top); custom_margins.Set(printing::kSettingMarginTop, top); int bottom = 0; margins.Get("bottom", &bottom); custom_margins.Set(printing::kSettingMarginBottom, bottom); int left = 0; margins.Get("left", &left); custom_margins.Set(printing::kSettingMarginLeft, left); int right = 0; margins.Get("right", &right); custom_margins.Set(printing::kSettingMarginRight, right); settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins)); } } else { settings.Set( printing::kSettingMarginsType, static_cast<int>(printing::mojom::MarginType::kDefaultMargins)); } // Set whether to print color or greyscale bool print_color = true; options.Get("color", &print_color); auto const color_model = print_color ? printing::mojom::ColorModel::kColor : printing::mojom::ColorModel::kGray; settings.Set(printing::kSettingColor, static_cast<int>(color_model)); // Is the orientation landscape or portrait. bool landscape = false; options.Get("landscape", &landscape); settings.Set(printing::kSettingLandscape, landscape); // We set the default to the system's default printer and only update // if at the Chromium level if the user overrides. // Printer device name as opened by the OS. std::u16string device_name; options.Get("deviceName", &device_name); int scale_factor = 100; options.Get("scaleFactor", &scale_factor); settings.Set(printing::kSettingScaleFactor, scale_factor); int pages_per_sheet = 1; options.Get("pagesPerSheet", &pages_per_sheet); settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet); // True if the user wants to print with collate. bool collate = true; options.Get("collate", &collate); settings.Set(printing::kSettingCollate, collate); // The number of individual copies to print int copies = 1; options.Get("copies", &copies); settings.Set(printing::kSettingCopies, copies); // Strings to be printed as headers and footers if requested by the user. std::string header; options.Get("header", &header); std::string footer; options.Get("footer", &footer); if (!(header.empty() && footer.empty())) { settings.Set(printing::kSettingHeaderFooterEnabled, true); settings.Set(printing::kSettingHeaderFooterTitle, header); settings.Set(printing::kSettingHeaderFooterURL, footer); } else { settings.Set(printing::kSettingHeaderFooterEnabled, false); } // We don't want to allow the user to enable these settings // but we need to set them or a CHECK is hit. settings.Set(printing::kSettingPrinterType, static_cast<int>(printing::mojom::PrinterType::kLocal)); settings.Set(printing::kSettingShouldPrintSelectionOnly, false); settings.Set(printing::kSettingRasterizePdf, false); // Set custom page ranges to print std::vector<gin_helper::Dictionary> page_ranges; if (options.Get("pageRanges", &page_ranges)) { base::Value::List page_range_list; for (auto& range : page_ranges) { int from, to; if (range.Get("from", &from) && range.Get("to", &to)) { base::Value::Dict range; // Chromium uses 1-based page ranges, so increment each by 1. range.Set(printing::kSettingPageRangeFrom, from + 1); range.Set(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range)); } else { continue; } } if (!page_range_list.empty()) settings.Set(printing::kSettingPageRange, std::move(page_range_list)); } // Duplex type user wants to use. printing::mojom::DuplexMode duplex_mode = printing::mojom::DuplexMode::kSimplex; options.Get("duplexMode", &duplex_mode); settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode)); // We've already done necessary parameter sanitization at the // JS level, so we can simply pass this through. base::Value media_size(base::Value::Type::DICTIONARY); if (options.Get("mediaSize", &media_size)) settings.Set(printing::kSettingMediaSize, std::move(media_size)); // Set custom dots per inch (dpi) gin_helper::Dictionary dpi_settings; int dpi = 72; if (options.Get("dpi", &dpi_settings)) { int horizontal = 72; dpi_settings.Get("horizontal", &horizontal); settings.Set(printing::kSettingDpiHorizontal, horizontal); int vertical = 72; dpi_settings.Get("vertical", &vertical); settings.Set(printing::kSettingDpiVertical, vertical); } else { settings.Set(printing::kSettingDpiHorizontal, dpi); settings.Set(printing::kSettingDpiVertical, dpi); } print_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name), base::BindOnce(&WebContents::OnGetDeviceNameToUse, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), silent)); } // Partially duplicated and modified from // headless/lib/browser/protocol/page_handler.cc;l=41 v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); // This allows us to track headless printing calls. auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID); auto landscape = settings.GetDict().FindBool("landscape"); auto display_header_footer = settings.GetDict().FindBool("displayHeaderFooter"); auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds"); auto scale = settings.GetDict().FindDouble("scale"); auto paper_width = settings.GetDict().FindInt("paperWidth"); auto paper_height = settings.GetDict().FindInt("paperHeight"); auto margin_top = settings.GetDict().FindIntByDottedPath("margins.top"); auto margin_bottom = settings.GetDict().FindIntByDottedPath("margins.bottom"); auto margin_left = settings.GetDict().FindIntByDottedPath("margins.left"); auto margin_right = settings.GetDict().FindIntByDottedPath("margins.right"); auto page_ranges = *settings.GetDict().FindString("pageRanges"); auto header_template = *settings.GetDict().FindString("headerTemplate"); auto footer_template = *settings.GetDict().FindString("footerTemplate"); auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize"); absl::variant<printing::mojom::PrintPagesParamsPtr, std::string> print_pages_params = print_to_pdf::GetPrintPagesParams( web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(), landscape, display_header_footer, print_background, scale, paper_width, paper_height, margin_top, margin_bottom, margin_left, margin_right, absl::make_optional(header_template), absl::make_optional(footer_template), prefer_css_page_size); if (absl::holds_alternative<std::string>(print_pages_params)) { auto error = absl::get<std::string>(print_pages_params); promise.RejectWithErrorMessage("Invalid print parameters: " + error); return handle; } auto* manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!manager) { promise.RejectWithErrorMessage("Failed to find print manager"); return handle; } auto params = std::move( absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params)); params->params->document_cookie = unique_id.value_or(0); manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges, std::move(params), base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(), std::move(promise))); return handle; } void WebContents::OnPDFCreated( gin_helper::Promise<v8::Local<v8::Value>> promise, PrintViewManagerElectron::PrintResult print_result, scoped_refptr<base::RefCountedMemory> data) { if (print_result != PrintViewManagerElectron::PrintResult::PRINT_SUCCESS) { promise.RejectWithErrorMessage( "Failed to generate PDF: " + PrintViewManagerElectron::PrintResultToString(print_result)); return; } v8::Isolate* isolate = promise.isolate(); gin_helper::Locker locker(isolate); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope( v8::Local<v8::Context>::New(isolate, promise.GetContext())); v8::Local<v8::Value> buffer = node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()), data->size()) .ToLocalChecked(); promise.Resolve(buffer); } #endif void WebContents::AddWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsAddFileSystem(std::string(), path); } void WebContents::RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsRemoveFileSystem(path); } void WebContents::Undo() { web_contents()->Undo(); } void WebContents::Redo() { web_contents()->Redo(); } void WebContents::Cut() { web_contents()->Cut(); } void WebContents::Copy() { web_contents()->Copy(); } void WebContents::Paste() { web_contents()->Paste(); } void WebContents::PasteAndMatchStyle() { web_contents()->PasteAndMatchStyle(); } void WebContents::Delete() { web_contents()->Delete(); } void WebContents::SelectAll() { web_contents()->SelectAll(); } void WebContents::Unselect() { web_contents()->CollapseSelection(); } void WebContents::Replace(const std::u16string& word) { web_contents()->Replace(word); } void WebContents::ReplaceMisspelling(const std::u16string& word) { web_contents()->ReplaceMisspelling(word); } uint32_t WebContents::FindInPage(gin::Arguments* args) { std::u16string search_text; if (!args->GetNext(&search_text) || search_text.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must provide a non-empty search content"); return 0; } uint32_t request_id = ++find_in_page_request_id_; gin_helper::Dictionary dict; auto options = blink::mojom::FindOptions::New(); if (args->GetNext(&dict)) { dict.Get("forward", &options->forward); dict.Get("matchCase", &options->match_case); dict.Get("findNext", &options->new_session); } web_contents()->Find(request_id, search_text, std::move(options)); return request_id; } void WebContents::StopFindInPage(content::StopFindAction action) { web_contents()->StopFinding(action); } void WebContents::ShowDefinitionForSelection() { #if BUILDFLAG(IS_MAC) auto* const view = web_contents()->GetRenderWidgetHostView(); if (view) view->ShowDefinitionForSelection(); #endif } void WebContents::CopyImageAt(int x, int y) { auto* const host = web_contents()->GetPrimaryMainFrame(); if (host) host->CopyImageAt(x, y); } void WebContents::Focus() { // Focusing on WebContents does not automatically focus the window on macOS // and Linux, do it manually to match the behavior on Windows. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) if (owner_window()) owner_window()->Focus(true); #endif web_contents()->Focus(); } #if !BUILDFLAG(IS_MAC) bool WebContents::IsFocused() const { auto* view = web_contents()->GetRenderWidgetHostView(); if (!view) return false; if (GetType() != Type::kBackgroundPage) { auto* window = web_contents()->GetNativeView()->GetToplevelWindow(); if (window && !window->IsVisible()) return false; } return view->HasFocus(); } #endif void WebContents::SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event) { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); blink::WebInputEvent::Type type = gin::GetWebInputEventType(isolate, input_event); if (blink::WebInputEvent::IsMouseEventType(type)) { blink::WebMouseEvent mouse_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); #endif } else { rwh->ForwardMouseEvent(mouse_event); } return; } } else if (blink::WebInputEvent::IsKeyboardEventType(type)) { content::NativeWebKeyboardEvent keyboard_event( blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow()); if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) { rwh->ForwardKeyboardEvent(keyboard_event); return; } } else if (type == blink::WebInputEvent::Type::kMouseWheel) { blink::WebMouseWheelEvent mouse_wheel_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); #endif } else { // Chromium expects phase info in wheel events (and applies a // DCHECK to verify it). See: https://crbug.com/756524. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); // Send a synthetic wheel event with phaseEnded to finish scrolling. mouse_wheel_event.has_synthetic_phase = true; mouse_wheel_event.delta_x = 0; mouse_wheel_event.delta_y = 0; mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kEventNonBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); } return; } } isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object"))); } void WebContents::BeginFrameSubscription(gin::Arguments* args) { bool only_dirty = false; FrameSubscriber::FrameCaptureCallback callback; if (args->Length() > 1) { if (!args->GetNext(&only_dirty)) { args->ThrowError(); return; } } if (!args->GetNext(&callback)) { args->ThrowError(); return; } frame_subscriber_ = std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty); } void WebContents::EndFrameSubscription() { frame_subscriber_.reset(); } void WebContents::StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args) { base::FilePath file; std::vector<base::FilePath> files; if (!item.Get("files", &files) && item.Get("file", &file)) { files.push_back(file); } v8::Local<v8::Value> icon_value; if (!item.Get("icon", &icon_value)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'icon' parameter is required"); return; } NativeImage* icon = nullptr; if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) || icon->image().IsEmpty()) { return; } // Start dragging. if (!files.empty()) { base::CurrentThread::ScopedNestableTaskAllower allow; DragFileItems(files, icon->image(), web_contents()->GetNativeView()); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must specify either 'file' or 'files' option"); } } v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) { gfx::Rect rect; gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // get rect arguments if they exist args->GetNext(&rect); auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view) { promise.Resolve(gfx::Image()); return handle; } #if !BUILDFLAG(IS_MAC) // If the view's renderer is suspended this may fail on Windows/Linux - // bail if so. See CopyFromSurface in // content/public/browser/render_widget_host_view.h. auto* rfh = web_contents()->GetPrimaryMainFrame(); if (rfh && rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) { promise.Resolve(gfx::Image()); return handle; } #endif // BUILDFLAG(IS_MAC) // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); const float scale = display::Screen::GetScreen() ->GetDisplayNearestView(native_view) .device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, base::BindOnce(&OnCapturePageDone, std::move(promise))); return handle; } void WebContents::IncrementCapturerCount(gin::Arguments* args) { gfx::Size size; bool stay_hidden = false; bool stay_awake = false; // get size arguments if they exist args->GetNext(&size); // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); std::ignore = web_contents() ->IncrementCapturerCount(size, stay_hidden, stay_awake) .Release(); } void WebContents::DecrementCapturerCount(gin::Arguments* args) { bool stay_hidden = false; bool stay_awake = false; // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); web_contents()->DecrementCapturerCount(stay_hidden, stay_awake); } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const content::WebCursor& webcursor) { const ui::Cursor& cursor = webcursor.cursor(); if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor), gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()), cursor.image_scale_factor(), gfx::Size(cursor.custom_bitmap().width(), cursor.custom_bitmap().height()), cursor.custom_hotspot()); } else { Emit("cursor-changed", CursorTypeToString(cursor)); } } bool WebContents::IsGuest() const { return type_ == Type::kWebView; } void WebContents::AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id) { attached_ = true; if (guest_delegate_) guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id); } bool WebContents::IsOffScreen() const { #if BUILDFLAG(ENABLE_OSR) return type_ == Type::kOffScreen; #else return false; #endif } #if BUILDFLAG(ENABLE_OSR) void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) { Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap)); } void WebContents::StartPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(true); } void WebContents::StopPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(false); } bool WebContents::IsPainting() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv && osr_wcv->IsPainting(); } void WebContents::SetFrameRate(int frame_rate) { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetFrameRate(frame_rate); } int WebContents::GetFrameRate() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv ? osr_wcv->GetFrameRate() : 0; } #endif void WebContents::Invalidate() { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); #endif } else { auto* const window = owner_window(); if (window) window->Invalidate(); } } gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) { if (IsOffScreen() && wc == web_contents()) { auto* relay = NativeWindowRelay::FromWebContents(web_contents()); if (relay) { auto* owner_window = relay->GetNativeWindow(); return owner_window ? owner_window->GetSize() : gfx::Size(); } } return gfx::Size(); } void WebContents::SetZoomLevel(double level) { zoom_controller_->SetZoomLevel(level); } double WebContents::GetZoomLevel() const { return zoom_controller_->GetZoomLevel(); } void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) { if (factor < std::numeric_limits<double>::epsilon()) { thrower.ThrowError("'zoomFactor' must be a double greater than 0.0"); return; } auto level = blink::PageZoomFactorToZoomLevel(factor); SetZoomLevel(level); } double WebContents::GetZoomFactor() const { auto level = GetZoomLevel(); return blink::PageZoomLevelToZoomFactor(level); } void WebContents::SetTemporaryZoomLevel(double level) { zoom_controller_->SetTemporaryZoomLevel(level); } void WebContents::DoGetZoomLevel( electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback callback) { std::move(callback).Run(GetZoomLevel()); } std::vector<base::FilePath> WebContents::GetPreloadPaths() const { auto result = SessionPreferences::GetValidPreloads(GetBrowserContext()); if (auto* web_preferences = WebContentsPreferences::From(web_contents())) { base::FilePath preload; if (web_preferences->GetPreloadPath(&preload)) { result.emplace_back(preload); } } return result; } v8::Local<v8::Value> WebContents::GetLastWebPreferences( v8::Isolate* isolate) const { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (!web_preferences) return v8::Null(isolate); return gin::ConvertToV8(isolate, *web_preferences->last_preference()); } v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow( v8::Isolate* isolate) const { if (owner_window()) return BrowserWindow::From(isolate, owner_window()); else return v8::Null(isolate); } v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) { return v8::Local<v8::Value>::New(isolate, session_); } content::WebContents* WebContents::HostWebContents() const { if (!embedder_) return nullptr; return embedder_->web_contents(); } void WebContents::SetEmbedder(const WebContents* embedder) { if (embedder) { NativeWindow* owner_window = nullptr; auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents()); if (relay) { owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); content::RenderWidgetHostView* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->Hide(); rwhv->Show(); } } } void WebContents::SetDevToolsWebContents(const WebContents* devtools) { if (inspectable_web_contents_) inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents()); } v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const { gfx::NativeView ptr = web_contents()->GetNativeView(); auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr), sizeof(gfx::NativeView)); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) { if (devtools_web_contents_.IsEmpty()) return v8::Null(isolate); else return v8::Local<v8::Value>::New(isolate, devtools_web_contents_); } v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) { if (debugger_.IsEmpty()) { auto handle = electron::api::Debugger::Create(isolate, web_contents()); debugger_.Reset(isolate, handle.ToV8()); } return v8::Local<v8::Value>::New(isolate, debugger_); } content::RenderFrameHost* WebContents::MainFrame() { return web_contents()->GetPrimaryMainFrame(); } void WebContents::NotifyUserActivation() { content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame(); if (frame) frame->NotifyUserActivation( blink::mojom::UserActivationNotificationType::kInteraction); } void WebContents::SetImageAnimationPolicy(const std::string& new_policy) { auto* web_preferences = WebContentsPreferences::From(web_contents()); web_preferences->SetImageAnimationPolicy(new_policy); web_contents()->OnWebPreferencesChanged(); } v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("Failed to create memory dump"); return handle; } auto pid = frame_host->GetProcess()->GetProcess().Pid(); v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext()); memory_instrumentation::MemoryInstrumentation::GetInstance() ->RequestGlobalDumpForPid( pid, std::vector<std::string>(), base::BindOnce(&ElectronBindings::DidReceiveMemoryDump, std::move(context), std::move(promise), pid)); return handle; } v8::Local<v8::Promise> WebContents::TakeHeapSnapshot( v8::Isolate* isolate, const base::FilePath& file_path) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); base::ThreadRestrictions::ScopedAllowIO allow_io; base::File file(file_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); if (!file.IsValid()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } if (!frame_host->IsRenderFrameLive()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } // This dance with `base::Owned` is to ensure that the interface stays alive // until the callback is called. Otherwise it would be closed at the end of // this function. auto electron_renderer = std::make_unique<mojo::Remote<mojom::ElectronRenderer>>(); frame_host->GetRemoteInterfaces()->GetInterface( electron_renderer->BindNewPipeAndPassReceiver()); auto* raw_ptr = electron_renderer.get(); (*raw_ptr)->TakeHeapSnapshot( mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())), base::BindOnce( [](mojo::Remote<mojom::ElectronRenderer>* ep, gin_helper::Promise<void> promise, bool success) { if (success) { promise.Resolve(); } else { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } void WebContents::UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) { Emit("preferred-size-changed", pref_size); } bool WebContents::CanOverscrollContent() { return false; } std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) { return ShowEyeDropper(frame, listener); } void WebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener), params); } void WebContents::EnumerateDirectory( content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path); } bool WebContents::IsFullscreenForTabOrPending( const content::WebContents* source) { bool transition_fs = owner_window() ? owner_window()->fullscreen_transition_state() != NativeWindow::FullScreenTransitionState::NONE : false; return html_fullscreen_ || transition_fs; } bool WebContents::TakeFocus(content::WebContents* source, bool reverse) { if (source && source->GetOutermostWebContents() == source) { // If this is the outermost web contents and the user has tabbed or // shift + tabbed through all the elements, reset the focus back to // the first or last element so that it doesn't stay in the body. source->FocusThroughTabTraversal(reverse); return true; } return false; } content::PictureInPictureResult WebContents::EnterPictureInPicture( content::WebContents* web_contents) { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) return PictureInPictureWindowManager::GetInstance() ->EnterVideoPictureInPicture(web_contents); #else return content::PictureInPictureResult::kNotSupported; #endif } void WebContents::ExitPictureInPicture() { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); #endif } void WebContents::DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) { base::FilePath path; auto it = saved_files_.find(url); if (it != saved_files_.end() && !save_as) { path = it->second; } else { file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.title = url; settings.default_path = base::FilePath::FromUTF8Unsafe(url); if (!file_dialog::ShowSaveDialogSync(settings, &path)) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "canceledSaveURL", base::Value(url)); return; } } saved_files_[url] = path; // Notify DevTools. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "savedURL", base::Value(url), base::Value(path.AsUTF8Unsafe())); file_task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteToFile, path, content)); } void WebContents::DevToolsAppendToFile(const std::string& url, const std::string& content) { auto it = saved_files_.find(url); if (it == saved_files_.end()) return; // Notify DevTools. inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL", base::Value(url)); file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&AppendToFile, it->second, content)); } void WebContents::DevToolsRequestFileSystems() { auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); if (file_system_paths.empty()) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List())); return; } std::vector<FileSystem> file_systems; for (const auto& file_system_path : file_system_paths) { base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path.first); std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id, file_system_path.first, file_system_path.second); file_systems.push_back(file_system); } base::Value::List file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(std::move(file_system_value))); } void WebContents::DevToolsAddFileSystem( const std::string& type, const base::FilePath& file_system_path) { base::FilePath path = file_system_path; if (path.empty()) { std::vector<base::FilePath> paths; file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY; if (!file_dialog::ShowOpenDialogSync(settings, &paths)) return; path = paths[0]; } std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe())) return; FileSystem file_system = CreateFileSystemStruct( GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type); base::Value::Dict file_system_value = CreateFileSystemValue(file_system); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->SetKey(path.AsUTF8Unsafe(), base::Value(type)); std::string error = ""; // No error inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemAdded", base::Value(error), base::Value(std::move(file_system_value))); } void WebContents::DevToolsRemoveFileSystem( const base::FilePath& file_system_path) { if (!inspectable_web_contents_) return; std::string path = file_system_path.AsUTF8Unsafe(); storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath( file_system_path); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->RemoveKey(path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemRemoved", base::Value(path)); } void WebContents::DevToolsIndexPath( int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsIndexingDone(request_id, file_system_path); return; } if (devtools_indexing_jobs_.count(request_id) != 0) return; std::vector<std::string> excluded_folders; std::unique_ptr<base::Value> parsed_excluded_folders = base::JSONReader::ReadDeprecated(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetListDeprecated()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsSearchCompleted(request_id, file_system_path, std::vector<std::string>()); return; } devtools_file_system_indexer_->SearchInPath( file_system_path, query, base::BindRepeating(&WebContents::OnDevToolsSearchCompleted, weak_factory_.GetWeakPtr(), request_id, file_system_path)); } void WebContents::DevToolsSetEyeDropperActive(bool active) { auto* web_contents = GetWebContents(); if (!web_contents) return; if (active) { eye_dropper_ = std::make_unique<DevToolsEyeDropper>( web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper, base::Unretained(this))); } else { eye_dropper_.reset(); } } void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) { base::Value::Dict color; color.Set("r", r); color.Set("g", g); color.Set("b", b); color.Set("a", a); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color))); } #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel WebContents::GetDevToolsWindowIcon() { return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{}; } #endif #if BUILDFLAG(IS_LINUX) void WebContents::GetDevToolsWindowWMClass(std::string* name, std::string* class_name) { *class_name = Browser::Get()->GetName(); *name = base::ToLowerASCII(*class_name); } #endif void WebContents::OnDevToolsIndexingWorkCalculated( int request_id, const std::string& file_system_path, int total_work) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id), base::Value(file_system_path), base::Value(total_work)); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingWorked", base::Value(request_id), base::Value(file_system_path), base::Value(worked)); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone", base::Value(request_id), base::Value(file_system_path)); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::Value::List file_paths_value; for (const auto& file_path : file_paths) file_paths_value.Append(file_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "searchCompleted", base::Value(request_id), base::Value(file_system_path), base::Value(std::move(file_paths_value))); } void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) { // Window is already in fullscreen mode, save the state. if (enter_fullscreen && owner_window_->IsFullscreen()) { native_fullscreen_ = true; UpdateHtmlApiFullscreen(true); return; } // Exit html fullscreen state but not window's fullscreen mode. if (!enter_fullscreen && native_fullscreen_) { UpdateHtmlApiFullscreen(false); return; } // Set fullscreen on window if allowed. auto* web_preferences = WebContentsPreferences::From(GetWebContents()); bool html_fullscreenable = web_preferences ? !web_preferences->ShouldDisableHtmlFullscreenWindowResize() : true; if (html_fullscreenable) owner_window_->SetFullScreen(enter_fullscreen); UpdateHtmlApiFullscreen(enter_fullscreen); native_fullscreen_ = false; } void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) { if (fullscreen == is_html_fullscreen()) return; html_fullscreen_ = fullscreen; // Notify renderer of the html fullscreen change. web_contents() ->GetRenderViewHost() ->GetWidget() ->SynchronizeVisualProperties(); // The embedder WebContents is separated from the frame tree of webview, so // we must manually sync their fullscreen states. if (embedder_) embedder_->SetHtmlApiFullscreen(fullscreen); if (fullscreen) { Emit("enter-html-full-screen"); owner_window_->NotifyWindowEnterHtmlFullScreen(); } else { Emit("leave-html-full-screen"); owner_window_->NotifyWindowLeaveHtmlFullScreen(); } // Make sure all child webviews quit html fullscreen. if (!fullscreen && !IsGuest()) { auto* manager = WebViewManager::GetWebViewManager(web_contents()); manager->ForEachGuest( web_contents(), base::BindRepeating([](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); api_web_contents->SetHtmlApiFullscreen(false); return false; })); } } // static v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = "WebContents"; templ->Set( gin::StringToSymbol(isolate, "isDestroyed"), gin::CreateFunctionTemplate( isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed), options)); // We use gin_helper::ObjectTemplateBuilder instead of // gin::ObjectTemplateBuilder here to handle the fact that WebContents is // destroyable. return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("getBackgroundThrottling", &WebContents::GetBackgroundThrottling) .SetMethod("setBackgroundThrottling", &WebContents::SetBackgroundThrottling) .SetMethod("getProcessId", &WebContents::GetProcessID) .SetMethod("getOSProcessId", &WebContents::GetOSProcessID) .SetMethod("equal", &WebContents::Equal) .SetMethod("_loadURL", &WebContents::LoadURL) .SetMethod("reload", &WebContents::Reload) .SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache) .SetMethod("downloadURL", &WebContents::DownloadURL) .SetMethod("getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) .SetMethod("stop", &WebContents::Stop) .SetMethod("canGoBack", &WebContents::CanGoBack) .SetMethod("goBack", &WebContents::GoBack) .SetMethod("canGoForward", &WebContents::CanGoForward) .SetMethod("goForward", &WebContents::GoForward) .SetMethod("canGoToOffset", &WebContents::CanGoToOffset) .SetMethod("goToOffset", &WebContents::GoToOffset) .SetMethod("canGoToIndex", &WebContents::CanGoToIndex) .SetMethod("goToIndex", &WebContents::GoToIndex) .SetMethod("getActiveIndex", &WebContents::GetActiveIndex) .SetMethod("clearHistory", &WebContents::ClearHistory) .SetMethod("length", &WebContents::GetHistoryLength) .SetMethod("isCrashed", &WebContents::IsCrashed) .SetMethod("forcefullyCrashRenderer", &WebContents::ForcefullyCrashRenderer) .SetMethod("setUserAgent", &WebContents::SetUserAgent) .SetMethod("getUserAgent", &WebContents::GetUserAgent) .SetMethod("savePage", &WebContents::SavePage) .SetMethod("openDevTools", &WebContents::OpenDevTools) .SetMethod("closeDevTools", &WebContents::CloseDevTools) .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened) .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused) .SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation) .SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation) .SetMethod("toggleDevTools", &WebContents::ToggleDevTools) .SetMethod("inspectElement", &WebContents::InspectElement) .SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts) .SetMethod("setAudioMuted", &WebContents::SetAudioMuted) .SetMethod("isAudioMuted", &WebContents::IsAudioMuted) .SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible) .SetMethod("undo", &WebContents::Undo) .SetMethod("redo", &WebContents::Redo) .SetMethod("cut", &WebContents::Cut) .SetMethod("copy", &WebContents::Copy) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("replace", &WebContents::Replace) .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling) .SetMethod("findInPage", &WebContents::FindInPage) .SetMethod("stopFindInPage", &WebContents::StopFindInPage) .SetMethod("focus", &WebContents::Focus) .SetMethod("isFocused", &WebContents::IsFocused) .SetMethod("sendInputEvent", &WebContents::SendInputEvent) .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("startDrag", &WebContents::StartDrag) .SetMethod("attachToIframe", &WebContents::AttachToIframe) .SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame) .SetMethod("isOffscreen", &WebContents::IsOffScreen) #if BUILDFLAG(ENABLE_OSR) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) #endif .SetMethod("invalidate", &WebContents::Invalidate) .SetMethod("setZoomLevel", &WebContents::SetZoomLevel) .SetMethod("getZoomLevel", &WebContents::GetZoomLevel) .SetMethod("setZoomFactor", &WebContents::SetZoomFactor) .SetMethod("getZoomFactor", &WebContents::GetZoomFactor) .SetMethod("getType", &WebContents::GetType) .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths) .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker) .SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker) .SetMethod("inspectSharedWorkerById", &WebContents::InspectSharedWorkerById) .SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers) #if BUILDFLAG(ENABLE_PRINTING) .SetMethod("_print", &WebContents::Print) .SetMethod("_printToPDF", &WebContents::PrintToPDF) #endif .SetMethod("_setNextChildWebPreferences", &WebContents::SetNextChildWebPreferences) .SetMethod("addWorkSpace", &WebContents::AddWorkSpace) .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("showDefinitionForSelection", &WebContents::ShowDefinitionForSelection) .SetMethod("copyImageAt", &WebContents::CopyImageAt) .SetMethod("capturePage", &WebContents::CapturePage) .SetMethod("setEmbedder", &WebContents::SetEmbedder) .SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents) .SetMethod("getNativeView", &WebContents::GetNativeView) .SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount) .SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount) .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot) .SetMethod("setImageAnimationPolicy", &WebContents::SetImageAnimationPolicy) .SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo) .SetProperty("id", &WebContents::ID) .SetProperty("session", &WebContents::Session) .SetProperty("hostWebContents", &WebContents::HostWebContents) .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents) .SetProperty("debugger", &WebContents::Debugger) .SetProperty("mainFrame", &WebContents::MainFrame) .Build(); } const char* WebContents::GetTypeName() { return "WebContents"; } ElectronBrowserContext* WebContents::GetBrowserContext() const { return static_cast<ElectronBrowserContext*>( web_contents()->GetBrowserContext()); } // static gin::Handle<WebContents> WebContents::New( v8::Isolate* isolate, const gin_helper::Dictionary& options) { gin::Handle<WebContents> handle = gin::CreateHandle(isolate, new WebContents(isolate, options)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static gin::Handle<WebContents> WebContents::CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) { gin::Handle<WebContents> handle = gin::CreateHandle( isolate, new WebContents(isolate, std::move(web_contents), type)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static WebContents* WebContents::From(content::WebContents* web_contents) { if (!web_contents) return nullptr; auto* data = static_cast<UserDataLink*>( web_contents->GetUserData(kElectronApiWebContentsKey)); return data ? data->web_contents.get() : nullptr; } // static gin::Handle<WebContents> WebContents::FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents) { WebContents* api_web_contents = From(web_contents); if (!api_web_contents) { api_web_contents = new WebContents(isolate, web_contents); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, api_web_contents, "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } } return gin::CreateHandle(isolate, api_web_contents); } // static gin::Handle<WebContents> WebContents::CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences) { // Check if webPreferences has |webContents| option. gin::Handle<WebContents> web_contents; if (web_preferences.GetHidden("webContents", &web_contents) && !web_contents.IsEmpty()) { // Set webPreferences from options if using an existing webContents. // These preferences will be used when the webContent launches new // render processes. auto* existing_preferences = WebContentsPreferences::From(web_contents->web_contents()); gin_helper::Dictionary web_preferences_dict; if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(), &web_preferences_dict)) { existing_preferences->SetFromDictionary(web_preferences_dict); absl::optional<SkColor> color = existing_preferences->GetBackgroundColor(); web_contents->web_contents()->SetPageBaseBackgroundColor(color); // Because web preferences don't recognize transparency, // only set rwhv background color if a color exists auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView(); if (rwhv && color.has_value()) SetBackgroundColor(rwhv, color.value()); } } else { // Create one if not. web_contents = WebContents::New(isolate, web_preferences); } return web_contents; } // static WebContents* WebContents::FromID(int32_t id) { return GetAllWebContents().Lookup(id); } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace electron::api namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) { WebContents* contents = WebContents::FromID(id); return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } gin::Handle<WebContents> WebContentsFromDevToolsTargetID( v8::Isolate* isolate, std::string target_id) { auto agent_host = content::DevToolsAgentHost::GetForId(target_id); WebContents* contents = agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr; return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8( v8::Isolate* isolate) { std::vector<gin::Handle<WebContents>> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue())); } return list; } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); dict.SetMethod("fromId", &WebContentsFromID); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
35,046
[Bug]: webContents.getUserAgent() is empty since 20.0.0-alpha.6
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.0-alpha.6 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version 20.0.0-alpha.5 ### Expected Behavior `webContents.getUserAgent()` returns a string with a user Agent ### Actual Behavior webContents.getUserAgent() returns an empty string ### Testcase Gist URL https://gist.github.com/33fd4a9ac6db6b28b1dcc5b765edb622 ### Additional Information In the console the user agent is printed in alpha.5, but empty in alpha.6. Looking at the diff between alpha.5 and alpha.6, this PR seems the likely cause: https://github.com/electron/electron/pull/34524 / #34481 It's worth noting that the renderer does have a filled-in userAgent.
https://github.com/electron/electron/issues/35046
https://github.com/electron/electron/pull/35069
8004cb8722c8d52f4cd553bbaea86750149e8ca4
9028bb79a85fedf64230c2f1c6a29ab072c98c20
2022-07-25T14:12:09Z
c++
2022-07-29T15:09:47Z
shell/browser/electron_browser_context.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_context.h" #include <memory> #include <utility> #include "base/barrier_closure.h" #include "base/base_paths.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/no_destructor.h" #include "base/path_service.h" #include "base/strings/escape.h" #include "base/strings/string_util.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/prefs/json_pref_store.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/pref_service_factory.h" #include "components/prefs/value_map_pref_store.h" #include "components/proxy_config/pref_proxy_config_tracker_impl.h" #include "components/proxy_config/proxy_config_pref_names.h" #include "content/browser/blob_storage/chrome_blob_storage_context.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/cors_origin_pattern_setter.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "services/network/public/mojom/network_context.mojom.h" #include "shell/browser/cookie_change_notifier.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_download_manager_delegate.h" #include "shell/browser/electron_permission_manager.h" #include "shell/browser/net/resolve_proxy_helper.h" #include "shell/browser/pref_store_delegate.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/special_storage_policy.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/zoom_level_delegate.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/options_switches.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/browser/extension_pref_store.h" #include "extensions/browser/extension_pref_value_map_factory.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/pref_names.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extension_system.h" #include "shell/browser/extensions/electron_extension_system_factory.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "components/pref_registry/pref_registry_syncable.h" #include "components/user_prefs/user_prefs.h" #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "base/i18n/rtl.h" #include "components/language/core/browser/language_prefs.h" #include "components/spellcheck/browser/pref_names.h" #include "components/spellcheck/common/spellcheck_common.h" #endif using content::BrowserThread; namespace electron { namespace { // Convert string to lower case and escape it. std::string MakePartitionName(const std::string& input) { return base::EscapePath(base::ToLowerASCII(input)); } } // namespace // static ElectronBrowserContext::BrowserContextMap& ElectronBrowserContext::browser_context_map() { static base::NoDestructor<ElectronBrowserContext::BrowserContextMap> browser_context_map; return *browser_context_map; } ElectronBrowserContext::ElectronBrowserContext(const std::string& partition, bool in_memory, base::Value::Dict options) : storage_policy_(base::MakeRefCounted<SpecialStoragePolicy>()), protocol_registry_(base::WrapUnique(new ProtocolRegistry)), in_memory_(in_memory), ssl_config_(network::mojom::SSLConfig::New()) { // Read options. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); use_cache_ = !command_line->HasSwitch(switches::kDisableHttpCache); if (auto use_cache_opt = options.FindBool("cache")) { use_cache_ = use_cache_opt.value(); } base::StringToInt(command_line->GetSwitchValueASCII(switches::kDiskCacheSize), &max_cache_size_); base::PathService::Get(DIR_SESSION_DATA, &path_); if (!in_memory && !partition.empty()) path_ = path_.Append(FILE_PATH_LITERAL("Partitions")) .Append(base::FilePath::FromUTF8Unsafe( MakePartitionName(partition))); BrowserContextDependencyManager::GetInstance()->MarkBrowserContextLive(this); // Initialize Pref Registry. InitPrefs(); cookie_change_notifier_ = std::make_unique<CookieChangeNotifier>(this); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { BrowserContextDependencyManager::GetInstance() ->CreateBrowserContextServices(this); extension_system_ = static_cast<extensions::ElectronExtensionSystem*>( extensions::ExtensionSystem::Get(this)); extension_system_->InitForRegularProfile(true /* extensions_enabled */); extension_system_->FinishInitialization(); } #endif } ElectronBrowserContext::~ElectronBrowserContext() { DCHECK_CURRENTLY_ON(BrowserThread::UI); NotifyWillBeDestroyed(); // Notify any keyed services of browser context destruction. BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices( this); ShutdownStoragePartitions(); BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, std::move(resource_context_)); } void ElectronBrowserContext::InitPrefs() { auto prefs_path = GetPath().Append(FILE_PATH_LITERAL("Preferences")); base::ThreadRestrictions::ScopedAllowIO allow_io; PrefServiceFactory prefs_factory; scoped_refptr<JsonPrefStore> pref_store = base::MakeRefCounted<JsonPrefStore>(prefs_path); pref_store->ReadPrefs(); // Synchronous. prefs_factory.set_user_prefs(pref_store); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { auto* ext_pref_store = new ExtensionPrefStore( ExtensionPrefValueMapFactory::GetForBrowserContext(this), IsOffTheRecord()); prefs_factory.set_extension_prefs(ext_pref_store); } #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) auto registry = base::MakeRefCounted<user_prefs::PrefRegistrySyncable>(); #else auto registry = base::MakeRefCounted<PrefRegistrySimple>(); #endif registry->RegisterFilePathPref(prefs::kSelectFileLastDirectory, base::FilePath()); base::FilePath download_dir; base::PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_dir); registry->RegisterFilePathPref(prefs::kDownloadDefaultDirectory, download_dir); registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths); InspectableWebContents::RegisterPrefs(registry.get()); MediaDeviceIDSalt::RegisterPrefs(registry.get()); ZoomLevelDelegate::RegisterPrefs(registry.get()); PrefProxyConfigTrackerImpl::RegisterPrefs(registry.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) extensions::ExtensionPrefs::RegisterProfilePrefs(registry.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) BrowserContextDependencyManager::GetInstance() ->RegisterProfilePrefsForServices(registry.get()); language::LanguagePrefs::RegisterProfilePrefs(registry.get()); #endif prefs_ = prefs_factory.Create( registry.get(), std::make_unique<PrefStoreDelegate>(weak_factory_.GetWeakPtr())); prefs_->UpdateCommandLinePrefStore(new ValueMapPrefStore); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) user_prefs::UserPrefs::Set(this, prefs_.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) auto* current_dictionaries = prefs()->Get(spellcheck::prefs::kSpellCheckDictionaries); // No configured dictionaries, the default will be en-US if (current_dictionaries->GetListDeprecated().empty()) { std::string default_code = spellcheck::GetCorrespondingSpellCheckLanguage( base::i18n::GetConfiguredLocale()); if (!default_code.empty()) { base::Value::List language_codes; language_codes.Append(default_code); prefs()->Set(spellcheck::prefs::kSpellCheckDictionaries, base::Value(std::move(language_codes))); } } #endif } void ElectronBrowserContext::SetUserAgent(const std::string& user_agent) { user_agent_ = user_agent; } base::FilePath ElectronBrowserContext::GetPath() { return path_; } bool ElectronBrowserContext::IsOffTheRecord() { return in_memory_; } bool ElectronBrowserContext::CanUseHttpCache() const { return use_cache_; } int ElectronBrowserContext::GetMaxCacheSize() const { return max_cache_size_; } content::ResourceContext* ElectronBrowserContext::GetResourceContext() { if (!resource_context_) resource_context_ = std::make_unique<content::ResourceContext>(); return resource_context_.get(); } std::string ElectronBrowserContext::GetMediaDeviceIDSalt() { if (!media_device_id_salt_.get()) media_device_id_salt_ = std::make_unique<MediaDeviceIDSalt>(prefs_.get()); return media_device_id_salt_->GetSalt(); } std::unique_ptr<content::ZoomLevelDelegate> ElectronBrowserContext::CreateZoomLevelDelegate( const base::FilePath& partition_path) { if (!IsOffTheRecord()) { return std::make_unique<ZoomLevelDelegate>(prefs(), partition_path); } return std::unique_ptr<content::ZoomLevelDelegate>(); } content::DownloadManagerDelegate* ElectronBrowserContext::GetDownloadManagerDelegate() { if (!download_manager_delegate_.get()) { auto* download_manager = this->GetDownloadManager(); download_manager_delegate_ = std::make_unique<ElectronDownloadManagerDelegate>(download_manager); } return download_manager_delegate_.get(); } content::BrowserPluginGuestManager* ElectronBrowserContext::GetGuestManager() { if (!guest_manager_) guest_manager_ = std::make_unique<WebViewManager>(); return guest_manager_.get(); } content::PlatformNotificationService* ElectronBrowserContext::GetPlatformNotificationService() { return ElectronBrowserClient::Get()->GetPlatformNotificationService(); } content::PermissionControllerDelegate* ElectronBrowserContext::GetPermissionControllerDelegate() { if (!permission_manager_.get()) permission_manager_ = std::make_unique<ElectronPermissionManager>(); return permission_manager_.get(); } storage::SpecialStoragePolicy* ElectronBrowserContext::GetSpecialStoragePolicy() { return storage_policy_.get(); } std::string ElectronBrowserContext::GetUserAgent() const { return user_agent_.value_or(ElectronBrowserClient::Get()->GetUserAgent()); } absl::optional<std::string> ElectronBrowserContext::GetUserAgentOverride() const { return user_agent_; } predictors::PreconnectManager* ElectronBrowserContext::GetPreconnectManager() { if (!preconnect_manager_.get()) { preconnect_manager_ = std::make_unique<predictors::PreconnectManager>(nullptr, this); } return preconnect_manager_.get(); } scoped_refptr<network::SharedURLLoaderFactory> ElectronBrowserContext::GetURLLoaderFactory() { if (url_loader_factory_) return url_loader_factory_; mojo::PendingRemote<network::mojom::URLLoaderFactory> network_factory_remote; mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver = network_factory_remote.InitWithNewPipeAndPassReceiver(); // Consult the embedder. mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient> header_client; static_cast<content::ContentBrowserClient*>(ElectronBrowserClient::Get()) ->WillCreateURLLoaderFactory( this, nullptr, -1, content::ContentBrowserClient::URLLoaderFactoryType::kNavigation, url::Origin(), absl::nullopt, ukm::kInvalidSourceIdObj, &factory_receiver, &header_client, nullptr, nullptr, nullptr); network::mojom::URLLoaderFactoryParamsPtr params = network::mojom::URLLoaderFactoryParams::New(); params->header_client = std::move(header_client); params->process_id = network::mojom::kBrowserProcessId; params->is_trusted = true; params->is_corb_enabled = false; // The tests of net module would fail if this setting is true, it seems that // the non-NetworkService implementation always has web security enabled. params->disable_web_security = false; auto* storage_partition = GetDefaultStoragePartition(); storage_partition->GetNetworkContext()->CreateURLLoaderFactory( std::move(factory_receiver), std::move(params)); url_loader_factory_ = base::MakeRefCounted<network::WrapperSharedURLLoaderFactory>( std::move(network_factory_remote)); return url_loader_factory_; } content::PushMessagingService* ElectronBrowserContext::GetPushMessagingService() { return nullptr; } content::SSLHostStateDelegate* ElectronBrowserContext::GetSSLHostStateDelegate() { return nullptr; } content::BackgroundFetchDelegate* ElectronBrowserContext::GetBackgroundFetchDelegate() { return nullptr; } content::BackgroundSyncController* ElectronBrowserContext::GetBackgroundSyncController() { return nullptr; } content::BrowsingDataRemoverDelegate* ElectronBrowserContext::GetBrowsingDataRemoverDelegate() { return nullptr; } content::ClientHintsControllerDelegate* ElectronBrowserContext::GetClientHintsControllerDelegate() { return nullptr; } content::StorageNotificationService* ElectronBrowserContext::GetStorageNotificationService() { return nullptr; } ResolveProxyHelper* ElectronBrowserContext::GetResolveProxyHelper() { if (!resolve_proxy_helper_) { resolve_proxy_helper_ = base::MakeRefCounted<ResolveProxyHelper>(this); } return resolve_proxy_helper_.get(); } network::mojom::SSLConfigPtr ElectronBrowserContext::GetSSLConfig() { return ssl_config_.Clone(); } void ElectronBrowserContext::SetSSLConfig(network::mojom::SSLConfigPtr config) { ssl_config_ = std::move(config); if (ssl_config_client_) { ssl_config_client_->OnSSLConfigUpdated(ssl_config_.Clone()); } } void ElectronBrowserContext::SetSSLConfigClient( mojo::Remote<network::mojom::SSLConfigClient> client) { ssl_config_client_ = std::move(client); } void ElectronBrowserContext::GrantDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { granted_devices_[permission_type][origin].push_back( std::make_unique<base::Value>(device.Clone())); } void ElectronBrowserContext::RevokeDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return; for (auto it = origin_devices_it->second.begin(); it != origin_devices_it->second.end();) { if (DoesDeviceMatch(device, it->get(), permission_type)) { it = origin_devices_it->second.erase(it); } else { ++it; } } } bool ElectronBrowserContext::DoesDeviceMatch( const base::Value& device, const base::Value* device_to_compare, blink::PermissionType permission_type) { if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::HID)) { if (device.GetDict().FindInt(kHidVendorIdKey) != device_to_compare->GetDict().FindInt(kHidVendorIdKey) || device.GetDict().FindInt(kHidProductIdKey) != device_to_compare->GetDict().FindInt(kHidProductIdKey)) { return false; } const auto* serial_number = device_to_compare->GetDict().FindString(kHidSerialNumberKey); const auto* device_serial_number = device.GetDict().FindString(kHidSerialNumberKey); if (serial_number && device_serial_number && *device_serial_number == *serial_number) return true; } else if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::SERIAL)) { #if BUILDFLAG(IS_WIN) const auto* instance_id = device.GetDict().FindString(kDeviceInstanceIdKey); const auto* port_instance_id = device_to_compare->GetDict().FindString(kDeviceInstanceIdKey); if (instance_id && port_instance_id && *instance_id == *port_instance_id) return true; #else const auto* serial_number = device.GetDict().FindString(kSerialNumberKey); const auto* port_serial_number = device_to_compare->GetDict().FindString(kSerialNumberKey); if (device.GetDict().FindInt(kVendorIdKey) != device_to_compare->GetDict().FindInt(kVendorIdKey) || device.GetDict().FindInt(kProductIdKey) != device_to_compare->GetDict().FindInt(kProductIdKey) || (serial_number && port_serial_number && *port_serial_number != *serial_number)) { return false; } #if BUILDFLAG(IS_MAC) const auto* usb_driver_key = device.GetDict().FindString(kUsbDriverKey); const auto* port_usb_driver_key = device_to_compare->GetDict().FindString(kUsbDriverKey); if (usb_driver_key && port_usb_driver_key && *usb_driver_key != *port_usb_driver_key) { return false; } #endif // BUILDFLAG(IS_MAC) return true; #endif // BUILDFLAG(IS_WIN) } return false; } bool ElectronBrowserContext::CheckDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return false; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return false; for (const auto& device_to_compare : origin_devices_it->second) { if (DoesDeviceMatch(device, device_to_compare.get(), permission_type)) return true; } return false; } // static ElectronBrowserContext* ElectronBrowserContext::From( const std::string& partition, bool in_memory, base::Value::Dict options) { PartitionKey key(partition, in_memory); ElectronBrowserContext* browser_context = browser_context_map()[key].get(); if (browser_context) { return browser_context; } auto* new_context = new ElectronBrowserContext(partition, in_memory, std::move(options)); browser_context_map()[key] = std::unique_ptr<ElectronBrowserContext>(new_context); return new_context; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,046
[Bug]: webContents.getUserAgent() is empty since 20.0.0-alpha.6
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.0-alpha.6 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version 20.0.0-alpha.5 ### Expected Behavior `webContents.getUserAgent()` returns a string with a user Agent ### Actual Behavior webContents.getUserAgent() returns an empty string ### Testcase Gist URL https://gist.github.com/33fd4a9ac6db6b28b1dcc5b765edb622 ### Additional Information In the console the user agent is printed in alpha.5, but empty in alpha.6. Looking at the diff between alpha.5 and alpha.6, this PR seems the likely cause: https://github.com/electron/electron/pull/34524 / #34481 It's worth noting that the renderer does have a filled-in userAgent.
https://github.com/electron/electron/issues/35046
https://github.com/electron/electron/pull/35069
8004cb8722c8d52f4cd553bbaea86750149e8ca4
9028bb79a85fedf64230c2f1c6a29ab072c98c20
2022-07-25T14:12:09Z
c++
2022-07-29T15:09:47Z
shell/browser/electron_browser_context.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_ELECTRON_BROWSER_CONTEXT_H_ #define ELECTRON_SHELL_BROWSER_ELECTRON_BROWSER_CONTEXT_H_ #include <map> #include <memory> #include <string> #include <vector> #include "base/memory/weak_ptr.h" #include "chrome/browser/predictors/preconnect_manager.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/resource_context.h" #include "electron/buildflags/buildflags.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/network/public/mojom/network_context.mojom.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" #include "shell/browser/media/media_device_id_salt.h" #include "third_party/blink/public/common/permissions/permission_utils.h" class PrefService; class ValueMapPrefStore; namespace network { class SharedURLLoaderFactory; } namespace storage { class SpecialStoragePolicy; } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) namespace extensions { class ElectronExtensionSystem; } #endif namespace electron { using DevicePermissionMap = std::map<blink::PermissionType, std::map<url::Origin, std::vector<std::unique_ptr<base::Value>>>>; class ElectronDownloadManagerDelegate; class ElectronPermissionManager; class CookieChangeNotifier; class ResolveProxyHelper; class WebViewManager; class ProtocolRegistry; class ElectronBrowserContext : public content::BrowserContext { public: // disable copy ElectronBrowserContext(const ElectronBrowserContext&) = delete; ElectronBrowserContext& operator=(const ElectronBrowserContext&) = delete; // partition_id => browser_context struct PartitionKey { std::string partition; bool in_memory; PartitionKey(const std::string& partition, bool in_memory) : partition(partition), in_memory(in_memory) {} bool operator<(const PartitionKey& other) const { if (partition == other.partition) return in_memory < other.in_memory; return partition < other.partition; } bool operator==(const PartitionKey& other) const { return (partition == other.partition) && (in_memory == other.in_memory); } }; using BrowserContextMap = std::map<PartitionKey, std::unique_ptr<ElectronBrowserContext>>; // Get or create the BrowserContext according to its |partition| and // |in_memory|. The |options| will be passed to constructor when there is no // existing BrowserContext. static ElectronBrowserContext* From(const std::string& partition, bool in_memory, base::Value::Dict options = {}); static BrowserContextMap& browser_context_map(); void SetUserAgent(const std::string& user_agent); std::string GetUserAgent() const; absl::optional<std::string> GetUserAgentOverride() const; bool CanUseHttpCache() const; int GetMaxCacheSize() const; ResolveProxyHelper* GetResolveProxyHelper(); predictors::PreconnectManager* GetPreconnectManager(); scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory(); // content::BrowserContext: base::FilePath GetPath() override; bool IsOffTheRecord() override; content::ResourceContext* GetResourceContext() override; std::unique_ptr<content::ZoomLevelDelegate> CreateZoomLevelDelegate( const base::FilePath& partition_path) override; content::PushMessagingService* GetPushMessagingService() override; content::SSLHostStateDelegate* GetSSLHostStateDelegate() override; content::BackgroundFetchDelegate* GetBackgroundFetchDelegate() override; content::BackgroundSyncController* GetBackgroundSyncController() override; content::BrowsingDataRemoverDelegate* GetBrowsingDataRemoverDelegate() override; std::string GetMediaDeviceIDSalt() override; content::DownloadManagerDelegate* GetDownloadManagerDelegate() override; content::BrowserPluginGuestManager* GetGuestManager() override; content::PlatformNotificationService* GetPlatformNotificationService() override; content::PermissionControllerDelegate* GetPermissionControllerDelegate() override; storage::SpecialStoragePolicy* GetSpecialStoragePolicy() override; content::ClientHintsControllerDelegate* GetClientHintsControllerDelegate() override; content::StorageNotificationService* GetStorageNotificationService() override; CookieChangeNotifier* cookie_change_notifier() const { return cookie_change_notifier_.get(); } PrefService* prefs() const { return prefs_.get(); } void set_in_memory_pref_store(ValueMapPrefStore* pref_store) { in_memory_pref_store_ = pref_store; } ValueMapPrefStore* in_memory_pref_store() const { return in_memory_pref_store_; } base::WeakPtr<ElectronBrowserContext> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ElectronExtensionSystem* extension_system() { // Guard usages of extension_system() with !IsOffTheRecord() // There is no extension system for in-memory sessions DCHECK(!IsOffTheRecord()); return extension_system_; } #endif ProtocolRegistry* protocol_registry() const { return protocol_registry_.get(); } void SetSSLConfig(network::mojom::SSLConfigPtr config); network::mojom::SSLConfigPtr GetSSLConfig(); void SetSSLConfigClient(mojo::Remote<network::mojom::SSLConfigClient> client); ~ElectronBrowserContext() override; // Grants |origin| access to |device|. // To be used in place of ObjectPermissionContextBase::GrantObjectPermission. void GrantDevicePermission(const url::Origin& origin, const base::Value& device, blink::PermissionType permissionType); // Revokes |origin| access to |device|. // To be used in place of ObjectPermissionContextBase::RevokeObjectPermission. void RevokeDevicePermission(const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type); // Returns the list of devices that |origin| has been granted permission to // access. To be used in place of // ObjectPermissionContextBase::GetGrantedObjects. bool CheckDevicePermission(const url::Origin& origin, const base::Value& device, blink::PermissionType permissionType); private: ElectronBrowserContext(const std::string& partition, bool in_memory, base::Value::Dict options); // Initialize pref registry. void InitPrefs(); bool DoesDeviceMatch(const base::Value& device, const base::Value* device_to_compare, blink::PermissionType permission_type); ValueMapPrefStore* in_memory_pref_store_ = nullptr; std::unique_ptr<content::ResourceContext> resource_context_; std::unique_ptr<CookieChangeNotifier> cookie_change_notifier_; std::unique_ptr<PrefService> prefs_; std::unique_ptr<ElectronDownloadManagerDelegate> download_manager_delegate_; std::unique_ptr<WebViewManager> guest_manager_; std::unique_ptr<ElectronPermissionManager> permission_manager_; std::unique_ptr<MediaDeviceIDSalt> media_device_id_salt_; scoped_refptr<ResolveProxyHelper> resolve_proxy_helper_; scoped_refptr<storage::SpecialStoragePolicy> storage_policy_; std::unique_ptr<predictors::PreconnectManager> preconnect_manager_; std::unique_ptr<ProtocolRegistry> protocol_registry_; absl::optional<std::string> user_agent_; base::FilePath path_; bool in_memory_ = false; bool use_cache_ = true; int max_cache_size_ = 0; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // Owned by the KeyedService system. extensions::ElectronExtensionSystem* extension_system_; #endif // Shared URLLoaderFactory. scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; network::mojom::SSLConfigPtr ssl_config_; mojo::Remote<network::mojom::SSLConfigClient> ssl_config_client_; // In-memory cache that holds objects that have been granted permissions. DevicePermissionMap granted_devices_; base::WeakPtrFactory<ElectronBrowserContext> weak_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_ELECTRON_BROWSER_CONTEXT_H_
closed
electron/electron
https://github.com/electron/electron
35,046
[Bug]: webContents.getUserAgent() is empty since 20.0.0-alpha.6
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.0-alpha.6 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version 20.0.0-alpha.5 ### Expected Behavior `webContents.getUserAgent()` returns a string with a user Agent ### Actual Behavior webContents.getUserAgent() returns an empty string ### Testcase Gist URL https://gist.github.com/33fd4a9ac6db6b28b1dcc5b765edb622 ### Additional Information In the console the user agent is printed in alpha.5, but empty in alpha.6. Looking at the diff between alpha.5 and alpha.6, this PR seems the likely cause: https://github.com/electron/electron/pull/34524 / #34481 It's worth noting that the renderer does have a filled-in userAgent.
https://github.com/electron/electron/issues/35046
https://github.com/electron/electron/pull/35069
8004cb8722c8d52f4cd553bbaea86750149e8ca4
9028bb79a85fedf64230c2f1c6a29ab072c98c20
2022-07-25T14:12:09Z
c++
2022-07-29T15:09:47Z
spec-main/api-web-contents-spec.ts
import { expect } from 'chai'; import { AddressInfo } from 'net'; import * as path from 'path'; import * as fs from 'fs'; import * as http from 'http'; import { BrowserWindow, ipcMain, webContents, session, WebContents, app, BrowserView } from 'electron/main'; import { emittedOnce } from './events-helpers'; import { closeAllWindows } from './window-helpers'; import { ifdescribe, delay, defer } from './spec-helpers'; const pdfjs = require('pdfjs-dist'); const fixturesPath = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixturesPath = path.resolve(__dirname, 'fixtures'); const features = process._linkedBinding('electron_common_features'); describe('webContents module', () => { describe('getAllWebContents() API', () => { afterEach(closeAllWindows); it('returns an array of web contents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html')); await emittedOnce(w.webContents, 'did-attach-webview'); w.webContents.openDevTools(); await emittedOnce(w.webContents, 'devtools-opened'); const all = webContents.getAllWebContents().sort((a, b) => { return a.id - b.id; }); expect(all).to.have.length(3); expect(all[0].getType()).to.equal('window'); expect(all[all.length - 2].getType()).to.equal('webview'); expect(all[all.length - 1].getType()).to.equal('remote'); }); }); describe('fromId()', () => { it('returns undefined for an unknown id', () => { expect(webContents.fromId(12345)).to.be.undefined(); }); }); describe('fromDevToolsTargetId()', () => { it('returns WebContents for attached DevTools target', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); try { await w.webContents.debugger.attach('1.3'); const { targetInfo } = await w.webContents.debugger.sendCommand('Target.getTargetInfo'); expect(webContents.fromDevToolsTargetId(targetInfo.targetId)).to.equal(w.webContents); } finally { await w.webContents.debugger.detach(); } }); it('returns undefined for an unknown id', () => { expect(webContents.fromDevToolsTargetId('nope')).to.be.undefined(); }); }); describe('will-prevent-unload event', function () { afterEach(closeAllWindows); it('does not emit if beforeunload returns undefined in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('does not emit if beforeunload returns undefined in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); view.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits if beforeunload returns false in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'will-prevent-unload'); }); it('emits if beforeunload returns false in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(view.webContents, 'will-prevent-unload'); }); it('supports calling preventDefault on will-prevent-unload events in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', event => event.preventDefault()); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); }); describe('webContents.send(channel, args...)', () => { afterEach(closeAllWindows); it('throws an error when the channel is missing', () => { const w = new BrowserWindow({ show: false }); expect(() => { (w.webContents.send as any)(); }).to.throw('Missing required channel argument'); expect(() => { w.webContents.send(null as any); }).to.throw('Missing required channel argument'); }); it('does not block node async APIs when sent before document is ready', (done) => { // Please reference https://github.com/electron/electron/issues/19368 if // this test fails. ipcMain.once('async-node-api-done', () => { done(); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, sandbox: false, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html')); setTimeout(() => { w.webContents.send('test'); }, 50); }); }); ifdescribe(features.isPrintingEnabled())('webContents.print()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('throws when invalid settings are passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print(true); }).to.throw('webContents.print(): Invalid print settings specified.'); }); it('throws when an invalid callback is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({}, true); }).to.throw('webContents.print(): Invalid optional callback provided.'); }); it('fails when an invalid deviceName is passed', (done) => { w.webContents.print({ deviceName: 'i-am-a-nonexistent-printer' }, (success, reason) => { expect(success).to.equal(false); expect(reason).to.match(/Invalid deviceName provided/); done(); }); }); it('throws when an invalid pageSize is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({ pageSize: 'i-am-a-bad-pagesize' }, () => {}); }).to.throw('Unsupported pageSize: i-am-a-bad-pagesize'); }); it('throws when an invalid custom pageSize is passed', () => { expect(() => { w.webContents.print({ pageSize: { width: 100, height: 200 } }); }).to.throw('height and width properties must be minimum 352 microns.'); }); it('does not crash with custom margins', () => { expect(() => { w.webContents.print({ silent: true, margins: { marginType: 'custom', top: 1, bottom: 1, left: 1, right: 1 } }); }).to.not.throw(); }); }); describe('webContents.executeJavaScript', () => { describe('in about:blank', () => { const expected = 'hello, world!'; const expectedErrorMsg = 'woops!'; const code = `(() => "${expected}")()`; const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`; const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`; const errorTypes = new Set([ Error, ReferenceError, EvalError, RangeError, SyntaxError, TypeError, URIError ]); let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false } }); await w.loadURL('about:blank'); }); after(closeAllWindows); it('resolves the returned promise with the result', async () => { const result = await w.webContents.executeJavaScript(code); expect(result).to.equal(expected); }); it('resolves the returned promise with the result if the code returns an asynchronous promise', async () => { const result = await w.webContents.executeJavaScript(asyncCode); expect(result).to.equal(expected); }); it('rejects the returned promise if an async error is thrown', async () => { await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg); }); it('rejects the returned promise with an error if an Error.prototype is thrown', async () => { for (const error of errorTypes) { await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`)) .to.eventually.be.rejectedWith(error); } }); }); describe('on a real page', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('works after page load and during subframe load', async () => { await w.loadURL(serverUrl); // initiate a sub-frame load, then try and execute script during it await w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/slow' document.body.appendChild(iframe) null // don't return the iframe `); await w.webContents.executeJavaScript('console.log(\'hello\')'); }); it('executes after page load', async () => { const executeJavaScript = w.webContents.executeJavaScript('(() => "test")()'); w.loadURL(serverUrl); const result = await executeJavaScript; expect(result).to.equal('test'); }); }); }); describe('webContents.executeJavaScriptInIsolatedWorld', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadURL('about:blank'); }); it('resolves the returned promise with the result', async () => { await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X = 123' }]); const isolatedResult = await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X' }]); const mainWorldResult = await w.webContents.executeJavaScript('window.X'); expect(isolatedResult).to.equal(123); expect(mainWorldResult).to.equal(undefined); }); }); describe('loadURL() promise API', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('resolves when done loading', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('resolves when done loading a file URL', async () => { await expect(w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'))).to.eventually.be.fulfilled(); }); it('rejects when failing to load a file URL', async () => { await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FILE_NOT_FOUND'); }); // Temporarily disable on WOA until // https://github.com/electron/electron/issues/20008 is resolved const testFn = (process.platform === 'win32' && process.arch === 'arm64' ? it.skip : it); testFn('rejects when loading fails due to DNS not resolved', async () => { await expect(w.loadURL('https://err.name.not.resolved')).to.eventually.be.rejected() .and.have.property('code', 'ERR_NAME_NOT_RESOLVED'); }); it('rejects when navigation is cancelled due to a bad scheme', async () => { await expect(w.loadURL('bad-scheme://foo')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FAILED'); }); it('sets appropriate error information on rejection', async () => { let err: any; try { await w.loadURL('file:non-existent'); } catch (e) { err = e; } expect(err).not.to.be.null(); expect(err.code).to.eql('ERR_FILE_NOT_FOUND'); expect(err.errno).to.eql(-6); expect(err.url).to.eql(process.platform === 'win32' ? 'file://non-existent/' : 'file:///non-existent'); }); it('rejects if the load is aborted', async () => { const s = http.createServer(() => { /* never complete the request */ }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = expect(w.loadURL(`http://127.0.0.1:${port}`)).to.eventually.be.rejectedWith(Error, /ERR_ABORTED/); // load a different file before the first load completes, causing the // first load to be aborted. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); await p; s.close(); }); it("doesn't reject when a subframe fails to load", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="http://err.name.not.resolved"></iframe>'); resp = res; // don't end the response yet }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = new Promise<void>(resolve => { w.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.end(); await main; s.close(); }); it("doesn't resolve when a subframe loads", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="about:blank"></iframe>'); resp = res; // don't end the response yet }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = new Promise<void>(resolve => { w.webContents.on('did-frame-finish-load', (event, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.destroy(); // cause the main request to fail await expect(main).to.eventually.be.rejected() .and.have.property('errno', -355); // ERR_INCOMPLETE_CHUNKED_ENCODING s.close(); }); }); describe('getFocusedWebContents() API', () => { afterEach(closeAllWindows); const testFn = (process.platform === 'win32' && process.arch === 'arm64' ? it.skip : it); testFn('returns the focused web contents', async () => { const w = new BrowserWindow({ show: true }); await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.id); const devToolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.openDevTools(); await devToolsOpened; expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.devToolsWebContents!.id); const devToolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.id); }); it('does not crash when called on a detached dev tools window', async () => { const w = new BrowserWindow({ show: true }); w.webContents.openDevTools({ mode: 'detach' }); w.webContents.inspectElement(100, 100); // For some reason we have to wait for two focused events...? await emittedOnce(w.webContents, 'devtools-focused'); expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); // Work around https://github.com/electron/electron/issues/19985 await delay(); const devToolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); }); }); describe('setDevToolsWebContents() API', () => { afterEach(closeAllWindows); it('sets arbitrary webContents as devtools', async () => { const w = new BrowserWindow({ show: false }); const devtools = new BrowserWindow({ show: false }); const promise = emittedOnce(devtools.webContents, 'dom-ready'); w.webContents.setDevToolsWebContents(devtools.webContents); w.webContents.openDevTools(); await promise; expect(devtools.webContents.getURL().startsWith('devtools://devtools')).to.be.true(); const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name'); expect(result).to.equal('InspectorFrontendHostImpl'); devtools.destroy(); }); }); describe('isFocused() API', () => { it('returns false when the window is hidden', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(w.isVisible()).to.be.false(); expect(w.webContents.isFocused()).to.be.false(); }); }); describe('isCurrentlyAudible() API', () => { afterEach(closeAllWindows); it('returns whether audio is playing', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await w.webContents.executeJavaScript(` window.context = new AudioContext // Start in suspended state, because of the // new web audio api policy. context.suspend() window.oscillator = context.createOscillator() oscillator.connect(context.destination) oscillator.start() `); let p = emittedOnce(w.webContents, '-audio-state-changed'); w.webContents.executeJavaScript('context.resume()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.true(); p = emittedOnce(w.webContents, '-audio-state-changed'); w.webContents.executeJavaScript('oscillator.stop()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.false(); }); }); describe('openDevTools() API', () => { afterEach(closeAllWindows); it('can show window with activation', async () => { const w = new BrowserWindow({ show: false }); const focused = emittedOnce(w, 'focus'); w.show(); await focused; expect(w.isFocused()).to.be.true(); const blurred = emittedOnce(w, 'blur'); w.webContents.openDevTools({ mode: 'detach', activate: true }); await Promise.all([ emittedOnce(w.webContents, 'devtools-opened'), emittedOnce(w.webContents, 'devtools-focused') ]); await blurred; expect(w.isFocused()).to.be.false(); }); it('can show window without activation', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: false }); await devtoolsOpened; expect(w.webContents.isDevToolsOpened()).to.be.true(); }); }); describe('before-input-event event', () => { afterEach(closeAllWindows); it('can prevent document keyboard events', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); const keyDown = new Promise(resolve => { ipcMain.once('keydown', (event, key) => resolve(key)); }); w.webContents.once('before-input-event', (event, input) => { if (input.key === 'a') event.preventDefault(); }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' }); expect(await keyDown).to.equal('b'); }); it('has the correct properties', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testBeforeInput = async (opts: any) => { const modifiers = []; if (opts.shift) modifiers.push('shift'); if (opts.control) modifiers.push('control'); if (opts.alt) modifiers.push('alt'); if (opts.meta) modifiers.push('meta'); if (opts.isAutoRepeat) modifiers.push('isAutoRepeat'); const p = emittedOnce(w.webContents, 'before-input-event'); w.webContents.sendInputEvent({ type: opts.type, keyCode: opts.keyCode, modifiers: modifiers as any }); const [, input] = await p; expect(input.type).to.equal(opts.type); expect(input.key).to.equal(opts.key); expect(input.code).to.equal(opts.code); expect(input.isAutoRepeat).to.equal(opts.isAutoRepeat); expect(input.shift).to.equal(opts.shift); expect(input.control).to.equal(opts.control); expect(input.alt).to.equal(opts.alt); expect(input.meta).to.equal(opts.meta); }; await testBeforeInput({ type: 'keyDown', key: 'A', code: 'KeyA', keyCode: 'a', shift: true, control: true, alt: true, meta: true, isAutoRepeat: true }); await testBeforeInput({ type: 'keyUp', key: '.', code: 'Period', keyCode: '.', shift: false, control: true, alt: true, meta: false, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: '!', code: 'Digit1', keyCode: '1', shift: true, control: false, alt: false, meta: true, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: 'Tab', code: 'Tab', keyCode: 'Tab', shift: false, control: true, alt: false, meta: false, isAutoRepeat: true }); }); }); // On Mac, zooming isn't done with the mouse wheel. ifdescribe(process.platform !== 'darwin')('zoom-changed', () => { afterEach(closeAllWindows); it('is emitted with the correct zoom-in info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: 1, wheelTicksX: 0, wheelTicksY: 1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await emittedOnce(w.webContents, 'zoom-changed'); expect(zoomDirection).to.equal('in'); }; await testZoomChanged(); }); it('is emitted with the correct zoom-out info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: -1, wheelTicksX: 0, wheelTicksY: -1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await emittedOnce(w.webContents, 'zoom-changed'); expect(zoomDirection).to.equal('out'); }; await testZoomChanged(); }); }); describe('sendInputEvent(event)', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); }); afterEach(closeAllWindows); it('can send keydown events', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can send keydown events with modifiers', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); it('can send keydown events with special keys', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab', modifiers: ['alt'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Tab'); expect(code).to.equal('Tab'); expect(keyCode).to.equal(9); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.true(); }); it('can send char events', async () => { const keypress = emittedOnce(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can send char events with modifiers', async () => { const keypress = emittedOnce(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); }); describe('insertCSS', () => { afterEach(closeAllWindows); it('supports inserting CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.webContents.insertCSS('body { background-repeat: round; }'); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('round'); }); it('supports removing inserted CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); const key = await w.webContents.insertCSS('body { background-repeat: round; }'); await w.webContents.removeInsertedCSS(key); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('repeat'); }); }); describe('inspectElement()', () => { afterEach(closeAllWindows); it('supports inspecting an element in the devtools', (done) => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.once('devtools-opened', () => { done(); }); w.webContents.inspectElement(10, 10); }); }); describe('startDrag({file, icon})', () => { it('throws errors for a missing file or a missing/empty icon', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.startDrag({ icon: path.join(fixturesPath, 'assets', 'logo.png') } as any); }).to.throw('Must specify either \'file\' or \'files\' option'); expect(() => { w.webContents.startDrag({ file: __filename } as any); }).to.throw('\'icon\' parameter is required'); expect(() => { w.webContents.startDrag({ file: __filename, icon: path.join(mainFixturesPath, 'blank.png') }); }).to.throw(/Failed to load image from path (.+)/); }); }); describe('focus APIs', () => { describe('focus()', () => { afterEach(closeAllWindows); it('does not blur the focused window when the web contents is hidden', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.show(); await w.loadURL('about:blank'); w.focus(); const child = new BrowserWindow({ show: false }); child.loadURL('about:blank'); child.webContents.focus(); const currentFocused = w.isFocused(); const childFocused = child.isFocused(); child.close(); expect(currentFocused).to.be.true(); expect(childFocused).to.be.false(); }); }); const moveFocusToDevTools = async (win: BrowserWindow) => { const devToolsOpened = emittedOnce(win.webContents, 'devtools-opened'); win.webContents.openDevTools({ mode: 'right' }); await devToolsOpened; win.webContents.devToolsWebContents!.focus(); }; describe('focus event', () => { afterEach(closeAllWindows); it('is triggered when web contents is focused', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await moveFocusToDevTools(w); const focusPromise = emittedOnce(w.webContents, 'focus'); w.webContents.focus(); await expect(focusPromise).to.eventually.be.fulfilled(); }); it('is triggered when BrowserWindow is focused', async () => { const window1 = new BrowserWindow({ show: false }); const window2 = new BrowserWindow({ show: false }); await Promise.all([ window1.loadURL('about:blank'), window2.loadURL('about:blank') ]); const focusPromise1 = emittedOnce(window1.webContents, 'focus'); const focusPromise2 = emittedOnce(window2.webContents, 'focus'); window1.showInactive(); window2.showInactive(); window1.focus(); await expect(focusPromise1).to.eventually.be.fulfilled(); window2.focus(); await expect(focusPromise2).to.eventually.be.fulfilled(); }); }); describe('blur event', () => { afterEach(closeAllWindows); it('is triggered when web contents is blurred', async () => { const w = new BrowserWindow({ show: true }); await w.loadURL('about:blank'); w.webContents.focus(); const blurPromise = emittedOnce(w.webContents, 'blur'); await moveFocusToDevTools(w); await expect(blurPromise).to.eventually.be.fulfilled(); }); }); }); describe('getOSProcessId()', () => { afterEach(closeAllWindows); it('returns a valid process id', async () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getOSProcessId()).to.equal(0); await w.loadURL('about:blank'); expect(w.webContents.getOSProcessId()).to.be.above(0); }); }); describe('getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns a valid stream id', () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getMediaSourceId(w.webContents)).to.be.a('string').that.is.not.empty(); }); }); describe('userAgent APIs', () => { it('can set the user agent (functions)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.getUserAgent(); w.webContents.setUserAgent('my-user-agent'); expect(w.webContents.getUserAgent()).to.equal('my-user-agent'); w.webContents.setUserAgent(userAgent); expect(w.webContents.getUserAgent()).to.equal(userAgent); }); it('can set the user agent (properties)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.userAgent; w.webContents.userAgent = 'my-user-agent'; expect(w.webContents.userAgent).to.equal('my-user-agent'); w.webContents.userAgent = userAgent; expect(w.webContents.userAgent).to.equal(userAgent); }); }); describe('audioMuted APIs', () => { it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.setAudioMuted(true); expect(w.webContents.isAudioMuted()).to.be.true(); w.webContents.setAudioMuted(false); expect(w.webContents.isAudioMuted()).to.be.false(); }); it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.audioMuted = true; expect(w.webContents.audioMuted).to.be.true(); w.webContents.audioMuted = false; expect(w.webContents.audioMuted).to.be.false(); }); }); describe('zoom api', () => { const hostZoomMap: Record<string, number> = { host1: 0.3, host2: 0.7, host3: 0.2 }; before(() => { const protocol = session.defaultSession.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { const response = `<script> const {ipcRenderer} = require('electron') ipcRenderer.send('set-zoom', window.location.hostname) ipcRenderer.on(window.location.hostname + '-zoom-set', () => { ipcRenderer.send(window.location.hostname + '-zoom-level') }) </script>`; callback({ data: response, mimeType: 'text/html' }); }); }); after(() => { const protocol = session.defaultSession.protocol; protocol.unregisterProtocol(standardScheme); }); afterEach(closeAllWindows); it('throws on an invalid zoomFactor', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { w.webContents.setZoomFactor(0.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); expect(() => { w.webContents.setZoomFactor(-2.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); }); it('can set the correct zoom level (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.getZoomLevel(); expect(zoomLevel).to.eql(0.0); w.webContents.setZoomLevel(0.5); const newZoomLevel = w.webContents.getZoomLevel(); expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.setZoomLevel(0); } }); it('can set the correct zoom level (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.eql(0.0); w.webContents.zoomLevel = 0.5; const newZoomLevel = w.webContents.zoomLevel; expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.zoomLevel = 0; } }); it('can set the correct zoom factor (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.getZoomFactor(); expect(zoomFactor).to.eql(1.0); w.webContents.setZoomFactor(0.5); const newZoomFactor = w.webContents.getZoomFactor(); expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.setZoomFactor(1.0); } }); it('can set the correct zoom factor (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.zoomFactor; expect(zoomFactor).to.eql(1.0); w.webContents.zoomFactor = 0.5; const newZoomFactor = w.webContents.zoomFactor; expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.zoomFactor = 1.0; } }); it('can persist zoom level across navigation', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let finalNavigation = false; ipcMain.on('set-zoom', (e, host) => { const zoomLevel = hostZoomMap[host]; if (!finalNavigation) w.webContents.zoomLevel = zoomLevel; e.sender.send(`${host}-zoom-set`); }); ipcMain.on('host1-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host1; expect(zoomLevel).to.equal(expectedZoomLevel); if (finalNavigation) { done(); } else { w.loadURL(`${standardScheme}://host2`); } } catch (e) { done(e); } }); ipcMain.once('host2-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host2; expect(zoomLevel).to.equal(expectedZoomLevel); finalNavigation = true; w.webContents.goBack(); } catch (e) { done(e); } }); w.loadURL(`${standardScheme}://host1`); }); it('can propagate zoom level across same session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false }); defer(() => { w2.setClosable(true); w2.close(); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel1).to.equal(zoomLevel2); }); it('cannot propagate zoom level across different session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false, webPreferences: { partition: 'temp' } }); const protocol = w2.webContents.session.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { callback('hello'); }); defer(() => { w2.setClosable(true); w2.close(); protocol.unregisterProtocol(standardScheme); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); it('can persist when it contains iframe', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { setTimeout(() => { res.end(); }, 200); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; const content = `<iframe src=${url}></iframe>`; w.webContents.on('did-frame-finish-load', (e, isMainFrame) => { if (!isMainFrame) { try { const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(2.0); w.webContents.zoomLevel = 0; done(); } catch (e) { done(e); } finally { server.close(); } } }); w.webContents.on('dom-ready', () => { w.webContents.zoomLevel = 2.0; }); w.loadURL(`data:text/html,${content}`); }); }); it('cannot propagate when used with webframe', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const w2 = new BrowserWindow({ show: false }); const temporaryZoomSet = emittedOnce(ipcMain, 'temporary-zoom-set'); w.loadFile(path.join(fixturesPath, 'pages', 'webframe-zoom.html')); await temporaryZoomSet; const finalZoomLevel = w.webContents.getZoomLevel(); await w2.loadFile(path.join(fixturesPath, 'pages', 'c.html')); const zoomLevel1 = w.webContents.zoomLevel; const zoomLevel2 = w2.webContents.zoomLevel; w2.setClosable(true); w2.close(); expect(zoomLevel1).to.equal(finalZoomLevel); expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); describe('with unique domains', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before((done) => { server = http.createServer((req, res) => { setTimeout(() => res.end('hey'), 0); }); server.listen(0, '127.0.0.1', () => { serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; crossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('cannot persist zoom level after navigation with webFrame', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const source = ` const {ipcRenderer, webFrame} = require('electron') webFrame.setZoomLevel(0.6) ipcRenderer.send('zoom-level-set', webFrame.getZoomLevel()) `; const zoomLevelPromise = emittedOnce(ipcMain, 'zoom-level-set'); await w.loadURL(serverUrl); await w.webContents.executeJavaScript(source); let [, zoomLevel] = await zoomLevelPromise; expect(zoomLevel).to.equal(0.6); const loadPromise = emittedOnce(w.webContents, 'did-finish-load'); await w.loadURL(crossSiteUrl); await loadPromise; zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(0); }); }); }); describe('webrtc ip policy api', () => { afterEach(closeAllWindows); it('can set and get webrtc ip policies', () => { const w = new BrowserWindow({ show: false }); const policies = [ 'default', 'default_public_interface_only', 'default_public_and_private_interfaces', 'disable_non_proxied_udp' ]; policies.forEach((policy) => { w.webContents.setWebRTCIPHandlingPolicy(policy as any); expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy); }); }); }); describe('render view deleted events', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before((done) => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${crossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else if (req.url === '/first-window-open') { res.end(`<html><script>window.open('${serverUrl}/second-window-open', 'first child');</script></html>`); } else if (req.url === '/second-window-open') { res.end('<html><script>window.open(\'wrong://url\', \'second child\');</script></html>'); } else { res.end(); } }; setTimeout(respond, 0); }); server.listen(0, '127.0.0.1', () => { serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; crossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); afterEach(closeAllWindows); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; w.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); w.webContents.on('did-finish-load', () => { w.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('current-render-view-deleted was emitted'); }); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const parentWindow = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; let childWindow: BrowserWindow | null = null; const destroyed = emittedOnce(parentWindow.webContents, 'destroyed'); const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; const childWindowCreated = new Promise<void>((resolve) => { app.once('browser-window-created', (event, window) => { childWindow = window; window.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); resolve(); }); }); parentWindow.loadURL(`${serverUrl}/first-window-open`); await childWindowCreated; childWindow!.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); parentWindow.close(); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('child window was destroyed'); }); it('emits current-render-view-deleted if the current RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; w.webContents.on('current-render-view-deleted' as any, () => { currentRenderViewDeletedEmitted = true; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.true('current-render-view-deleted wasn\'t emitted'); }); it('emits render-view-deleted if any RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let rvhDeletedCount = 0; w.webContents.on('render-view-deleted' as any, () => { rvhDeletedCount++; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; const expectedRenderViewDeletedEventCount = 1; expect(rvhDeletedCount).to.equal(expectedRenderViewDeletedEventCount, 'render-view-deleted wasn\'t emitted the expected nr. of times'); }); }); describe('setIgnoreMenuShortcuts(ignore)', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.setIgnoreMenuShortcuts(true); w.webContents.setIgnoreMenuShortcuts(false); }).to.not.throw(); }); }); const crashPrefs = [ { nodeIntegration: true }, { sandbox: true } ]; const nicePrefs = (o: any) => { let s = ''; for (const key of Object.keys(o)) { s += `${key}=${o[key]}, `; } return `(${s.slice(0, s.length - 2)})`; }; for (const prefs of crashPrefs) { describe(`crash with webPreferences ${nicePrefs(prefs)}`, () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); it('isCrashed() is false by default', () => { expect(w.webContents.isCrashed()).to.equal(false); }); it('forcefullyCrashRenderer() crashes the process with reason=killed||crashed', async () => { expect(w.webContents.isCrashed()).to.equal(false); const crashEvent = emittedOnce(w.webContents, 'render-process-gone'); w.webContents.forcefullyCrashRenderer(); const [, details] = await crashEvent; expect(details.reason === 'killed' || details.reason === 'crashed').to.equal(true, 'reason should be killed || crashed'); expect(w.webContents.isCrashed()).to.equal(true); }); it('a crashed process is recoverable with reload()', async () => { expect(w.webContents.isCrashed()).to.equal(false); w.webContents.forcefullyCrashRenderer(); w.webContents.reload(); expect(w.webContents.isCrashed()).to.equal(false); }); }); } // Destroying webContents in its event listener is going to crash when // Electron is built in Debug mode. describe('destroy()', () => { let server: http.Server; let serverUrl: string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/200': response.end(); break; default: done('unsupported endpoint'); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', url: '/200' }, { name: 'dom-ready', url: '/200' }, { name: 'did-stop-loading', url: '/200' }, { name: 'did-finish-load', url: '/200' }, // FIXME: Multiple Emit calls inside an observer assume that object // will be alive till end of the observer. Synchronous `destroy` api // violates this contract and crashes. { name: 'did-frame-finish-load', url: '/200' }, { name: 'did-fail-load', url: '/net-error' } ]; for (const e of events) { it(`should not crash when invoked synchronously inside ${e.name} handler`, async function () { // This test is flaky on Windows CI and we don't know why, but the // purpose of this test is to make sure Electron does not crash so it // is fine to retry this test for a few times. this.retries(3); const contents = (webContents as any).create() as WebContents; const originalEmit = contents.emit.bind(contents); contents.emit = (...args) => { return originalEmit(...args); }; contents.once(e.name as any, () => (contents as any).destroy()); const destroyed = emittedOnce(contents, 'destroyed'); contents.loadURL(serverUrl + e.url); await destroyed; }); } }); describe('did-change-theme-color event', () => { afterEach(closeAllWindows); it('is triggered with correct theme color', (done) => { const w = new BrowserWindow({ show: true }); let count = 0; w.webContents.on('did-change-theme-color', (e, color) => { try { if (count === 0) { count += 1; expect(color).to.equal('#FFEEDD'); w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); } else if (count === 1) { expect(color).to.be.null(); done(); } } catch (e) { done(e); } }); w.loadFile(path.join(fixturesPath, 'pages', 'theme-color.html')); }); }); describe('console-message event', () => { afterEach(closeAllWindows); it('is triggered with correct log message', (done) => { const w = new BrowserWindow({ show: true }); w.webContents.on('console-message', (e, level, message) => { // Don't just assert as Chromium might emit other logs that we should ignore. if (message === 'a') { done(); } }); w.loadFile(path.join(fixturesPath, 'pages', 'a.html')); }); }); describe('ipc-message event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends an asynchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); w.webContents.executeJavaScript(` require('electron').ipcRenderer.send('message', 'Hello World!') `); const [, channel, message] = await emittedOnce(w.webContents, 'ipc-message'); expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); }); }); describe('ipc-message-sync event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends a synchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); const promise: Promise<[string, string]> = new Promise(resolve => { w.webContents.once('ipc-message-sync', (event, channel, arg) => { event.returnValue = 'foobar' as any; resolve([channel, arg]); }); }); const result = await w.webContents.executeJavaScript(` require('electron').ipcRenderer.sendSync('message', 'Hello World!') `); const [channel, message] = await promise; expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); expect(result).to.equal('foobar'); }); }); describe('referrer', () => { afterEach(closeAllWindows); it('propagates referrer information to new target=_blank windows', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } finally { server.close(); } } res.end('<a id="a" href="/should_have_referrer" target="_blank">link</a>'); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/'; w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url); expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin'); return { action: 'allow' }; }); w.webContents.executeJavaScript('a.click()'); }); w.loadURL(url); }); }); // TODO(jeremy): window.open() in a real browser passes the referrer, but // our hacked-up window.open() shim doesn't. It should. xit('propagates referrer information to windows opened with window.open', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } } res.end(''); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/'; w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url); expect(details.referrer.policy).to.equal('no-referrer-when-downgrade'); return { action: 'allow' }; }); w.webContents.executeJavaScript('window.open(location.href + "should_have_referrer")'); }); w.loadURL(url); }); }); }); describe('webframe messages in sandboxed contents', () => { afterEach(closeAllWindows); it('responds to executeJavaScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const result = await w.webContents.executeJavaScript('37 + 5'); expect(result).to.equal(42); }); }); describe('preload-error event', () => { afterEach(closeAllWindows); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('is triggered when unhandled exception is thrown', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-exception.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('Hello World!'); }); it('is triggered on syntax errors', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-syntax.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('foobar is not defined'); }); it('is triggered when preload script loading fails', async () => { const preload = path.join(fixturesPath, 'module', 'preload-invalid.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.contain('preload-invalid.js'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('takeHeapSnapshot()', () => { afterEach(closeAllWindows); it('works with sandboxed renderers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot'); const cleanup = () => { try { fs.unlinkSync(filePath); } catch (e) { // ignore error } }; try { await w.webContents.takeHeapSnapshot(filePath); const stats = fs.statSync(filePath); expect(stats.size).not.to.be.equal(0); } finally { cleanup(); } }); it('fails with invalid file path', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const promise = w.webContents.takeHeapSnapshot(''); return expect(promise).to.be.eventually.rejectedWith(Error, 'takeHeapSnapshot failed'); }); }); describe('setBackgroundThrottling()', () => { afterEach(closeAllWindows); it('does not crash when allowing', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(true); }); it('does not crash when called via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); (w as any).setBackgroundThrottling(true); }); it('does not crash when disallowing', () => { const w = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: true } }); w.webContents.setBackgroundThrottling(false); }); }); describe('getBackgroundThrottling()', () => { afterEach(closeAllWindows); it('works via getter', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); expect(w.webContents.getBackgroundThrottling()).to.equal(false); w.webContents.setBackgroundThrottling(true); expect(w.webContents.getBackgroundThrottling()).to.equal(true); }); it('works via property', () => { const w = new BrowserWindow({ show: false }); w.webContents.backgroundThrottling = false; expect(w.webContents.backgroundThrottling).to.equal(false); w.webContents.backgroundThrottling = true; expect(w.webContents.backgroundThrottling).to.equal(true); }); it('works via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); (w as any).setBackgroundThrottling(false); expect((w as any).getBackgroundThrottling()).to.equal(false); (w as any).setBackgroundThrottling(true); expect((w as any).getBackgroundThrottling()).to.equal(true); }); }); ifdescribe(features.isPrintingEnabled())('getPrinters()', () => { afterEach(closeAllWindows); it('can get printer list', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const printers = w.webContents.getPrinters(); expect(printers).to.be.an('array'); }); }); ifdescribe(features.isPrintingEnabled())('getPrintersAsync()', () => { afterEach(closeAllWindows); it('can get printer list', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const printers = await w.webContents.getPrintersAsync(); expect(printers).to.be.an('array'); }); }); ifdescribe(features.isPrintingEnabled())('printToPDF()', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); }); afterEach(closeAllWindows); it('rejects on incorrectly typed parameters', async () => { const badTypes = { landscape: [], displayHeaderFooter: '123', printBackground: 2, scale: 'not-a-number', pageSize: 'IAmAPageSize', margins: 'terrible', pageRanges: { oops: 'im-not-the-right-key' }, headerTemplate: [1, 2, 3], footerTemplate: [4, 5, 6], preferCSSPageSize: 'no' }; // These will hard crash in Chromium unless we type-check for (const [key, value] of Object.entries(badTypes)) { const param = { [key]: value }; await expect(w.webContents.printToPDF(param)).to.eventually.be.rejected(); } }); it('can print to PDF', async () => { const data = await w.webContents.printToPDF({}); expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); }); it('does not crash when called multiple times in parallel', async () => { const promises = []; for (let i = 0; i < 3; i++) { promises.push(w.webContents.printToPDF({})); } const results = await Promise.all(promises); for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); it('does not crash when called multiple times in sequence', async () => { const results = []; for (let i = 0; i < 3; i++) { const result = await w.webContents.printToPDF({}); results.push(result); } for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); describe('using a large document', () => { beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf.html')); }); afterEach(closeAllWindows); it('respects custom settings', async () => { const data = await w.webContents.printToPDF({ pageRanges: '1-3', landscape: true }); const doc = await pdfjs.getDocument(data).promise; // Check that correct # of pages are rendered. expect(doc.numPages).to.equal(3); // Check that PDF is generated in landscape mode. const firstPage = await doc.getPage(1); const { width, height } = firstPage.getViewport({ scale: 100 }); expect(width).to.be.greaterThan(height); }); }); }); describe('PictureInPicture video', () => { afterEach(closeAllWindows); it('works as expected', async function () { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html')); if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) { this.skip(); } const result = await w.webContents.executeJavaScript( `runTest(${features.isPictureInPictureEnabled()})`, true); expect(result).to.be.true(); }); }); describe('Shared Workers', () => { afterEach(closeAllWindows); it('can get multiple shared workers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = emittedOnce(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); expect(sharedWorkers).to.have.lengthOf(2); expect(sharedWorkers[0].url).to.contain('shared-worker'); expect(sharedWorkers[1].url).to.contain('shared-worker'); }); it('can inspect a specific shared worker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = emittedOnce(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); const devtoolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.inspectSharedWorkerById(sharedWorkers[0].id); await devtoolsOpened; const devtoolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devtoolsClosed; }); }); describe('login event', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; let serverPort: number; let proxyServer: http.Server; let proxyServerPort: number; before((done) => { server = http.createServer((request, response) => { if (request.url === '/no-auth') { return response.end('ok'); } if (request.headers.authorization) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers.authorization); } response .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }) .end('401'); }).listen(0, '127.0.0.1', () => { serverPort = (server.address() as AddressInfo).port; serverUrl = `http://127.0.0.1:${serverPort}`; done(); }); }); before((done) => { proxyServer = http.createServer((request, response) => { if (request.headers['proxy-authorization']) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers['proxy-authorization']); } response .writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }) .end(); }).listen(0, '127.0.0.1', () => { proxyServerPort = (proxyServer.address() as AddressInfo).port; done(); }); }); afterEach(async () => { await session.defaultSession.clearAuthCache(); }); after(() => { server.close(); proxyServer.close(); }); it('is emitted when navigating', async () => { const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(serverUrl + '/'); expect(eventAuthInfo.isProxy).to.be.false(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(serverPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('is emitted when a proxy requests authorization', async () => { const customSession = session.fromPartition(`${Math.random()}`); await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' }); const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(`${serverUrl}/no-auth`); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`); expect(eventAuthInfo.isProxy).to.be.true(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(proxyServerPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('cancels authentication when callback is called with no arguments', async () => { const w = new BrowserWindow({ show: false }); w.webContents.on('login', (event, request, authInfo, cb) => { event.preventDefault(); cb(); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal('401'); }); }); describe('page-title-updated event', () => { afterEach(closeAllWindows); it('is emitted with a full title for pages with no navigation', async () => { const bw = new BrowserWindow({ show: false }); await bw.loadURL('about:blank'); bw.webContents.executeJavaScript('child = window.open("", "", "show=no"); null'); const [, child] = await emittedOnce(app, 'web-contents-created'); bw.webContents.executeJavaScript('child.document.title = "new title"'); const [, title] = await emittedOnce(child, 'page-title-updated'); expect(title).to.equal('new title'); }); }); describe('crashed event', () => { it('does not crash main process when destroying WebContents in it', (done) => { const contents = (webContents as any).create({ nodeIntegration: true }); contents.once('crashed', () => { contents.destroy(); done(); }); contents.loadURL('about:blank').then(() => contents.forcefullyCrashRenderer()); }); }); describe('context-menu event', () => { afterEach(closeAllWindows); it('emits when right-clicked in page', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const promise = emittedOnce(w.webContents, 'context-menu'); // Simulate right-click to create context-menu event. const opts = { x: 0, y: 0, button: 'right' as any }; w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' }); w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' }); const [, params] = await promise; expect(params.pageURL).to.equal(w.webContents.getURL()); expect(params.frame).to.be.an('object'); expect(params.x).to.be.a('number'); expect(params.y).to.be.a('number'); }); }); it('emits a cancelable event before creating a child webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); w.webContents.on('-will-add-new-contents' as any, (event: any, url: any) => { expect(url).to.equal('about:blank'); event.preventDefault(); }); let wasCalled = false; w.webContents.on('new-window' as any, () => { wasCalled = true; }); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('window.open(\'about:blank\')'); await new Promise((resolve) => { process.nextTick(resolve); }); expect(wasCalled).to.equal(false); await closeAllWindows(); }); });
closed
electron/electron
https://github.com/electron/electron
34,450
[Bug]: File extension is missing 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 bug report that matches the one I want to file, without success. ### Electron Version 18.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 - 10.0.19042 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When saving a file, the file type should be correctly defined and the filename should include the extension on the operating system so that the correct program is launch when double-clicking it ### Actual Behavior The extension is missing. ![image](https://user-images.githubusercontent.com/797545/172208806-a15f11d5-5ac9-497c-a6ce-ee0ffe4d76a5.png) Here is the code we are using: ```js const a = document.createElement('a') a.type = getMimeType(name) a.href = `data:${a.type || 'text/plain'};base64,${base64}` a.download = name a.click() ``` I'll try to add a fiddle later ### Testcase Gist URL https://gist.github.com/c07b1efe128ba059d0fad7ebeb7a94cb ### Additional Information This is reproducible only on Windows
https://github.com/electron/electron/issues/34450
https://github.com/electron/electron/pull/34723
0d36c0cdc6fe616fe235e0f1aa32b691054d503d
0cdc946b2708c3592ec1c413f28a28442c843183
2022-06-06T18:32:43Z
c++
2022-08-02T00:40:17Z
shell/browser/electron_download_manager_delegate.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_download_manager_delegate.h" #include <string> #include <tuple> #include <utility> #include "base/bind.h" #include "base/files/file_util.h" #include "base/task/thread_pool.h" #include "base/threading/thread_restrictions.h" #include "chrome/common/pref_names.h" #include "components/download/public/common/download_danger_type.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_item_utils.h" #include "content/public/browser/download_manager.h" #include "net/base/filename_util.h" #include "shell/browser/api/electron_api_download_item.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_window.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/web_contents_preferences.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/options_switches.h" namespace electron { namespace { // Generate default file path to save the download. base::FilePath CreateDownloadPath(const GURL& url, const std::string& content_disposition, const std::string& suggested_filename, const std::string& mime_type, const base::FilePath& last_saved_directory, const base::FilePath& default_download_path) { auto generated_name = net::GenerateFileName(url, content_disposition, std::string(), suggested_filename, mime_type, "download"); base::FilePath download_path; // If the last saved directory is a non-empty existent path, use it as the // default. if (last_saved_directory.empty() || !base::PathExists(last_saved_directory)) { download_path = default_download_path; if (!base::PathExists(download_path)) base::CreateDirectory(download_path); } else { // Otherwise use the global default. download_path = last_saved_directory; } return download_path.Append(generated_name); } } // namespace ElectronDownloadManagerDelegate::ElectronDownloadManagerDelegate( content::DownloadManager* manager) : download_manager_(manager) {} ElectronDownloadManagerDelegate::~ElectronDownloadManagerDelegate() { if (download_manager_) { DCHECK_EQ(static_cast<content::DownloadManagerDelegate*>(this), download_manager_->GetDelegate()); download_manager_->SetDelegate(nullptr); download_manager_ = nullptr; } } void ElectronDownloadManagerDelegate::GetItemSavePath( download::DownloadItem* item, base::FilePath* path) { api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item); if (download) *path = download->GetSavePath(); } void ElectronDownloadManagerDelegate::GetItemSaveDialogOptions( download::DownloadItem* item, file_dialog::DialogSettings* options) { api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item); if (download) *options = download->GetSaveDialogOptions(); } void ElectronDownloadManagerDelegate::OnDownloadPathGenerated( uint32_t download_id, content::DownloadTargetCallback callback, const base::FilePath& default_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); base::ThreadRestrictions::ScopedAllowIO allow_io; auto* item = download_manager_->GetDownload(download_id); if (!item) return; NativeWindow* window = nullptr; content::WebContents* web_contents = content::DownloadItemUtils::GetWebContents(item); auto* relay = web_contents ? NativeWindowRelay::FromWebContents(web_contents) : nullptr; if (relay) window = relay->GetNativeWindow(); // Show save dialog if save path was not set already on item base::FilePath path; GetItemSavePath(item, &path); if (path.empty()) { file_dialog::DialogSettings settings; GetItemSaveDialogOptions(item, &settings); if (!settings.parent_window) settings.parent_window = window; if (settings.title.empty()) settings.title = item->GetURL().spec(); if (settings.default_path.empty()) settings.default_path = default_path; auto* web_preferences = WebContentsPreferences::From(web_contents); const bool offscreen = !web_preferences || web_preferences->IsOffscreen(); settings.force_detached = offscreen; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::Promise<gin_helper::Dictionary> dialog_promise(isolate); auto dialog_callback = base::BindOnce( &ElectronDownloadManagerDelegate::OnDownloadSaveDialogDone, base::Unretained(this), download_id, std::move(callback)); std::ignore = dialog_promise.Then(std::move(dialog_callback)); file_dialog::ShowSaveDialog(settings, std::move(dialog_promise)); } else { std::move(callback).Run( path, download::DownloadItem::TARGET_DISPOSITION_PROMPT, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, item->GetMixedContentStatus(), path, base::FilePath(), std::string() /*mime_type*/, download::DOWNLOAD_INTERRUPT_REASON_NONE); } } void ElectronDownloadManagerDelegate::OnDownloadSaveDialogDone( uint32_t download_id, content::DownloadTargetCallback download_callback, gin_helper::Dictionary result) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto* item = download_manager_->GetDownload(download_id); if (!item) return; bool canceled = true; result.Get("canceled", &canceled); base::FilePath path; if (!canceled) { if (result.Get("filePath", &path)) { // Remember the last selected download directory. last_saved_directory_ = path.DirName(); api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item); if (download) download->SetSavePath(path); } } // Running the DownloadTargetCallback with an empty FilePath signals that the // download should be cancelled. If user cancels the file save dialog, run // the callback with empty FilePath. const auto interrupt_reason = path.empty() ? download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED : download::DOWNLOAD_INTERRUPT_REASON_NONE; std::move(download_callback) .Run(path, download::DownloadItem::TARGET_DISPOSITION_PROMPT, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, item->GetMixedContentStatus(), path, base::FilePath(), std::string() /*mime_type*/, interrupt_reason); } void ElectronDownloadManagerDelegate::Shutdown() { weak_ptr_factory_.InvalidateWeakPtrs(); download_manager_ = nullptr; } bool ElectronDownloadManagerDelegate::DetermineDownloadTarget( download::DownloadItem* download, content::DownloadTargetCallback* callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!download->GetForcedFilePath().empty()) { std::move(*callback).Run( download->GetForcedFilePath(), download::DownloadItem::TARGET_DISPOSITION_OVERWRITE, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download::DownloadItem::MixedContentStatus::UNKNOWN, download->GetForcedFilePath(), base::FilePath(), std::string() /*mime_type*/, download::DOWNLOAD_INTERRUPT_REASON_NONE); return true; } // Try to get the save path from JS wrapper. base::FilePath save_path; GetItemSavePath(download, &save_path); if (!save_path.empty()) { std::move(*callback).Run( save_path, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download::DownloadItem::MixedContentStatus::UNKNOWN, save_path, base::FilePath(), std::string() /*mime_type*/, download::DOWNLOAD_INTERRUPT_REASON_NONE); return true; } auto* browser_context = static_cast<ElectronBrowserContext*>( download_manager_->GetBrowserContext()); base::FilePath default_download_path = browser_context->prefs()->GetFilePath(prefs::kDownloadDefaultDirectory); base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&CreateDownloadPath, download->GetURL(), download->GetContentDisposition(), download->GetSuggestedFilename(), download->GetMimeType(), last_saved_directory_, default_download_path), base::BindOnce(&ElectronDownloadManagerDelegate::OnDownloadPathGenerated, weak_ptr_factory_.GetWeakPtr(), download->GetId(), std::move(*callback))); return true; } bool ElectronDownloadManagerDelegate::ShouldOpenDownload( download::DownloadItem* download, content::DownloadOpenDelayedCallback callback) { return true; } void ElectronDownloadManagerDelegate::GetNextId( content::DownloadIdCallback callback) { static uint32_t next_id = download::DownloadItem::kInvalidId + 1; std::move(callback).Run(next_id++); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,450
[Bug]: File extension is missing 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 bug report that matches the one I want to file, without success. ### Electron Version 18.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 - 10.0.19042 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When saving a file, the file type should be correctly defined and the filename should include the extension on the operating system so that the correct program is launch when double-clicking it ### Actual Behavior The extension is missing. ![image](https://user-images.githubusercontent.com/797545/172208806-a15f11d5-5ac9-497c-a6ce-ee0ffe4d76a5.png) Here is the code we are using: ```js const a = document.createElement('a') a.type = getMimeType(name) a.href = `data:${a.type || 'text/plain'};base64,${base64}` a.download = name a.click() ``` I'll try to add a fiddle later ### Testcase Gist URL https://gist.github.com/c07b1efe128ba059d0fad7ebeb7a94cb ### Additional Information This is reproducible only on Windows
https://github.com/electron/electron/issues/34450
https://github.com/electron/electron/pull/34723
0d36c0cdc6fe616fe235e0f1aa32b691054d503d
0cdc946b2708c3592ec1c413f28a28442c843183
2022-06-06T18:32:43Z
c++
2022-08-02T00:40:17Z
shell/browser/electron_download_manager_delegate.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_download_manager_delegate.h" #include <string> #include <tuple> #include <utility> #include "base/bind.h" #include "base/files/file_util.h" #include "base/task/thread_pool.h" #include "base/threading/thread_restrictions.h" #include "chrome/common/pref_names.h" #include "components/download/public/common/download_danger_type.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_item_utils.h" #include "content/public/browser/download_manager.h" #include "net/base/filename_util.h" #include "shell/browser/api/electron_api_download_item.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_window.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/web_contents_preferences.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/options_switches.h" namespace electron { namespace { // Generate default file path to save the download. base::FilePath CreateDownloadPath(const GURL& url, const std::string& content_disposition, const std::string& suggested_filename, const std::string& mime_type, const base::FilePath& last_saved_directory, const base::FilePath& default_download_path) { auto generated_name = net::GenerateFileName(url, content_disposition, std::string(), suggested_filename, mime_type, "download"); base::FilePath download_path; // If the last saved directory is a non-empty existent path, use it as the // default. if (last_saved_directory.empty() || !base::PathExists(last_saved_directory)) { download_path = default_download_path; if (!base::PathExists(download_path)) base::CreateDirectory(download_path); } else { // Otherwise use the global default. download_path = last_saved_directory; } return download_path.Append(generated_name); } } // namespace ElectronDownloadManagerDelegate::ElectronDownloadManagerDelegate( content::DownloadManager* manager) : download_manager_(manager) {} ElectronDownloadManagerDelegate::~ElectronDownloadManagerDelegate() { if (download_manager_) { DCHECK_EQ(static_cast<content::DownloadManagerDelegate*>(this), download_manager_->GetDelegate()); download_manager_->SetDelegate(nullptr); download_manager_ = nullptr; } } void ElectronDownloadManagerDelegate::GetItemSavePath( download::DownloadItem* item, base::FilePath* path) { api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item); if (download) *path = download->GetSavePath(); } void ElectronDownloadManagerDelegate::GetItemSaveDialogOptions( download::DownloadItem* item, file_dialog::DialogSettings* options) { api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item); if (download) *options = download->GetSaveDialogOptions(); } void ElectronDownloadManagerDelegate::OnDownloadPathGenerated( uint32_t download_id, content::DownloadTargetCallback callback, const base::FilePath& default_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); base::ThreadRestrictions::ScopedAllowIO allow_io; auto* item = download_manager_->GetDownload(download_id); if (!item) return; NativeWindow* window = nullptr; content::WebContents* web_contents = content::DownloadItemUtils::GetWebContents(item); auto* relay = web_contents ? NativeWindowRelay::FromWebContents(web_contents) : nullptr; if (relay) window = relay->GetNativeWindow(); // Show save dialog if save path was not set already on item base::FilePath path; GetItemSavePath(item, &path); if (path.empty()) { file_dialog::DialogSettings settings; GetItemSaveDialogOptions(item, &settings); if (!settings.parent_window) settings.parent_window = window; if (settings.title.empty()) settings.title = item->GetURL().spec(); if (settings.default_path.empty()) settings.default_path = default_path; auto* web_preferences = WebContentsPreferences::From(web_contents); const bool offscreen = !web_preferences || web_preferences->IsOffscreen(); settings.force_detached = offscreen; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::Promise<gin_helper::Dictionary> dialog_promise(isolate); auto dialog_callback = base::BindOnce( &ElectronDownloadManagerDelegate::OnDownloadSaveDialogDone, base::Unretained(this), download_id, std::move(callback)); std::ignore = dialog_promise.Then(std::move(dialog_callback)); file_dialog::ShowSaveDialog(settings, std::move(dialog_promise)); } else { std::move(callback).Run( path, download::DownloadItem::TARGET_DISPOSITION_PROMPT, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, item->GetMixedContentStatus(), path, base::FilePath(), std::string() /*mime_type*/, download::DOWNLOAD_INTERRUPT_REASON_NONE); } } void ElectronDownloadManagerDelegate::OnDownloadSaveDialogDone( uint32_t download_id, content::DownloadTargetCallback download_callback, gin_helper::Dictionary result) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto* item = download_manager_->GetDownload(download_id); if (!item) return; bool canceled = true; result.Get("canceled", &canceled); base::FilePath path; if (!canceled) { if (result.Get("filePath", &path)) { // Remember the last selected download directory. last_saved_directory_ = path.DirName(); api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item); if (download) download->SetSavePath(path); } } // Running the DownloadTargetCallback with an empty FilePath signals that the // download should be cancelled. If user cancels the file save dialog, run // the callback with empty FilePath. const auto interrupt_reason = path.empty() ? download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED : download::DOWNLOAD_INTERRUPT_REASON_NONE; std::move(download_callback) .Run(path, download::DownloadItem::TARGET_DISPOSITION_PROMPT, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, item->GetMixedContentStatus(), path, base::FilePath(), std::string() /*mime_type*/, interrupt_reason); } void ElectronDownloadManagerDelegate::Shutdown() { weak_ptr_factory_.InvalidateWeakPtrs(); download_manager_ = nullptr; } bool ElectronDownloadManagerDelegate::DetermineDownloadTarget( download::DownloadItem* download, content::DownloadTargetCallback* callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!download->GetForcedFilePath().empty()) { std::move(*callback).Run( download->GetForcedFilePath(), download::DownloadItem::TARGET_DISPOSITION_OVERWRITE, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download::DownloadItem::MixedContentStatus::UNKNOWN, download->GetForcedFilePath(), base::FilePath(), std::string() /*mime_type*/, download::DOWNLOAD_INTERRUPT_REASON_NONE); return true; } // Try to get the save path from JS wrapper. base::FilePath save_path; GetItemSavePath(download, &save_path); if (!save_path.empty()) { std::move(*callback).Run( save_path, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download::DownloadItem::MixedContentStatus::UNKNOWN, save_path, base::FilePath(), std::string() /*mime_type*/, download::DOWNLOAD_INTERRUPT_REASON_NONE); return true; } auto* browser_context = static_cast<ElectronBrowserContext*>( download_manager_->GetBrowserContext()); base::FilePath default_download_path = browser_context->prefs()->GetFilePath(prefs::kDownloadDefaultDirectory); base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&CreateDownloadPath, download->GetURL(), download->GetContentDisposition(), download->GetSuggestedFilename(), download->GetMimeType(), last_saved_directory_, default_download_path), base::BindOnce(&ElectronDownloadManagerDelegate::OnDownloadPathGenerated, weak_ptr_factory_.GetWeakPtr(), download->GetId(), std::move(*callback))); return true; } bool ElectronDownloadManagerDelegate::ShouldOpenDownload( download::DownloadItem* download, content::DownloadOpenDelayedCallback callback) { return true; } void ElectronDownloadManagerDelegate::GetNextId( content::DownloadIdCallback callback) { static uint32_t next_id = download::DownloadItem::kInvalidId + 1; std::move(callback).Run(next_id++); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,364
[Bug]: WCO on Windows don't respond to touch events
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4.4 ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior WCO on Windows respond to touch events ### Actual Behavior WCO on Windows do not respond to touch events ### Testcase Gist URL _No response_ ### Additional Information The same fiddle repro applies from this comment https://github.com/electron/electron/issues/34129#issuecomment-1124398574
https://github.com/electron/electron/issues/34364
https://github.com/electron/electron/pull/35117
0cdc946b2708c3592ec1c413f28a28442c843183
e3893632e7e7cf39fff160946fdc19a7ae058da2
2022-05-27T20:46:19Z
c++
2022-08-02T03:13:58Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch v8_context_snapshot_generator.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch don_t_use_potentially_null_getwebframe_-_view_when_get_blink.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch fix_allow_guest_webcontents_to_enter_fullscreen.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch
closed
electron/electron
https://github.com/electron/electron
34,364
[Bug]: WCO on Windows don't respond to touch events
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4.4 ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior WCO on Windows respond to touch events ### Actual Behavior WCO on Windows do not respond to touch events ### Testcase Gist URL _No response_ ### Additional Information The same fiddle repro applies from this comment https://github.com/electron/electron/issues/34129#issuecomment-1124398574
https://github.com/electron/electron/issues/34364
https://github.com/electron/electron/pull/35117
0cdc946b2708c3592ec1c413f28a28442c843183
e3893632e7e7cf39fff160946fdc19a7ae058da2
2022-05-27T20:46:19Z
c++
2022-08-02T03:13:58Z
patches/chromium/chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch
closed
electron/electron
https://github.com/electron/electron
34,364
[Bug]: WCO on Windows don't respond to touch events
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4.4 ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior WCO on Windows respond to touch events ### Actual Behavior WCO on Windows do not respond to touch events ### Testcase Gist URL _No response_ ### Additional Information The same fiddle repro applies from this comment https://github.com/electron/electron/issues/34129#issuecomment-1124398574
https://github.com/electron/electron/issues/34364
https://github.com/electron/electron/pull/35117
0cdc946b2708c3592ec1c413f28a28442c843183
e3893632e7e7cf39fff160946fdc19a7ae058da2
2022-05-27T20:46:19Z
c++
2022-08-02T03:13:58Z
shell/browser/ui/win/electron_desktop_window_tree_host_win.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/ui/win/electron_desktop_window_tree_host_win.h" #include "base/win/windows_version.h" #include "electron/buildflags/buildflags.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/win/dark_mode.h" #include "ui/base/win/hwnd_metrics.h" #include "ui/base/win/shell.h" namespace electron { ElectronDesktopWindowTreeHostWin::ElectronDesktopWindowTreeHostWin( NativeWindowViews* native_window_view, views::DesktopNativeWidgetAura* desktop_native_widget_aura) : views::DesktopWindowTreeHostWin(native_window_view->widget(), desktop_native_widget_aura), native_window_view_(native_window_view) {} ElectronDesktopWindowTreeHostWin::~ElectronDesktopWindowTreeHostWin() = default; bool ElectronDesktopWindowTreeHostWin::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { const bool dark_mode_supported = win::IsDarkModeSupported(); if (dark_mode_supported && message == WM_NCCREATE) { win::SetDarkModeForWindow(GetAcceleratedWidget()); ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); } else if (dark_mode_supported && message == WM_DESTROY) { ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); } return native_window_view_->PreHandleMSG(message, w_param, l_param, result); } bool ElectronDesktopWindowTreeHostWin::ShouldPaintAsActive() const { // Tell Chromium to use system default behavior when rendering inactive // titlebar, otherwise it would render inactive titlebar as active under // some cases. // See also https://github.com/electron/electron/issues/24647. return false; } bool ElectronDesktopWindowTreeHostWin::HasNativeFrame() const { // Since we never use chromium's titlebar implementation, we can just say // that we use a native titlebar. This will disable the repaint locking when // DWM composition is disabled. // See also https://github.com/electron/electron/issues/1821. return !ui::win::IsAeroGlassEnabled(); } bool ElectronDesktopWindowTreeHostWin::GetDwmFrameInsetsInPixels( gfx::Insets* insets) const { // Set DWMFrameInsets to prevent maximized frameless window from bleeding // into other monitors. if (IsMaximized() && !native_window_view_->has_frame()) { // This would be equivalent to calling: // DwmExtendFrameIntoClientArea({0, 0, 0, 0}); // // which means do not extend window frame into client area. It is almost // a no-op, but it can tell Windows to not extend the window frame to be // larger than current workspace. // // See also: // https://devblogs.microsoft.com/oldnewthing/20150304-00/?p=44543 *insets = gfx::Insets(); return true; } return false; } bool ElectronDesktopWindowTreeHostWin::GetClientAreaInsets( gfx::Insets* insets, HMONITOR monitor) const { // Windows by default extends the maximized window slightly larger than // current workspace, for frameless window since the standard frame has been // removed, the client area would then be drew outside current workspace. // // Indenting the client area can fix this behavior. if (IsMaximized() && !native_window_view_->has_frame()) { // The insets would be eventually passed to WM_NCCALCSIZE, which takes // the metrics under the DPI of _main_ monitor instead of current monitor. // // Please make sure you tested maximized frameless window under multiple // monitors with different DPIs before changing this code. const int thickness = ::GetSystemMetrics(SM_CXSIZEFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER); *insets = gfx::Insets::TLBR(thickness, thickness, thickness, thickness); return true; } return false; } void ElectronDesktopWindowTreeHostWin::OnNativeThemeUpdated( ui::NativeTheme* observed_theme) { win::SetDarkModeForWindow(GetAcceleratedWidget()); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,364
[Bug]: WCO on Windows don't respond to touch events
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4.4 ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior WCO on Windows respond to touch events ### Actual Behavior WCO on Windows do not respond to touch events ### Testcase Gist URL _No response_ ### Additional Information The same fiddle repro applies from this comment https://github.com/electron/electron/issues/34129#issuecomment-1124398574
https://github.com/electron/electron/issues/34364
https://github.com/electron/electron/pull/35117
0cdc946b2708c3592ec1c413f28a28442c843183
e3893632e7e7cf39fff160946fdc19a7ae058da2
2022-05-27T20:46:19Z
c++
2022-08-02T03:13:58Z
shell/browser/ui/win/electron_desktop_window_tree_host_win.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_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_ #define ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_ #include <windows.h> #include "shell/browser/native_window_views.h" #include "ui/views/widget/desktop_aura/desktop_window_tree_host_win.h" namespace electron { class ElectronDesktopWindowTreeHostWin : public views::DesktopWindowTreeHostWin, public ::ui::NativeThemeObserver { public: ElectronDesktopWindowTreeHostWin( NativeWindowViews* native_window_view, views::DesktopNativeWidgetAura* desktop_native_widget_aura); ~ElectronDesktopWindowTreeHostWin() override; // disable copy ElectronDesktopWindowTreeHostWin(const ElectronDesktopWindowTreeHostWin&) = delete; ElectronDesktopWindowTreeHostWin& operator=( const ElectronDesktopWindowTreeHostWin&) = delete; protected: bool PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) override; bool ShouldPaintAsActive() const override; bool HasNativeFrame() const override; bool GetDwmFrameInsetsInPixels(gfx::Insets* insets) const override; bool GetClientAreaInsets(gfx::Insets* insets, HMONITOR monitor) const override; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override; private: NativeWindowViews* native_window_view_; // weak ref }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_
closed
electron/electron
https://github.com/electron/electron
34,364
[Bug]: WCO on Windows don't respond to touch events
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4.4 ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior WCO on Windows respond to touch events ### Actual Behavior WCO on Windows do not respond to touch events ### Testcase Gist URL _No response_ ### Additional Information The same fiddle repro applies from this comment https://github.com/electron/electron/issues/34129#issuecomment-1124398574
https://github.com/electron/electron/issues/34364
https://github.com/electron/electron/pull/35117
0cdc946b2708c3592ec1c413f28a28442c843183
e3893632e7e7cf39fff160946fdc19a7ae058da2
2022-05-27T20:46:19Z
c++
2022-08-02T03:13:58Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch v8_context_snapshot_generator.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch don_t_use_potentially_null_getwebframe_-_view_when_get_blink.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch fix_allow_guest_webcontents_to_enter_fullscreen.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch
closed
electron/electron
https://github.com/electron/electron
34,364
[Bug]: WCO on Windows don't respond to touch events
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4.4 ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior WCO on Windows respond to touch events ### Actual Behavior WCO on Windows do not respond to touch events ### Testcase Gist URL _No response_ ### Additional Information The same fiddle repro applies from this comment https://github.com/electron/electron/issues/34129#issuecomment-1124398574
https://github.com/electron/electron/issues/34364
https://github.com/electron/electron/pull/35117
0cdc946b2708c3592ec1c413f28a28442c843183
e3893632e7e7cf39fff160946fdc19a7ae058da2
2022-05-27T20:46:19Z
c++
2022-08-02T03:13:58Z
patches/chromium/chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch
closed
electron/electron
https://github.com/electron/electron
34,364
[Bug]: WCO on Windows don't respond to touch events
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4.4 ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior WCO on Windows respond to touch events ### Actual Behavior WCO on Windows do not respond to touch events ### Testcase Gist URL _No response_ ### Additional Information The same fiddle repro applies from this comment https://github.com/electron/electron/issues/34129#issuecomment-1124398574
https://github.com/electron/electron/issues/34364
https://github.com/electron/electron/pull/35117
0cdc946b2708c3592ec1c413f28a28442c843183
e3893632e7e7cf39fff160946fdc19a7ae058da2
2022-05-27T20:46:19Z
c++
2022-08-02T03:13:58Z
shell/browser/ui/win/electron_desktop_window_tree_host_win.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/ui/win/electron_desktop_window_tree_host_win.h" #include "base/win/windows_version.h" #include "electron/buildflags/buildflags.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/win/dark_mode.h" #include "ui/base/win/hwnd_metrics.h" #include "ui/base/win/shell.h" namespace electron { ElectronDesktopWindowTreeHostWin::ElectronDesktopWindowTreeHostWin( NativeWindowViews* native_window_view, views::DesktopNativeWidgetAura* desktop_native_widget_aura) : views::DesktopWindowTreeHostWin(native_window_view->widget(), desktop_native_widget_aura), native_window_view_(native_window_view) {} ElectronDesktopWindowTreeHostWin::~ElectronDesktopWindowTreeHostWin() = default; bool ElectronDesktopWindowTreeHostWin::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { const bool dark_mode_supported = win::IsDarkModeSupported(); if (dark_mode_supported && message == WM_NCCREATE) { win::SetDarkModeForWindow(GetAcceleratedWidget()); ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); } else if (dark_mode_supported && message == WM_DESTROY) { ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); } return native_window_view_->PreHandleMSG(message, w_param, l_param, result); } bool ElectronDesktopWindowTreeHostWin::ShouldPaintAsActive() const { // Tell Chromium to use system default behavior when rendering inactive // titlebar, otherwise it would render inactive titlebar as active under // some cases. // See also https://github.com/electron/electron/issues/24647. return false; } bool ElectronDesktopWindowTreeHostWin::HasNativeFrame() const { // Since we never use chromium's titlebar implementation, we can just say // that we use a native titlebar. This will disable the repaint locking when // DWM composition is disabled. // See also https://github.com/electron/electron/issues/1821. return !ui::win::IsAeroGlassEnabled(); } bool ElectronDesktopWindowTreeHostWin::GetDwmFrameInsetsInPixels( gfx::Insets* insets) const { // Set DWMFrameInsets to prevent maximized frameless window from bleeding // into other monitors. if (IsMaximized() && !native_window_view_->has_frame()) { // This would be equivalent to calling: // DwmExtendFrameIntoClientArea({0, 0, 0, 0}); // // which means do not extend window frame into client area. It is almost // a no-op, but it can tell Windows to not extend the window frame to be // larger than current workspace. // // See also: // https://devblogs.microsoft.com/oldnewthing/20150304-00/?p=44543 *insets = gfx::Insets(); return true; } return false; } bool ElectronDesktopWindowTreeHostWin::GetClientAreaInsets( gfx::Insets* insets, HMONITOR monitor) const { // Windows by default extends the maximized window slightly larger than // current workspace, for frameless window since the standard frame has been // removed, the client area would then be drew outside current workspace. // // Indenting the client area can fix this behavior. if (IsMaximized() && !native_window_view_->has_frame()) { // The insets would be eventually passed to WM_NCCALCSIZE, which takes // the metrics under the DPI of _main_ monitor instead of current monitor. // // Please make sure you tested maximized frameless window under multiple // monitors with different DPIs before changing this code. const int thickness = ::GetSystemMetrics(SM_CXSIZEFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER); *insets = gfx::Insets::TLBR(thickness, thickness, thickness, thickness); return true; } return false; } void ElectronDesktopWindowTreeHostWin::OnNativeThemeUpdated( ui::NativeTheme* observed_theme) { win::SetDarkModeForWindow(GetAcceleratedWidget()); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,364
[Bug]: WCO on Windows don't respond to touch events
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4.4 ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior WCO on Windows respond to touch events ### Actual Behavior WCO on Windows do not respond to touch events ### Testcase Gist URL _No response_ ### Additional Information The same fiddle repro applies from this comment https://github.com/electron/electron/issues/34129#issuecomment-1124398574
https://github.com/electron/electron/issues/34364
https://github.com/electron/electron/pull/35117
0cdc946b2708c3592ec1c413f28a28442c843183
e3893632e7e7cf39fff160946fdc19a7ae058da2
2022-05-27T20:46:19Z
c++
2022-08-02T03:13:58Z
shell/browser/ui/win/electron_desktop_window_tree_host_win.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_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_ #define ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_ #include <windows.h> #include "shell/browser/native_window_views.h" #include "ui/views/widget/desktop_aura/desktop_window_tree_host_win.h" namespace electron { class ElectronDesktopWindowTreeHostWin : public views::DesktopWindowTreeHostWin, public ::ui::NativeThemeObserver { public: ElectronDesktopWindowTreeHostWin( NativeWindowViews* native_window_view, views::DesktopNativeWidgetAura* desktop_native_widget_aura); ~ElectronDesktopWindowTreeHostWin() override; // disable copy ElectronDesktopWindowTreeHostWin(const ElectronDesktopWindowTreeHostWin&) = delete; ElectronDesktopWindowTreeHostWin& operator=( const ElectronDesktopWindowTreeHostWin&) = delete; protected: bool PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) override; bool ShouldPaintAsActive() const override; bool HasNativeFrame() const override; bool GetDwmFrameInsetsInPixels(gfx::Insets* insets) const override; bool GetClientAreaInsets(gfx::Insets* insets, HMONITOR monitor) const override; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override; private: NativeWindowViews* native_window_view_; // weak ref }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_
closed
electron/electron
https://github.com/electron/electron
34,820
[Bug]: wayland window decorations mangled and not clickable
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.7 ### What operating system are you using? Ubuntu ### Operating System Version 22.04 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.0-alpha.3 ### Expected Behavior Running under wayland natively (`--ozone-platform=wayland`) and enabling window decorations (`app.commandLine.appendSwitch('enable-features', 'WaylandWindowDecorations');` in main.js) should show a title bar which is clickable. Below is from 19.0.0-alpha.3 where it still worked: ![grafik](https://user-images.githubusercontent.com/1392875/177206042-21015934-5a2b-4484-bc5c-111198be4008.png) ### Actual Behavior Running under wayland natively (`--ozone-platform=wayland`) and enabling window decorations (`app.commandLine.appendSwitch('enable-features', 'WaylandWindowDecorations');` in main.js) shows mangled transparent border on the left side instead of a title bar and is not clickable: On **electron 19** is broke during the alpha and beta cycle: Below is from 19.0.0-alpha.4 where it first broke, here the buttons are still clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205464-db1274be-63dc-4d5d-93e2-14157984966d.png) Starting with 19.0.0-beta.4 the buttons are also no longer clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205697-3e1d4362-2cd3-4ceb-a4f1-5ee6ef68643f.png) With 19.0.0 up and until 19.0.7 the same, broken titlebar and not clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205907-2ed403b8-df96-4c9e-8292-52092cb4db8b.png) On **electron 18-x-y** it also broke between 18.2.0 and 18.2.1, but only the buttons cannot be clicked any longer: 18.2.0 still everything ok, titlebar there and clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205350-a175f92b-5b28-40e3-a108-c05e6b87aa7d.png) 18.2.1: Titlebar still there, but no longer clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205401-2dafdd0f-a8de-4a39-8cec-e101bcfb74e5.png) Up and including 18.3.5 the titlebar stays there, but not clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205824-60381433-c39b-440d-9aa2-a7c62592f642.png) ### Testcase Gist URL https://gist.github.com/csett86/5d45c47cb1d5331b9ede0788ff5ae284 ### Additional Information To reproduce with the gist, you need to add ```--ozone-platform=wayland``` to the user-provided flags, as I could find a way to add this to the fiddle (the WaylandWindowDecorations are part of the fiddle): ![grafik](https://user-images.githubusercontent.com/1392875/177206134-6371daec-5e63-4127-a344-0bf72ffba907.png)
https://github.com/electron/electron/issues/34820
https://github.com/electron/electron/pull/34955
4e8480b15b63cf71648f8f9357713b8827dec27c
7b8fb2b07418c7bad6ce811ca75c926ee53663fc
2022-07-04T18:59:46Z
c++
2022-08-03T08:51:52Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch don_t_use_potentially_null_getwebframe_-_view_when_get_blink.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch fix_allow_guest_webcontents_to_enter_fullscreen.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch
closed
electron/electron
https://github.com/electron/electron
34,820
[Bug]: wayland window decorations mangled and not clickable
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.7 ### What operating system are you using? Ubuntu ### Operating System Version 22.04 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.0-alpha.3 ### Expected Behavior Running under wayland natively (`--ozone-platform=wayland`) and enabling window decorations (`app.commandLine.appendSwitch('enable-features', 'WaylandWindowDecorations');` in main.js) should show a title bar which is clickable. Below is from 19.0.0-alpha.3 where it still worked: ![grafik](https://user-images.githubusercontent.com/1392875/177206042-21015934-5a2b-4484-bc5c-111198be4008.png) ### Actual Behavior Running under wayland natively (`--ozone-platform=wayland`) and enabling window decorations (`app.commandLine.appendSwitch('enable-features', 'WaylandWindowDecorations');` in main.js) shows mangled transparent border on the left side instead of a title bar and is not clickable: On **electron 19** is broke during the alpha and beta cycle: Below is from 19.0.0-alpha.4 where it first broke, here the buttons are still clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205464-db1274be-63dc-4d5d-93e2-14157984966d.png) Starting with 19.0.0-beta.4 the buttons are also no longer clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205697-3e1d4362-2cd3-4ceb-a4f1-5ee6ef68643f.png) With 19.0.0 up and until 19.0.7 the same, broken titlebar and not clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205907-2ed403b8-df96-4c9e-8292-52092cb4db8b.png) On **electron 18-x-y** it also broke between 18.2.0 and 18.2.1, but only the buttons cannot be clicked any longer: 18.2.0 still everything ok, titlebar there and clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205350-a175f92b-5b28-40e3-a108-c05e6b87aa7d.png) 18.2.1: Titlebar still there, but no longer clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205401-2dafdd0f-a8de-4a39-8cec-e101bcfb74e5.png) Up and including 18.3.5 the titlebar stays there, but not clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205824-60381433-c39b-440d-9aa2-a7c62592f642.png) ### Testcase Gist URL https://gist.github.com/csett86/5d45c47cb1d5331b9ede0788ff5ae284 ### Additional Information To reproduce with the gist, you need to add ```--ozone-platform=wayland``` to the user-provided flags, as I could find a way to add this to the fiddle (the WaylandWindowDecorations are part of the fiddle): ![grafik](https://user-images.githubusercontent.com/1392875/177206134-6371daec-5e63-4127-a344-0bf72ffba907.png)
https://github.com/electron/electron/issues/34820
https://github.com/electron/electron/pull/34955
4e8480b15b63cf71648f8f9357713b8827dec27c
7b8fb2b07418c7bad6ce811ca75c926ee53663fc
2022-07-04T18:59:46Z
c++
2022-08-03T08:51:52Z
patches/chromium/add_maximized_parameter_to_linuxui_getwindowframeprovider.patch
closed
electron/electron
https://github.com/electron/electron
34,820
[Bug]: wayland window decorations mangled and not clickable
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.7 ### What operating system are you using? Ubuntu ### Operating System Version 22.04 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.0-alpha.3 ### Expected Behavior Running under wayland natively (`--ozone-platform=wayland`) and enabling window decorations (`app.commandLine.appendSwitch('enable-features', 'WaylandWindowDecorations');` in main.js) should show a title bar which is clickable. Below is from 19.0.0-alpha.3 where it still worked: ![grafik](https://user-images.githubusercontent.com/1392875/177206042-21015934-5a2b-4484-bc5c-111198be4008.png) ### Actual Behavior Running under wayland natively (`--ozone-platform=wayland`) and enabling window decorations (`app.commandLine.appendSwitch('enable-features', 'WaylandWindowDecorations');` in main.js) shows mangled transparent border on the left side instead of a title bar and is not clickable: On **electron 19** is broke during the alpha and beta cycle: Below is from 19.0.0-alpha.4 where it first broke, here the buttons are still clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205464-db1274be-63dc-4d5d-93e2-14157984966d.png) Starting with 19.0.0-beta.4 the buttons are also no longer clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205697-3e1d4362-2cd3-4ceb-a4f1-5ee6ef68643f.png) With 19.0.0 up and until 19.0.7 the same, broken titlebar and not clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205907-2ed403b8-df96-4c9e-8292-52092cb4db8b.png) On **electron 18-x-y** it also broke between 18.2.0 and 18.2.1, but only the buttons cannot be clicked any longer: 18.2.0 still everything ok, titlebar there and clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205350-a175f92b-5b28-40e3-a108-c05e6b87aa7d.png) 18.2.1: Titlebar still there, but no longer clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205401-2dafdd0f-a8de-4a39-8cec-e101bcfb74e5.png) Up and including 18.3.5 the titlebar stays there, but not clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205824-60381433-c39b-440d-9aa2-a7c62592f642.png) ### Testcase Gist URL https://gist.github.com/csett86/5d45c47cb1d5331b9ede0788ff5ae284 ### Additional Information To reproduce with the gist, you need to add ```--ozone-platform=wayland``` to the user-provided flags, as I could find a way to add this to the fiddle (the WaylandWindowDecorations are part of the fiddle): ![grafik](https://user-images.githubusercontent.com/1392875/177206134-6371daec-5e63-4127-a344-0bf72ffba907.png)
https://github.com/electron/electron/issues/34820
https://github.com/electron/electron/pull/34955
4e8480b15b63cf71648f8f9357713b8827dec27c
7b8fb2b07418c7bad6ce811ca75c926ee53663fc
2022-07-04T18:59:46Z
c++
2022-08-03T08:51:52Z
shell/browser/ui/views/client_frame_view_linux.cc
// Copyright (c) 2021 Ryan Gonzalez. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/views/client_frame_view_linux.h" #include <algorithm> #include "base/strings/utf_string_conversions.h" #include "cc/paint/paint_filter.h" #include "cc/paint/paint_flags.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "ui/base/hit_test.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/canvas.h" #include "ui/gfx/font_list.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/skia_util.h" #include "ui/gfx/text_constants.h" #include "ui/gtk/gtk_compat.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #include "ui/linux/linux_ui.h" #include "ui/linux/nav_button_provider.h" #include "ui/native_theme/native_theme.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/style/typography.h" #include "ui/views/widget/widget.h" #include "ui/views/window/frame_buttons.h" #include "ui/views/window/window_button_order_provider.h" namespace electron { namespace { // These values should be the same as Chromium uses. constexpr int kResizeOutsideBorderSize = 10; constexpr int kResizeInsideBoundsSize = 5; ui::NavButtonProvider::ButtonState ButtonStateToNavButtonProviderState( views::Button::ButtonState state) { switch (state) { case views::Button::STATE_NORMAL: return ui::NavButtonProvider::ButtonState::kNormal; case views::Button::STATE_HOVERED: return ui::NavButtonProvider::ButtonState::kHovered; case views::Button::STATE_PRESSED: return ui::NavButtonProvider::ButtonState::kPressed; case views::Button::STATE_DISABLED: return ui::NavButtonProvider::ButtonState::kDisabled; case views::Button::STATE_COUNT: default: NOTREACHED(); return ui::NavButtonProvider::ButtonState::kNormal; } } } // namespace // static const char ClientFrameViewLinux::kViewClassName[] = "ClientFrameView"; ClientFrameViewLinux::ClientFrameViewLinux() : theme_(ui::NativeTheme::GetInstanceForNativeUi()), nav_button_provider_(ui::LinuxUi::instance()->CreateNavButtonProvider()), nav_buttons_{ NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kClose, views::FrameButton::kClose, &views::Widget::Close, IDS_APP_ACCNAME_CLOSE, HTCLOSE}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kMaximize, views::FrameButton::kMaximize, &views::Widget::Maximize, IDS_APP_ACCNAME_MAXIMIZE, HTMAXBUTTON}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kRestore, views::FrameButton::kMaximize, &views::Widget::Restore, IDS_APP_ACCNAME_RESTORE, HTMAXBUTTON}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kMinimize, views::FrameButton::kMinimize, &views::Widget::Minimize, IDS_APP_ACCNAME_MINIMIZE, HTMINBUTTON}, }, trailing_frame_buttons_{views::FrameButton::kMinimize, views::FrameButton::kMaximize, views::FrameButton::kClose} { for (auto& button : nav_buttons_) { button.button = new views::ImageButton(); button.button->SetImageVerticalAlignment(views::ImageButton::ALIGN_MIDDLE); button.button->SetAccessibleName( l10n_util::GetStringUTF16(button.accessibility_id)); AddChildView(button.button); } title_ = new views::Label(); title_->SetSubpixelRenderingEnabled(false); title_->SetAutoColorReadabilityEnabled(false); title_->SetHorizontalAlignment(gfx::ALIGN_CENTER); title_->SetVerticalAlignment(gfx::ALIGN_MIDDLE); title_->SetTextStyle(views::style::STYLE_TAB_ACTIVE); AddChildView(title_); native_theme_observer_.Observe(theme_); if (ui::LinuxUi* ui = ui::LinuxUi::instance()) { ui->AddWindowButtonOrderObserver(this); OnWindowButtonOrderingChange(); } } ClientFrameViewLinux::~ClientFrameViewLinux() { if (ui::LinuxUi* ui = ui::LinuxUi::instance()) ui->RemoveWindowButtonOrderObserver(this); theme_->RemoveObserver(this); } void ClientFrameViewLinux::Init(NativeWindowViews* window, views::Widget* frame) { FramelessView::Init(window, frame); // Unretained() is safe because the subscription is saved into an instance // member and thus will be cancelled upon the instance's destruction. paint_as_active_changed_subscription_ = frame_->RegisterPaintAsActiveChangedCallback(base::BindRepeating( &ClientFrameViewLinux::PaintAsActiveChanged, base::Unretained(this))); auto* tree_host = static_cast<ElectronDesktopWindowTreeHostLinux*>( ElectronDesktopWindowTreeHostLinux::GetHostForWidget( window->GetAcceleratedWidget())); host_supports_client_frame_shadow_ = tree_host->SupportsClientFrameShadow(); frame_provider_ = ui::LinuxUi::instance()->GetWindowFrameProvider( !host_supports_client_frame_shadow_); UpdateWindowTitle(); for (auto& button : nav_buttons_) { // Unretained() is safe because the buttons are added as children to, and // thus owned by, this view. Thus, the buttons themselves will be destroyed // when this view is destroyed, and the frame's life must never outlive the // view. button.button->SetCallback( base::BindRepeating(button.callback, base::Unretained(frame))); } UpdateThemeValues(); } gfx::Insets ClientFrameViewLinux::GetBorderDecorationInsets() const { return frame_provider_->GetFrameThicknessDip(); } gfx::Insets ClientFrameViewLinux::GetInputInsets() const { return gfx::Insets( host_supports_client_frame_shadow_ ? -kResizeOutsideBorderSize : 0); } gfx::Rect ClientFrameViewLinux::GetWindowContentBounds() const { gfx::Rect content_bounds = bounds(); content_bounds.Inset(GetBorderDecorationInsets()); return content_bounds; } SkRRect ClientFrameViewLinux::GetRoundedWindowContentBounds() const { SkRect rect = gfx::RectToSkRect(GetWindowContentBounds()); SkRRect rrect; if (!frame_->IsMaximized()) { SkPoint round_point{theme_values_.window_border_radius, theme_values_.window_border_radius}; SkPoint radii[] = {round_point, round_point, {}, {}}; rrect.setRectRadii(rect, radii); } else { rrect.setRect(rect); } return rrect; } void ClientFrameViewLinux::OnNativeThemeUpdated( ui::NativeTheme* observed_theme) { UpdateThemeValues(); } void ClientFrameViewLinux::OnWindowButtonOrderingChange() { auto* provider = views::WindowButtonOrderProvider::GetInstance(); leading_frame_buttons_ = provider->leading_buttons(); trailing_frame_buttons_ = provider->trailing_buttons(); InvalidateLayout(); } int ClientFrameViewLinux::ResizingBorderHitTest(const gfx::Point& point) { return ResizingBorderHitTestImpl( point, GetBorderDecorationInsets() + gfx::Insets(kResizeInsideBoundsSize)); } gfx::Rect ClientFrameViewLinux::GetBoundsForClientView() const { gfx::Rect client_bounds = bounds(); if (!frame_->IsFullscreen()) { client_bounds.Inset(GetBorderDecorationInsets()); client_bounds.Inset( gfx::Insets::TLBR(0, GetTitlebarBounds().height(), 0, 0)); } return client_bounds; } gfx::Rect ClientFrameViewLinux::GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const { gfx::Insets insets = bounds().InsetsFrom(GetBoundsForClientView()); return gfx::Rect(std::max(0, client_bounds.x() - insets.left()), std::max(0, client_bounds.y() - insets.top()), client_bounds.width() + insets.width(), client_bounds.height() + insets.height()); } int ClientFrameViewLinux::NonClientHitTest(const gfx::Point& point) { int component = ResizingBorderHitTest(point); if (component != HTNOWHERE) { return component; } for (auto& button : nav_buttons_) { if (button.button->GetVisible() && button.button->GetMirroredBounds().Contains(point)) { return button.hit_test_id; } } if (GetTitlebarBounds().Contains(point)) { return HTCAPTION; } return FramelessView::NonClientHitTest(point); } void ClientFrameViewLinux::GetWindowMask(const gfx::Size& size, SkPath* window_mask) { // Nothing to do here, as transparency is used for decorations, not masks. } void ClientFrameViewLinux::UpdateWindowTitle() { title_->SetText(base::UTF8ToUTF16(window_->GetTitle())); } void ClientFrameViewLinux::SizeConstraintsChanged() { InvalidateLayout(); } gfx::Size ClientFrameViewLinux::CalculatePreferredSize() const { return SizeWithDecorations(FramelessView::CalculatePreferredSize()); } gfx::Size ClientFrameViewLinux::GetMinimumSize() const { return SizeWithDecorations(FramelessView::GetMinimumSize()); } gfx::Size ClientFrameViewLinux::GetMaximumSize() const { return SizeWithDecorations(FramelessView::GetMaximumSize()); } void ClientFrameViewLinux::Layout() { FramelessView::Layout(); if (frame_->IsFullscreen()) { // Just hide everything and return. for (NavButton& button : nav_buttons_) { button.button->SetVisible(false); } title_->SetVisible(false); return; } UpdateButtonImages(); LayoutButtons(); gfx::Rect title_bounds(GetTitlebarContentBounds()); title_bounds.Inset(theme_values_.title_padding); title_->SetVisible(true); title_->SetBounds(title_bounds.x(), title_bounds.y(), title_bounds.width(), title_bounds.height()); } void ClientFrameViewLinux::OnPaint(gfx::Canvas* canvas) { if (!frame_->IsFullscreen()) { frame_provider_->PaintWindowFrame(canvas, GetLocalBounds(), GetTitlebarBounds().bottom(), ShouldPaintAsActive()); } } const char* ClientFrameViewLinux::GetClassName() const { return kViewClassName; } void ClientFrameViewLinux::PaintAsActiveChanged() { UpdateThemeValues(); } void ClientFrameViewLinux::UpdateThemeValues() { gtk::GtkCssContext window_context = gtk::AppendCssNodeToStyleContext({}, "GtkWindow#window.background.csd"); gtk::GtkCssContext headerbar_context = gtk::AppendCssNodeToStyleContext( {}, "GtkHeaderBar#headerbar.default-decoration.titlebar"); gtk::GtkCssContext title_context = gtk::AppendCssNodeToStyleContext( headerbar_context, "GtkLabel#label.title"); gtk::GtkCssContext button_context = gtk::AppendCssNodeToStyleContext( headerbar_context, "GtkButton#button.image-button"); gtk_style_context_set_parent(headerbar_context, window_context); gtk_style_context_set_parent(title_context, headerbar_context); gtk_style_context_set_parent(button_context, headerbar_context); // ShouldPaintAsActive asks the widget, so assume active if the widget is not // set yet. if (GetWidget() != nullptr && !ShouldPaintAsActive()) { gtk_style_context_set_state(window_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(headerbar_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(title_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(button_context, GTK_STATE_FLAG_BACKDROP); } theme_values_.window_border_radius = frame_provider_->GetTopCornerRadiusDip(); gtk::GtkStyleContextGet(headerbar_context, "min-height", &theme_values_.titlebar_min_height, nullptr); theme_values_.titlebar_padding = gtk::GtkStyleContextGetPadding(headerbar_context); theme_values_.title_color = gtk::GtkStyleContextGetColor(title_context); theme_values_.title_padding = gtk::GtkStyleContextGetPadding(title_context); gtk::GtkStyleContextGet(button_context, "min-height", &theme_values_.button_min_size, nullptr); theme_values_.button_padding = gtk::GtkStyleContextGetPadding(button_context); title_->SetEnabledColor(theme_values_.title_color); InvalidateLayout(); SchedulePaint(); } ui::NavButtonProvider::FrameButtonDisplayType ClientFrameViewLinux::GetButtonTypeToSkip() const { return frame_->IsMaximized() ? ui::NavButtonProvider::FrameButtonDisplayType::kMaximize : ui::NavButtonProvider::FrameButtonDisplayType::kRestore; } void ClientFrameViewLinux::UpdateButtonImages() { nav_button_provider_->RedrawImages(theme_values_.button_min_size, frame_->IsMaximized(), ShouldPaintAsActive()); ui::NavButtonProvider::FrameButtonDisplayType skip_type = GetButtonTypeToSkip(); for (NavButton& button : nav_buttons_) { if (button.type == skip_type) { continue; } for (size_t state_id = 0; state_id < views::Button::STATE_COUNT; state_id++) { views::Button::ButtonState state = static_cast<views::Button::ButtonState>(state_id); button.button->SetImage( state, nav_button_provider_->GetImage( button.type, ButtonStateToNavButtonProviderState(state))); } } } void ClientFrameViewLinux::LayoutButtons() { for (NavButton& button : nav_buttons_) { button.button->SetVisible(false); } gfx::Rect remaining_content_bounds = GetTitlebarContentBounds(); LayoutButtonsOnSide(ButtonSide::kLeading, &remaining_content_bounds); LayoutButtonsOnSide(ButtonSide::kTrailing, &remaining_content_bounds); } void ClientFrameViewLinux::LayoutButtonsOnSide( ButtonSide side, gfx::Rect* remaining_content_bounds) { ui::NavButtonProvider::FrameButtonDisplayType skip_type = GetButtonTypeToSkip(); std::vector<views::FrameButton> frame_buttons; switch (side) { case ButtonSide::kLeading: frame_buttons = leading_frame_buttons_; break; case ButtonSide::kTrailing: frame_buttons = trailing_frame_buttons_; // We always lay buttons out going from the edge towards the center, but // they are given to us as left-to-right, so reverse them. std::reverse(frame_buttons.begin(), frame_buttons.end()); break; default: NOTREACHED(); } for (views::FrameButton frame_button : frame_buttons) { auto* button = std::find_if( nav_buttons_.begin(), nav_buttons_.end(), [&](const NavButton& test) { return test.type != skip_type && test.frame_button == frame_button; }); CHECK(button != nav_buttons_.end()) << "Failed to find frame button: " << static_cast<int>(frame_button); if (button->type == skip_type) { continue; } button->button->SetVisible(true); int button_width = theme_values_.button_min_size; int next_button_offset = button_width + nav_button_provider_->GetInterNavButtonSpacing(); int x_position = 0; gfx::Insets inset_after_placement; switch (side) { case ButtonSide::kLeading: x_position = remaining_content_bounds->x(); inset_after_placement.set_left(next_button_offset); break; case ButtonSide::kTrailing: x_position = remaining_content_bounds->right() - button_width; inset_after_placement.set_right(next_button_offset); break; default: NOTREACHED(); } button->button->SetBounds(x_position, remaining_content_bounds->y(), button_width, remaining_content_bounds->height()); remaining_content_bounds->Inset(inset_after_placement); } } gfx::Rect ClientFrameViewLinux::GetTitlebarBounds() const { if (frame_->IsFullscreen()) { return gfx::Rect(); } int font_height = gfx::FontList().GetHeight(); int titlebar_height = std::max(font_height, theme_values_.titlebar_min_height) + GetTitlebarContentInsets().height(); gfx::Insets decoration_insets = GetBorderDecorationInsets(); // We add the inset height here, so the .Inset() that follows won't reduce it // to be too small. gfx::Rect titlebar(width(), titlebar_height + decoration_insets.height()); titlebar.Inset(decoration_insets); return titlebar; } gfx::Insets ClientFrameViewLinux::GetTitlebarContentInsets() const { return theme_values_.titlebar_padding + nav_button_provider_->GetTopAreaSpacing(); } gfx::Rect ClientFrameViewLinux::GetTitlebarContentBounds() const { gfx::Rect titlebar(GetTitlebarBounds()); titlebar.Inset(GetTitlebarContentInsets()); return titlebar; } gfx::Size ClientFrameViewLinux::SizeWithDecorations(gfx::Size size) const { gfx::Insets decoration_insets = GetBorderDecorationInsets(); size.Enlarge(0, GetTitlebarBounds().height()); size.Enlarge(decoration_insets.width(), decoration_insets.height()); return size; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,820
[Bug]: wayland window decorations mangled and not clickable
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.7 ### What operating system are you using? Ubuntu ### Operating System Version 22.04 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.0-alpha.3 ### Expected Behavior Running under wayland natively (`--ozone-platform=wayland`) and enabling window decorations (`app.commandLine.appendSwitch('enable-features', 'WaylandWindowDecorations');` in main.js) should show a title bar which is clickable. Below is from 19.0.0-alpha.3 where it still worked: ![grafik](https://user-images.githubusercontent.com/1392875/177206042-21015934-5a2b-4484-bc5c-111198be4008.png) ### Actual Behavior Running under wayland natively (`--ozone-platform=wayland`) and enabling window decorations (`app.commandLine.appendSwitch('enable-features', 'WaylandWindowDecorations');` in main.js) shows mangled transparent border on the left side instead of a title bar and is not clickable: On **electron 19** is broke during the alpha and beta cycle: Below is from 19.0.0-alpha.4 where it first broke, here the buttons are still clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205464-db1274be-63dc-4d5d-93e2-14157984966d.png) Starting with 19.0.0-beta.4 the buttons are also no longer clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205697-3e1d4362-2cd3-4ceb-a4f1-5ee6ef68643f.png) With 19.0.0 up and until 19.0.7 the same, broken titlebar and not clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205907-2ed403b8-df96-4c9e-8292-52092cb4db8b.png) On **electron 18-x-y** it also broke between 18.2.0 and 18.2.1, but only the buttons cannot be clicked any longer: 18.2.0 still everything ok, titlebar there and clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205350-a175f92b-5b28-40e3-a108-c05e6b87aa7d.png) 18.2.1: Titlebar still there, but no longer clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205401-2dafdd0f-a8de-4a39-8cec-e101bcfb74e5.png) Up and including 18.3.5 the titlebar stays there, but not clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205824-60381433-c39b-440d-9aa2-a7c62592f642.png) ### Testcase Gist URL https://gist.github.com/csett86/5d45c47cb1d5331b9ede0788ff5ae284 ### Additional Information To reproduce with the gist, you need to add ```--ozone-platform=wayland``` to the user-provided flags, as I could find a way to add this to the fiddle (the WaylandWindowDecorations are part of the fiddle): ![grafik](https://user-images.githubusercontent.com/1392875/177206134-6371daec-5e63-4127-a344-0bf72ffba907.png)
https://github.com/electron/electron/issues/34820
https://github.com/electron/electron/pull/34955
4e8480b15b63cf71648f8f9357713b8827dec27c
7b8fb2b07418c7bad6ce811ca75c926ee53663fc
2022-07-04T18:59:46Z
c++
2022-08-03T08:51:52Z
shell/browser/ui/views/client_frame_view_linux.h
// Copyright (c) 2021 Ryan Gonzalez. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_UI_VIEWS_CLIENT_FRAME_VIEW_LINUX_H_ #define ELECTRON_SHELL_BROWSER_UI_VIEWS_CLIENT_FRAME_VIEW_LINUX_H_ #include <array> #include <memory> #include <vector> #include "base/scoped_observation.h" #include "shell/browser/ui/views/frameless_view.h" #include "ui/linux/linux_ui.h" #include "ui/linux/nav_button_provider.h" #include "ui/linux/window_button_order_observer.h" #include "ui/linux/window_frame_provider.h" #include "ui/native_theme/native_theme.h" #include "ui/native_theme/native_theme_observer.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/label.h" #include "ui/views/widget/widget.h" #include "ui/views/window/frame_buttons.h" namespace electron { class ClientFrameViewLinux : public FramelessView, public ui::NativeThemeObserver, public ui::WindowButtonOrderObserver { public: static const char kViewClassName[]; ClientFrameViewLinux(); ~ClientFrameViewLinux() override; void Init(NativeWindowViews* window, views::Widget* frame) override; // These are here for ElectronDesktopWindowTreeHostLinux to use. gfx::Insets GetBorderDecorationInsets() const; gfx::Insets GetInputInsets() const; gfx::Rect GetWindowContentBounds() const; SkRRect GetRoundedWindowContentBounds() const; protected: // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override; // views::WindowButtonOrderObserver: void OnWindowButtonOrderingChange() override; // Overridden from FramelessView: int ResizingBorderHitTest(const gfx::Point& point) override; // Overridden from views::NonClientFrameView: gfx::Rect GetBoundsForClientView() const override; gfx::Rect GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const override; int NonClientHitTest(const gfx::Point& point) override; void GetWindowMask(const gfx::Size& size, SkPath* window_mask) override; void UpdateWindowTitle() override; void SizeConstraintsChanged() override; // Overridden from View: gfx::Size CalculatePreferredSize() const override; gfx::Size GetMinimumSize() const override; gfx::Size GetMaximumSize() const override; void Layout() override; void OnPaint(gfx::Canvas* canvas) override; const char* GetClassName() const override; private: static constexpr int kNavButtonCount = 4; struct NavButton { ui::NavButtonProvider::FrameButtonDisplayType type; views::FrameButton frame_button; void (views::Widget::*callback)(); int accessibility_id; int hit_test_id; views::ImageButton* button{nullptr}; }; struct ThemeValues { float window_border_radius; int titlebar_min_height; gfx::Insets titlebar_padding; SkColor title_color; gfx::Insets title_padding; int button_min_size; gfx::Insets button_padding; }; void PaintAsActiveChanged(); void UpdateThemeValues(); enum class ButtonSide { kLeading, kTrailing }; ui::NavButtonProvider::FrameButtonDisplayType GetButtonTypeToSkip() const; void UpdateButtonImages(); void LayoutButtons(); void LayoutButtonsOnSide(ButtonSide side, gfx::Rect* remaining_content_bounds); gfx::Rect GetTitlebarBounds() const; gfx::Insets GetTitlebarContentInsets() const; gfx::Rect GetTitlebarContentBounds() const; gfx::Size SizeWithDecorations(gfx::Size size) const; ui::NativeTheme* theme_; ThemeValues theme_values_; views::Label* title_; std::unique_ptr<ui::NavButtonProvider> nav_button_provider_; std::array<NavButton, kNavButtonCount> nav_buttons_; std::vector<views::FrameButton> leading_frame_buttons_; std::vector<views::FrameButton> trailing_frame_buttons_; bool host_supports_client_frame_shadow_ = false; ui::WindowFrameProvider* frame_provider_; base::ScopedObservation<ui::NativeTheme, ui::NativeThemeObserver> native_theme_observer_{this}; base::ScopedObservation<ui::LinuxUi, ui::WindowButtonOrderObserver, &ui::LinuxUi::AddWindowButtonOrderObserver, &ui::LinuxUi::RemoveWindowButtonOrderObserver> window_button_order_observer_{this}; base::CallbackListSubscription paint_as_active_changed_subscription_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_VIEWS_CLIENT_FRAME_VIEW_LINUX_H_
closed
electron/electron
https://github.com/electron/electron
33,161
[Bug]: Window has borders while maximized in 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 17.1.0 and 18.0.0-alpha.5 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior The window should have no borders when maximized. ### Actual Behavior Window has borders when maximized (at least in GNOME, I have not tested in other interfaces/window managers). ### Testcase Gist URL _No response_ ### Additional Information To reproduce: - Use a Wayland environment. - Start the Electron demo app with the flags: `--enable-features=WaylandWindowDecorations --ozone-platform=wayland`. - Maximize the window. - See that the window isn't really maximized and there are still borders. Some notes: - The issue is not reproducible in Chromium 99.0.4844.51 with the same start flags, so that's probably not a bug in the window manager. - When removing the `WaylandWindowDecorations` feature flag, window maximizes correctly under Wayland (though there are no window decorations, so I have to maximize window using keyboard). - Maybe CC #29618 author? ![Screenshot](https://user-images.githubusercontent.com/29029632/156944326-4ac421cc-a2c1-4099-bf12-f0af1c29de4a.png)
https://github.com/electron/electron/issues/33161
https://github.com/electron/electron/pull/34955
4e8480b15b63cf71648f8f9357713b8827dec27c
7b8fb2b07418c7bad6ce811ca75c926ee53663fc
2022-03-06T22:40:31Z
c++
2022-08-03T08:51:52Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch don_t_use_potentially_null_getwebframe_-_view_when_get_blink.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch fix_allow_guest_webcontents_to_enter_fullscreen.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch
closed
electron/electron
https://github.com/electron/electron
33,161
[Bug]: Window has borders while maximized in 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 17.1.0 and 18.0.0-alpha.5 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior The window should have no borders when maximized. ### Actual Behavior Window has borders when maximized (at least in GNOME, I have not tested in other interfaces/window managers). ### Testcase Gist URL _No response_ ### Additional Information To reproduce: - Use a Wayland environment. - Start the Electron demo app with the flags: `--enable-features=WaylandWindowDecorations --ozone-platform=wayland`. - Maximize the window. - See that the window isn't really maximized and there are still borders. Some notes: - The issue is not reproducible in Chromium 99.0.4844.51 with the same start flags, so that's probably not a bug in the window manager. - When removing the `WaylandWindowDecorations` feature flag, window maximizes correctly under Wayland (though there are no window decorations, so I have to maximize window using keyboard). - Maybe CC #29618 author? ![Screenshot](https://user-images.githubusercontent.com/29029632/156944326-4ac421cc-a2c1-4099-bf12-f0af1c29de4a.png)
https://github.com/electron/electron/issues/33161
https://github.com/electron/electron/pull/34955
4e8480b15b63cf71648f8f9357713b8827dec27c
7b8fb2b07418c7bad6ce811ca75c926ee53663fc
2022-03-06T22:40:31Z
c++
2022-08-03T08:51:52Z
patches/chromium/add_maximized_parameter_to_linuxui_getwindowframeprovider.patch
closed
electron/electron
https://github.com/electron/electron
33,161
[Bug]: Window has borders while maximized in 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 17.1.0 and 18.0.0-alpha.5 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior The window should have no borders when maximized. ### Actual Behavior Window has borders when maximized (at least in GNOME, I have not tested in other interfaces/window managers). ### Testcase Gist URL _No response_ ### Additional Information To reproduce: - Use a Wayland environment. - Start the Electron demo app with the flags: `--enable-features=WaylandWindowDecorations --ozone-platform=wayland`. - Maximize the window. - See that the window isn't really maximized and there are still borders. Some notes: - The issue is not reproducible in Chromium 99.0.4844.51 with the same start flags, so that's probably not a bug in the window manager. - When removing the `WaylandWindowDecorations` feature flag, window maximizes correctly under Wayland (though there are no window decorations, so I have to maximize window using keyboard). - Maybe CC #29618 author? ![Screenshot](https://user-images.githubusercontent.com/29029632/156944326-4ac421cc-a2c1-4099-bf12-f0af1c29de4a.png)
https://github.com/electron/electron/issues/33161
https://github.com/electron/electron/pull/34955
4e8480b15b63cf71648f8f9357713b8827dec27c
7b8fb2b07418c7bad6ce811ca75c926ee53663fc
2022-03-06T22:40:31Z
c++
2022-08-03T08:51:52Z
shell/browser/ui/views/client_frame_view_linux.cc
// Copyright (c) 2021 Ryan Gonzalez. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/views/client_frame_view_linux.h" #include <algorithm> #include "base/strings/utf_string_conversions.h" #include "cc/paint/paint_filter.h" #include "cc/paint/paint_flags.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "ui/base/hit_test.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/canvas.h" #include "ui/gfx/font_list.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/skia_util.h" #include "ui/gfx/text_constants.h" #include "ui/gtk/gtk_compat.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #include "ui/linux/linux_ui.h" #include "ui/linux/nav_button_provider.h" #include "ui/native_theme/native_theme.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/style/typography.h" #include "ui/views/widget/widget.h" #include "ui/views/window/frame_buttons.h" #include "ui/views/window/window_button_order_provider.h" namespace electron { namespace { // These values should be the same as Chromium uses. constexpr int kResizeOutsideBorderSize = 10; constexpr int kResizeInsideBoundsSize = 5; ui::NavButtonProvider::ButtonState ButtonStateToNavButtonProviderState( views::Button::ButtonState state) { switch (state) { case views::Button::STATE_NORMAL: return ui::NavButtonProvider::ButtonState::kNormal; case views::Button::STATE_HOVERED: return ui::NavButtonProvider::ButtonState::kHovered; case views::Button::STATE_PRESSED: return ui::NavButtonProvider::ButtonState::kPressed; case views::Button::STATE_DISABLED: return ui::NavButtonProvider::ButtonState::kDisabled; case views::Button::STATE_COUNT: default: NOTREACHED(); return ui::NavButtonProvider::ButtonState::kNormal; } } } // namespace // static const char ClientFrameViewLinux::kViewClassName[] = "ClientFrameView"; ClientFrameViewLinux::ClientFrameViewLinux() : theme_(ui::NativeTheme::GetInstanceForNativeUi()), nav_button_provider_(ui::LinuxUi::instance()->CreateNavButtonProvider()), nav_buttons_{ NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kClose, views::FrameButton::kClose, &views::Widget::Close, IDS_APP_ACCNAME_CLOSE, HTCLOSE}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kMaximize, views::FrameButton::kMaximize, &views::Widget::Maximize, IDS_APP_ACCNAME_MAXIMIZE, HTMAXBUTTON}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kRestore, views::FrameButton::kMaximize, &views::Widget::Restore, IDS_APP_ACCNAME_RESTORE, HTMAXBUTTON}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kMinimize, views::FrameButton::kMinimize, &views::Widget::Minimize, IDS_APP_ACCNAME_MINIMIZE, HTMINBUTTON}, }, trailing_frame_buttons_{views::FrameButton::kMinimize, views::FrameButton::kMaximize, views::FrameButton::kClose} { for (auto& button : nav_buttons_) { button.button = new views::ImageButton(); button.button->SetImageVerticalAlignment(views::ImageButton::ALIGN_MIDDLE); button.button->SetAccessibleName( l10n_util::GetStringUTF16(button.accessibility_id)); AddChildView(button.button); } title_ = new views::Label(); title_->SetSubpixelRenderingEnabled(false); title_->SetAutoColorReadabilityEnabled(false); title_->SetHorizontalAlignment(gfx::ALIGN_CENTER); title_->SetVerticalAlignment(gfx::ALIGN_MIDDLE); title_->SetTextStyle(views::style::STYLE_TAB_ACTIVE); AddChildView(title_); native_theme_observer_.Observe(theme_); if (ui::LinuxUi* ui = ui::LinuxUi::instance()) { ui->AddWindowButtonOrderObserver(this); OnWindowButtonOrderingChange(); } } ClientFrameViewLinux::~ClientFrameViewLinux() { if (ui::LinuxUi* ui = ui::LinuxUi::instance()) ui->RemoveWindowButtonOrderObserver(this); theme_->RemoveObserver(this); } void ClientFrameViewLinux::Init(NativeWindowViews* window, views::Widget* frame) { FramelessView::Init(window, frame); // Unretained() is safe because the subscription is saved into an instance // member and thus will be cancelled upon the instance's destruction. paint_as_active_changed_subscription_ = frame_->RegisterPaintAsActiveChangedCallback(base::BindRepeating( &ClientFrameViewLinux::PaintAsActiveChanged, base::Unretained(this))); auto* tree_host = static_cast<ElectronDesktopWindowTreeHostLinux*>( ElectronDesktopWindowTreeHostLinux::GetHostForWidget( window->GetAcceleratedWidget())); host_supports_client_frame_shadow_ = tree_host->SupportsClientFrameShadow(); frame_provider_ = ui::LinuxUi::instance()->GetWindowFrameProvider( !host_supports_client_frame_shadow_); UpdateWindowTitle(); for (auto& button : nav_buttons_) { // Unretained() is safe because the buttons are added as children to, and // thus owned by, this view. Thus, the buttons themselves will be destroyed // when this view is destroyed, and the frame's life must never outlive the // view. button.button->SetCallback( base::BindRepeating(button.callback, base::Unretained(frame))); } UpdateThemeValues(); } gfx::Insets ClientFrameViewLinux::GetBorderDecorationInsets() const { return frame_provider_->GetFrameThicknessDip(); } gfx::Insets ClientFrameViewLinux::GetInputInsets() const { return gfx::Insets( host_supports_client_frame_shadow_ ? -kResizeOutsideBorderSize : 0); } gfx::Rect ClientFrameViewLinux::GetWindowContentBounds() const { gfx::Rect content_bounds = bounds(); content_bounds.Inset(GetBorderDecorationInsets()); return content_bounds; } SkRRect ClientFrameViewLinux::GetRoundedWindowContentBounds() const { SkRect rect = gfx::RectToSkRect(GetWindowContentBounds()); SkRRect rrect; if (!frame_->IsMaximized()) { SkPoint round_point{theme_values_.window_border_radius, theme_values_.window_border_radius}; SkPoint radii[] = {round_point, round_point, {}, {}}; rrect.setRectRadii(rect, radii); } else { rrect.setRect(rect); } return rrect; } void ClientFrameViewLinux::OnNativeThemeUpdated( ui::NativeTheme* observed_theme) { UpdateThemeValues(); } void ClientFrameViewLinux::OnWindowButtonOrderingChange() { auto* provider = views::WindowButtonOrderProvider::GetInstance(); leading_frame_buttons_ = provider->leading_buttons(); trailing_frame_buttons_ = provider->trailing_buttons(); InvalidateLayout(); } int ClientFrameViewLinux::ResizingBorderHitTest(const gfx::Point& point) { return ResizingBorderHitTestImpl( point, GetBorderDecorationInsets() + gfx::Insets(kResizeInsideBoundsSize)); } gfx::Rect ClientFrameViewLinux::GetBoundsForClientView() const { gfx::Rect client_bounds = bounds(); if (!frame_->IsFullscreen()) { client_bounds.Inset(GetBorderDecorationInsets()); client_bounds.Inset( gfx::Insets::TLBR(0, GetTitlebarBounds().height(), 0, 0)); } return client_bounds; } gfx::Rect ClientFrameViewLinux::GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const { gfx::Insets insets = bounds().InsetsFrom(GetBoundsForClientView()); return gfx::Rect(std::max(0, client_bounds.x() - insets.left()), std::max(0, client_bounds.y() - insets.top()), client_bounds.width() + insets.width(), client_bounds.height() + insets.height()); } int ClientFrameViewLinux::NonClientHitTest(const gfx::Point& point) { int component = ResizingBorderHitTest(point); if (component != HTNOWHERE) { return component; } for (auto& button : nav_buttons_) { if (button.button->GetVisible() && button.button->GetMirroredBounds().Contains(point)) { return button.hit_test_id; } } if (GetTitlebarBounds().Contains(point)) { return HTCAPTION; } return FramelessView::NonClientHitTest(point); } void ClientFrameViewLinux::GetWindowMask(const gfx::Size& size, SkPath* window_mask) { // Nothing to do here, as transparency is used for decorations, not masks. } void ClientFrameViewLinux::UpdateWindowTitle() { title_->SetText(base::UTF8ToUTF16(window_->GetTitle())); } void ClientFrameViewLinux::SizeConstraintsChanged() { InvalidateLayout(); } gfx::Size ClientFrameViewLinux::CalculatePreferredSize() const { return SizeWithDecorations(FramelessView::CalculatePreferredSize()); } gfx::Size ClientFrameViewLinux::GetMinimumSize() const { return SizeWithDecorations(FramelessView::GetMinimumSize()); } gfx::Size ClientFrameViewLinux::GetMaximumSize() const { return SizeWithDecorations(FramelessView::GetMaximumSize()); } void ClientFrameViewLinux::Layout() { FramelessView::Layout(); if (frame_->IsFullscreen()) { // Just hide everything and return. for (NavButton& button : nav_buttons_) { button.button->SetVisible(false); } title_->SetVisible(false); return; } UpdateButtonImages(); LayoutButtons(); gfx::Rect title_bounds(GetTitlebarContentBounds()); title_bounds.Inset(theme_values_.title_padding); title_->SetVisible(true); title_->SetBounds(title_bounds.x(), title_bounds.y(), title_bounds.width(), title_bounds.height()); } void ClientFrameViewLinux::OnPaint(gfx::Canvas* canvas) { if (!frame_->IsFullscreen()) { frame_provider_->PaintWindowFrame(canvas, GetLocalBounds(), GetTitlebarBounds().bottom(), ShouldPaintAsActive()); } } const char* ClientFrameViewLinux::GetClassName() const { return kViewClassName; } void ClientFrameViewLinux::PaintAsActiveChanged() { UpdateThemeValues(); } void ClientFrameViewLinux::UpdateThemeValues() { gtk::GtkCssContext window_context = gtk::AppendCssNodeToStyleContext({}, "GtkWindow#window.background.csd"); gtk::GtkCssContext headerbar_context = gtk::AppendCssNodeToStyleContext( {}, "GtkHeaderBar#headerbar.default-decoration.titlebar"); gtk::GtkCssContext title_context = gtk::AppendCssNodeToStyleContext( headerbar_context, "GtkLabel#label.title"); gtk::GtkCssContext button_context = gtk::AppendCssNodeToStyleContext( headerbar_context, "GtkButton#button.image-button"); gtk_style_context_set_parent(headerbar_context, window_context); gtk_style_context_set_parent(title_context, headerbar_context); gtk_style_context_set_parent(button_context, headerbar_context); // ShouldPaintAsActive asks the widget, so assume active if the widget is not // set yet. if (GetWidget() != nullptr && !ShouldPaintAsActive()) { gtk_style_context_set_state(window_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(headerbar_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(title_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(button_context, GTK_STATE_FLAG_BACKDROP); } theme_values_.window_border_radius = frame_provider_->GetTopCornerRadiusDip(); gtk::GtkStyleContextGet(headerbar_context, "min-height", &theme_values_.titlebar_min_height, nullptr); theme_values_.titlebar_padding = gtk::GtkStyleContextGetPadding(headerbar_context); theme_values_.title_color = gtk::GtkStyleContextGetColor(title_context); theme_values_.title_padding = gtk::GtkStyleContextGetPadding(title_context); gtk::GtkStyleContextGet(button_context, "min-height", &theme_values_.button_min_size, nullptr); theme_values_.button_padding = gtk::GtkStyleContextGetPadding(button_context); title_->SetEnabledColor(theme_values_.title_color); InvalidateLayout(); SchedulePaint(); } ui::NavButtonProvider::FrameButtonDisplayType ClientFrameViewLinux::GetButtonTypeToSkip() const { return frame_->IsMaximized() ? ui::NavButtonProvider::FrameButtonDisplayType::kMaximize : ui::NavButtonProvider::FrameButtonDisplayType::kRestore; } void ClientFrameViewLinux::UpdateButtonImages() { nav_button_provider_->RedrawImages(theme_values_.button_min_size, frame_->IsMaximized(), ShouldPaintAsActive()); ui::NavButtonProvider::FrameButtonDisplayType skip_type = GetButtonTypeToSkip(); for (NavButton& button : nav_buttons_) { if (button.type == skip_type) { continue; } for (size_t state_id = 0; state_id < views::Button::STATE_COUNT; state_id++) { views::Button::ButtonState state = static_cast<views::Button::ButtonState>(state_id); button.button->SetImage( state, nav_button_provider_->GetImage( button.type, ButtonStateToNavButtonProviderState(state))); } } } void ClientFrameViewLinux::LayoutButtons() { for (NavButton& button : nav_buttons_) { button.button->SetVisible(false); } gfx::Rect remaining_content_bounds = GetTitlebarContentBounds(); LayoutButtonsOnSide(ButtonSide::kLeading, &remaining_content_bounds); LayoutButtonsOnSide(ButtonSide::kTrailing, &remaining_content_bounds); } void ClientFrameViewLinux::LayoutButtonsOnSide( ButtonSide side, gfx::Rect* remaining_content_bounds) { ui::NavButtonProvider::FrameButtonDisplayType skip_type = GetButtonTypeToSkip(); std::vector<views::FrameButton> frame_buttons; switch (side) { case ButtonSide::kLeading: frame_buttons = leading_frame_buttons_; break; case ButtonSide::kTrailing: frame_buttons = trailing_frame_buttons_; // We always lay buttons out going from the edge towards the center, but // they are given to us as left-to-right, so reverse them. std::reverse(frame_buttons.begin(), frame_buttons.end()); break; default: NOTREACHED(); } for (views::FrameButton frame_button : frame_buttons) { auto* button = std::find_if( nav_buttons_.begin(), nav_buttons_.end(), [&](const NavButton& test) { return test.type != skip_type && test.frame_button == frame_button; }); CHECK(button != nav_buttons_.end()) << "Failed to find frame button: " << static_cast<int>(frame_button); if (button->type == skip_type) { continue; } button->button->SetVisible(true); int button_width = theme_values_.button_min_size; int next_button_offset = button_width + nav_button_provider_->GetInterNavButtonSpacing(); int x_position = 0; gfx::Insets inset_after_placement; switch (side) { case ButtonSide::kLeading: x_position = remaining_content_bounds->x(); inset_after_placement.set_left(next_button_offset); break; case ButtonSide::kTrailing: x_position = remaining_content_bounds->right() - button_width; inset_after_placement.set_right(next_button_offset); break; default: NOTREACHED(); } button->button->SetBounds(x_position, remaining_content_bounds->y(), button_width, remaining_content_bounds->height()); remaining_content_bounds->Inset(inset_after_placement); } } gfx::Rect ClientFrameViewLinux::GetTitlebarBounds() const { if (frame_->IsFullscreen()) { return gfx::Rect(); } int font_height = gfx::FontList().GetHeight(); int titlebar_height = std::max(font_height, theme_values_.titlebar_min_height) + GetTitlebarContentInsets().height(); gfx::Insets decoration_insets = GetBorderDecorationInsets(); // We add the inset height here, so the .Inset() that follows won't reduce it // to be too small. gfx::Rect titlebar(width(), titlebar_height + decoration_insets.height()); titlebar.Inset(decoration_insets); return titlebar; } gfx::Insets ClientFrameViewLinux::GetTitlebarContentInsets() const { return theme_values_.titlebar_padding + nav_button_provider_->GetTopAreaSpacing(); } gfx::Rect ClientFrameViewLinux::GetTitlebarContentBounds() const { gfx::Rect titlebar(GetTitlebarBounds()); titlebar.Inset(GetTitlebarContentInsets()); return titlebar; } gfx::Size ClientFrameViewLinux::SizeWithDecorations(gfx::Size size) const { gfx::Insets decoration_insets = GetBorderDecorationInsets(); size.Enlarge(0, GetTitlebarBounds().height()); size.Enlarge(decoration_insets.width(), decoration_insets.height()); return size; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,161
[Bug]: Window has borders while maximized in 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 17.1.0 and 18.0.0-alpha.5 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior The window should have no borders when maximized. ### Actual Behavior Window has borders when maximized (at least in GNOME, I have not tested in other interfaces/window managers). ### Testcase Gist URL _No response_ ### Additional Information To reproduce: - Use a Wayland environment. - Start the Electron demo app with the flags: `--enable-features=WaylandWindowDecorations --ozone-platform=wayland`. - Maximize the window. - See that the window isn't really maximized and there are still borders. Some notes: - The issue is not reproducible in Chromium 99.0.4844.51 with the same start flags, so that's probably not a bug in the window manager. - When removing the `WaylandWindowDecorations` feature flag, window maximizes correctly under Wayland (though there are no window decorations, so I have to maximize window using keyboard). - Maybe CC #29618 author? ![Screenshot](https://user-images.githubusercontent.com/29029632/156944326-4ac421cc-a2c1-4099-bf12-f0af1c29de4a.png)
https://github.com/electron/electron/issues/33161
https://github.com/electron/electron/pull/34955
4e8480b15b63cf71648f8f9357713b8827dec27c
7b8fb2b07418c7bad6ce811ca75c926ee53663fc
2022-03-06T22:40:31Z
c++
2022-08-03T08:51:52Z
shell/browser/ui/views/client_frame_view_linux.h
// Copyright (c) 2021 Ryan Gonzalez. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_UI_VIEWS_CLIENT_FRAME_VIEW_LINUX_H_ #define ELECTRON_SHELL_BROWSER_UI_VIEWS_CLIENT_FRAME_VIEW_LINUX_H_ #include <array> #include <memory> #include <vector> #include "base/scoped_observation.h" #include "shell/browser/ui/views/frameless_view.h" #include "ui/linux/linux_ui.h" #include "ui/linux/nav_button_provider.h" #include "ui/linux/window_button_order_observer.h" #include "ui/linux/window_frame_provider.h" #include "ui/native_theme/native_theme.h" #include "ui/native_theme/native_theme_observer.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/label.h" #include "ui/views/widget/widget.h" #include "ui/views/window/frame_buttons.h" namespace electron { class ClientFrameViewLinux : public FramelessView, public ui::NativeThemeObserver, public ui::WindowButtonOrderObserver { public: static const char kViewClassName[]; ClientFrameViewLinux(); ~ClientFrameViewLinux() override; void Init(NativeWindowViews* window, views::Widget* frame) override; // These are here for ElectronDesktopWindowTreeHostLinux to use. gfx::Insets GetBorderDecorationInsets() const; gfx::Insets GetInputInsets() const; gfx::Rect GetWindowContentBounds() const; SkRRect GetRoundedWindowContentBounds() const; protected: // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override; // views::WindowButtonOrderObserver: void OnWindowButtonOrderingChange() override; // Overridden from FramelessView: int ResizingBorderHitTest(const gfx::Point& point) override; // Overridden from views::NonClientFrameView: gfx::Rect GetBoundsForClientView() const override; gfx::Rect GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const override; int NonClientHitTest(const gfx::Point& point) override; void GetWindowMask(const gfx::Size& size, SkPath* window_mask) override; void UpdateWindowTitle() override; void SizeConstraintsChanged() override; // Overridden from View: gfx::Size CalculatePreferredSize() const override; gfx::Size GetMinimumSize() const override; gfx::Size GetMaximumSize() const override; void Layout() override; void OnPaint(gfx::Canvas* canvas) override; const char* GetClassName() const override; private: static constexpr int kNavButtonCount = 4; struct NavButton { ui::NavButtonProvider::FrameButtonDisplayType type; views::FrameButton frame_button; void (views::Widget::*callback)(); int accessibility_id; int hit_test_id; views::ImageButton* button{nullptr}; }; struct ThemeValues { float window_border_radius; int titlebar_min_height; gfx::Insets titlebar_padding; SkColor title_color; gfx::Insets title_padding; int button_min_size; gfx::Insets button_padding; }; void PaintAsActiveChanged(); void UpdateThemeValues(); enum class ButtonSide { kLeading, kTrailing }; ui::NavButtonProvider::FrameButtonDisplayType GetButtonTypeToSkip() const; void UpdateButtonImages(); void LayoutButtons(); void LayoutButtonsOnSide(ButtonSide side, gfx::Rect* remaining_content_bounds); gfx::Rect GetTitlebarBounds() const; gfx::Insets GetTitlebarContentInsets() const; gfx::Rect GetTitlebarContentBounds() const; gfx::Size SizeWithDecorations(gfx::Size size) const; ui::NativeTheme* theme_; ThemeValues theme_values_; views::Label* title_; std::unique_ptr<ui::NavButtonProvider> nav_button_provider_; std::array<NavButton, kNavButtonCount> nav_buttons_; std::vector<views::FrameButton> leading_frame_buttons_; std::vector<views::FrameButton> trailing_frame_buttons_; bool host_supports_client_frame_shadow_ = false; ui::WindowFrameProvider* frame_provider_; base::ScopedObservation<ui::NativeTheme, ui::NativeThemeObserver> native_theme_observer_{this}; base::ScopedObservation<ui::LinuxUi, ui::WindowButtonOrderObserver, &ui::LinuxUi::AddWindowButtonOrderObserver, &ui::LinuxUi::RemoveWindowButtonOrderObserver> window_button_order_observer_{this}; base::CallbackListSubscription paint_as_active_changed_subscription_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_VIEWS_CLIENT_FRAME_VIEW_LINUX_H_
closed
electron/electron
https://github.com/electron/electron
34,820
[Bug]: wayland window decorations mangled and not clickable
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.7 ### What operating system are you using? Ubuntu ### Operating System Version 22.04 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.0-alpha.3 ### Expected Behavior Running under wayland natively (`--ozone-platform=wayland`) and enabling window decorations (`app.commandLine.appendSwitch('enable-features', 'WaylandWindowDecorations');` in main.js) should show a title bar which is clickable. Below is from 19.0.0-alpha.3 where it still worked: ![grafik](https://user-images.githubusercontent.com/1392875/177206042-21015934-5a2b-4484-bc5c-111198be4008.png) ### Actual Behavior Running under wayland natively (`--ozone-platform=wayland`) and enabling window decorations (`app.commandLine.appendSwitch('enable-features', 'WaylandWindowDecorations');` in main.js) shows mangled transparent border on the left side instead of a title bar and is not clickable: On **electron 19** is broke during the alpha and beta cycle: Below is from 19.0.0-alpha.4 where it first broke, here the buttons are still clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205464-db1274be-63dc-4d5d-93e2-14157984966d.png) Starting with 19.0.0-beta.4 the buttons are also no longer clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205697-3e1d4362-2cd3-4ceb-a4f1-5ee6ef68643f.png) With 19.0.0 up and until 19.0.7 the same, broken titlebar and not clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205907-2ed403b8-df96-4c9e-8292-52092cb4db8b.png) On **electron 18-x-y** it also broke between 18.2.0 and 18.2.1, but only the buttons cannot be clicked any longer: 18.2.0 still everything ok, titlebar there and clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205350-a175f92b-5b28-40e3-a108-c05e6b87aa7d.png) 18.2.1: Titlebar still there, but no longer clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205401-2dafdd0f-a8de-4a39-8cec-e101bcfb74e5.png) Up and including 18.3.5 the titlebar stays there, but not clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205824-60381433-c39b-440d-9aa2-a7c62592f642.png) ### Testcase Gist URL https://gist.github.com/csett86/5d45c47cb1d5331b9ede0788ff5ae284 ### Additional Information To reproduce with the gist, you need to add ```--ozone-platform=wayland``` to the user-provided flags, as I could find a way to add this to the fiddle (the WaylandWindowDecorations are part of the fiddle): ![grafik](https://user-images.githubusercontent.com/1392875/177206134-6371daec-5e63-4127-a344-0bf72ffba907.png)
https://github.com/electron/electron/issues/34820
https://github.com/electron/electron/pull/34955
4e8480b15b63cf71648f8f9357713b8827dec27c
7b8fb2b07418c7bad6ce811ca75c926ee53663fc
2022-07-04T18:59:46Z
c++
2022-08-03T08:51:52Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch don_t_use_potentially_null_getwebframe_-_view_when_get_blink.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch fix_allow_guest_webcontents_to_enter_fullscreen.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch
closed
electron/electron
https://github.com/electron/electron
34,820
[Bug]: wayland window decorations mangled and not clickable
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.7 ### What operating system are you using? Ubuntu ### Operating System Version 22.04 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.0-alpha.3 ### Expected Behavior Running under wayland natively (`--ozone-platform=wayland`) and enabling window decorations (`app.commandLine.appendSwitch('enable-features', 'WaylandWindowDecorations');` in main.js) should show a title bar which is clickable. Below is from 19.0.0-alpha.3 where it still worked: ![grafik](https://user-images.githubusercontent.com/1392875/177206042-21015934-5a2b-4484-bc5c-111198be4008.png) ### Actual Behavior Running under wayland natively (`--ozone-platform=wayland`) and enabling window decorations (`app.commandLine.appendSwitch('enable-features', 'WaylandWindowDecorations');` in main.js) shows mangled transparent border on the left side instead of a title bar and is not clickable: On **electron 19** is broke during the alpha and beta cycle: Below is from 19.0.0-alpha.4 where it first broke, here the buttons are still clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205464-db1274be-63dc-4d5d-93e2-14157984966d.png) Starting with 19.0.0-beta.4 the buttons are also no longer clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205697-3e1d4362-2cd3-4ceb-a4f1-5ee6ef68643f.png) With 19.0.0 up and until 19.0.7 the same, broken titlebar and not clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205907-2ed403b8-df96-4c9e-8292-52092cb4db8b.png) On **electron 18-x-y** it also broke between 18.2.0 and 18.2.1, but only the buttons cannot be clicked any longer: 18.2.0 still everything ok, titlebar there and clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205350-a175f92b-5b28-40e3-a108-c05e6b87aa7d.png) 18.2.1: Titlebar still there, but no longer clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205401-2dafdd0f-a8de-4a39-8cec-e101bcfb74e5.png) Up and including 18.3.5 the titlebar stays there, but not clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205824-60381433-c39b-440d-9aa2-a7c62592f642.png) ### Testcase Gist URL https://gist.github.com/csett86/5d45c47cb1d5331b9ede0788ff5ae284 ### Additional Information To reproduce with the gist, you need to add ```--ozone-platform=wayland``` to the user-provided flags, as I could find a way to add this to the fiddle (the WaylandWindowDecorations are part of the fiddle): ![grafik](https://user-images.githubusercontent.com/1392875/177206134-6371daec-5e63-4127-a344-0bf72ffba907.png)
https://github.com/electron/electron/issues/34820
https://github.com/electron/electron/pull/34955
4e8480b15b63cf71648f8f9357713b8827dec27c
7b8fb2b07418c7bad6ce811ca75c926ee53663fc
2022-07-04T18:59:46Z
c++
2022-08-03T08:51:52Z
patches/chromium/add_maximized_parameter_to_linuxui_getwindowframeprovider.patch
closed
electron/electron
https://github.com/electron/electron
34,820
[Bug]: wayland window decorations mangled and not clickable
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.7 ### What operating system are you using? Ubuntu ### Operating System Version 22.04 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.0-alpha.3 ### Expected Behavior Running under wayland natively (`--ozone-platform=wayland`) and enabling window decorations (`app.commandLine.appendSwitch('enable-features', 'WaylandWindowDecorations');` in main.js) should show a title bar which is clickable. Below is from 19.0.0-alpha.3 where it still worked: ![grafik](https://user-images.githubusercontent.com/1392875/177206042-21015934-5a2b-4484-bc5c-111198be4008.png) ### Actual Behavior Running under wayland natively (`--ozone-platform=wayland`) and enabling window decorations (`app.commandLine.appendSwitch('enable-features', 'WaylandWindowDecorations');` in main.js) shows mangled transparent border on the left side instead of a title bar and is not clickable: On **electron 19** is broke during the alpha and beta cycle: Below is from 19.0.0-alpha.4 where it first broke, here the buttons are still clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205464-db1274be-63dc-4d5d-93e2-14157984966d.png) Starting with 19.0.0-beta.4 the buttons are also no longer clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205697-3e1d4362-2cd3-4ceb-a4f1-5ee6ef68643f.png) With 19.0.0 up and until 19.0.7 the same, broken titlebar and not clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205907-2ed403b8-df96-4c9e-8292-52092cb4db8b.png) On **electron 18-x-y** it also broke between 18.2.0 and 18.2.1, but only the buttons cannot be clicked any longer: 18.2.0 still everything ok, titlebar there and clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205350-a175f92b-5b28-40e3-a108-c05e6b87aa7d.png) 18.2.1: Titlebar still there, but no longer clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205401-2dafdd0f-a8de-4a39-8cec-e101bcfb74e5.png) Up and including 18.3.5 the titlebar stays there, but not clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205824-60381433-c39b-440d-9aa2-a7c62592f642.png) ### Testcase Gist URL https://gist.github.com/csett86/5d45c47cb1d5331b9ede0788ff5ae284 ### Additional Information To reproduce with the gist, you need to add ```--ozone-platform=wayland``` to the user-provided flags, as I could find a way to add this to the fiddle (the WaylandWindowDecorations are part of the fiddle): ![grafik](https://user-images.githubusercontent.com/1392875/177206134-6371daec-5e63-4127-a344-0bf72ffba907.png)
https://github.com/electron/electron/issues/34820
https://github.com/electron/electron/pull/34955
4e8480b15b63cf71648f8f9357713b8827dec27c
7b8fb2b07418c7bad6ce811ca75c926ee53663fc
2022-07-04T18:59:46Z
c++
2022-08-03T08:51:52Z
shell/browser/ui/views/client_frame_view_linux.cc
// Copyright (c) 2021 Ryan Gonzalez. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/views/client_frame_view_linux.h" #include <algorithm> #include "base/strings/utf_string_conversions.h" #include "cc/paint/paint_filter.h" #include "cc/paint/paint_flags.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "ui/base/hit_test.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/canvas.h" #include "ui/gfx/font_list.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/skia_util.h" #include "ui/gfx/text_constants.h" #include "ui/gtk/gtk_compat.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #include "ui/linux/linux_ui.h" #include "ui/linux/nav_button_provider.h" #include "ui/native_theme/native_theme.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/style/typography.h" #include "ui/views/widget/widget.h" #include "ui/views/window/frame_buttons.h" #include "ui/views/window/window_button_order_provider.h" namespace electron { namespace { // These values should be the same as Chromium uses. constexpr int kResizeOutsideBorderSize = 10; constexpr int kResizeInsideBoundsSize = 5; ui::NavButtonProvider::ButtonState ButtonStateToNavButtonProviderState( views::Button::ButtonState state) { switch (state) { case views::Button::STATE_NORMAL: return ui::NavButtonProvider::ButtonState::kNormal; case views::Button::STATE_HOVERED: return ui::NavButtonProvider::ButtonState::kHovered; case views::Button::STATE_PRESSED: return ui::NavButtonProvider::ButtonState::kPressed; case views::Button::STATE_DISABLED: return ui::NavButtonProvider::ButtonState::kDisabled; case views::Button::STATE_COUNT: default: NOTREACHED(); return ui::NavButtonProvider::ButtonState::kNormal; } } } // namespace // static const char ClientFrameViewLinux::kViewClassName[] = "ClientFrameView"; ClientFrameViewLinux::ClientFrameViewLinux() : theme_(ui::NativeTheme::GetInstanceForNativeUi()), nav_button_provider_(ui::LinuxUi::instance()->CreateNavButtonProvider()), nav_buttons_{ NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kClose, views::FrameButton::kClose, &views::Widget::Close, IDS_APP_ACCNAME_CLOSE, HTCLOSE}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kMaximize, views::FrameButton::kMaximize, &views::Widget::Maximize, IDS_APP_ACCNAME_MAXIMIZE, HTMAXBUTTON}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kRestore, views::FrameButton::kMaximize, &views::Widget::Restore, IDS_APP_ACCNAME_RESTORE, HTMAXBUTTON}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kMinimize, views::FrameButton::kMinimize, &views::Widget::Minimize, IDS_APP_ACCNAME_MINIMIZE, HTMINBUTTON}, }, trailing_frame_buttons_{views::FrameButton::kMinimize, views::FrameButton::kMaximize, views::FrameButton::kClose} { for (auto& button : nav_buttons_) { button.button = new views::ImageButton(); button.button->SetImageVerticalAlignment(views::ImageButton::ALIGN_MIDDLE); button.button->SetAccessibleName( l10n_util::GetStringUTF16(button.accessibility_id)); AddChildView(button.button); } title_ = new views::Label(); title_->SetSubpixelRenderingEnabled(false); title_->SetAutoColorReadabilityEnabled(false); title_->SetHorizontalAlignment(gfx::ALIGN_CENTER); title_->SetVerticalAlignment(gfx::ALIGN_MIDDLE); title_->SetTextStyle(views::style::STYLE_TAB_ACTIVE); AddChildView(title_); native_theme_observer_.Observe(theme_); if (ui::LinuxUi* ui = ui::LinuxUi::instance()) { ui->AddWindowButtonOrderObserver(this); OnWindowButtonOrderingChange(); } } ClientFrameViewLinux::~ClientFrameViewLinux() { if (ui::LinuxUi* ui = ui::LinuxUi::instance()) ui->RemoveWindowButtonOrderObserver(this); theme_->RemoveObserver(this); } void ClientFrameViewLinux::Init(NativeWindowViews* window, views::Widget* frame) { FramelessView::Init(window, frame); // Unretained() is safe because the subscription is saved into an instance // member and thus will be cancelled upon the instance's destruction. paint_as_active_changed_subscription_ = frame_->RegisterPaintAsActiveChangedCallback(base::BindRepeating( &ClientFrameViewLinux::PaintAsActiveChanged, base::Unretained(this))); auto* tree_host = static_cast<ElectronDesktopWindowTreeHostLinux*>( ElectronDesktopWindowTreeHostLinux::GetHostForWidget( window->GetAcceleratedWidget())); host_supports_client_frame_shadow_ = tree_host->SupportsClientFrameShadow(); frame_provider_ = ui::LinuxUi::instance()->GetWindowFrameProvider( !host_supports_client_frame_shadow_); UpdateWindowTitle(); for (auto& button : nav_buttons_) { // Unretained() is safe because the buttons are added as children to, and // thus owned by, this view. Thus, the buttons themselves will be destroyed // when this view is destroyed, and the frame's life must never outlive the // view. button.button->SetCallback( base::BindRepeating(button.callback, base::Unretained(frame))); } UpdateThemeValues(); } gfx::Insets ClientFrameViewLinux::GetBorderDecorationInsets() const { return frame_provider_->GetFrameThicknessDip(); } gfx::Insets ClientFrameViewLinux::GetInputInsets() const { return gfx::Insets( host_supports_client_frame_shadow_ ? -kResizeOutsideBorderSize : 0); } gfx::Rect ClientFrameViewLinux::GetWindowContentBounds() const { gfx::Rect content_bounds = bounds(); content_bounds.Inset(GetBorderDecorationInsets()); return content_bounds; } SkRRect ClientFrameViewLinux::GetRoundedWindowContentBounds() const { SkRect rect = gfx::RectToSkRect(GetWindowContentBounds()); SkRRect rrect; if (!frame_->IsMaximized()) { SkPoint round_point{theme_values_.window_border_radius, theme_values_.window_border_radius}; SkPoint radii[] = {round_point, round_point, {}, {}}; rrect.setRectRadii(rect, radii); } else { rrect.setRect(rect); } return rrect; } void ClientFrameViewLinux::OnNativeThemeUpdated( ui::NativeTheme* observed_theme) { UpdateThemeValues(); } void ClientFrameViewLinux::OnWindowButtonOrderingChange() { auto* provider = views::WindowButtonOrderProvider::GetInstance(); leading_frame_buttons_ = provider->leading_buttons(); trailing_frame_buttons_ = provider->trailing_buttons(); InvalidateLayout(); } int ClientFrameViewLinux::ResizingBorderHitTest(const gfx::Point& point) { return ResizingBorderHitTestImpl( point, GetBorderDecorationInsets() + gfx::Insets(kResizeInsideBoundsSize)); } gfx::Rect ClientFrameViewLinux::GetBoundsForClientView() const { gfx::Rect client_bounds = bounds(); if (!frame_->IsFullscreen()) { client_bounds.Inset(GetBorderDecorationInsets()); client_bounds.Inset( gfx::Insets::TLBR(0, GetTitlebarBounds().height(), 0, 0)); } return client_bounds; } gfx::Rect ClientFrameViewLinux::GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const { gfx::Insets insets = bounds().InsetsFrom(GetBoundsForClientView()); return gfx::Rect(std::max(0, client_bounds.x() - insets.left()), std::max(0, client_bounds.y() - insets.top()), client_bounds.width() + insets.width(), client_bounds.height() + insets.height()); } int ClientFrameViewLinux::NonClientHitTest(const gfx::Point& point) { int component = ResizingBorderHitTest(point); if (component != HTNOWHERE) { return component; } for (auto& button : nav_buttons_) { if (button.button->GetVisible() && button.button->GetMirroredBounds().Contains(point)) { return button.hit_test_id; } } if (GetTitlebarBounds().Contains(point)) { return HTCAPTION; } return FramelessView::NonClientHitTest(point); } void ClientFrameViewLinux::GetWindowMask(const gfx::Size& size, SkPath* window_mask) { // Nothing to do here, as transparency is used for decorations, not masks. } void ClientFrameViewLinux::UpdateWindowTitle() { title_->SetText(base::UTF8ToUTF16(window_->GetTitle())); } void ClientFrameViewLinux::SizeConstraintsChanged() { InvalidateLayout(); } gfx::Size ClientFrameViewLinux::CalculatePreferredSize() const { return SizeWithDecorations(FramelessView::CalculatePreferredSize()); } gfx::Size ClientFrameViewLinux::GetMinimumSize() const { return SizeWithDecorations(FramelessView::GetMinimumSize()); } gfx::Size ClientFrameViewLinux::GetMaximumSize() const { return SizeWithDecorations(FramelessView::GetMaximumSize()); } void ClientFrameViewLinux::Layout() { FramelessView::Layout(); if (frame_->IsFullscreen()) { // Just hide everything and return. for (NavButton& button : nav_buttons_) { button.button->SetVisible(false); } title_->SetVisible(false); return; } UpdateButtonImages(); LayoutButtons(); gfx::Rect title_bounds(GetTitlebarContentBounds()); title_bounds.Inset(theme_values_.title_padding); title_->SetVisible(true); title_->SetBounds(title_bounds.x(), title_bounds.y(), title_bounds.width(), title_bounds.height()); } void ClientFrameViewLinux::OnPaint(gfx::Canvas* canvas) { if (!frame_->IsFullscreen()) { frame_provider_->PaintWindowFrame(canvas, GetLocalBounds(), GetTitlebarBounds().bottom(), ShouldPaintAsActive()); } } const char* ClientFrameViewLinux::GetClassName() const { return kViewClassName; } void ClientFrameViewLinux::PaintAsActiveChanged() { UpdateThemeValues(); } void ClientFrameViewLinux::UpdateThemeValues() { gtk::GtkCssContext window_context = gtk::AppendCssNodeToStyleContext({}, "GtkWindow#window.background.csd"); gtk::GtkCssContext headerbar_context = gtk::AppendCssNodeToStyleContext( {}, "GtkHeaderBar#headerbar.default-decoration.titlebar"); gtk::GtkCssContext title_context = gtk::AppendCssNodeToStyleContext( headerbar_context, "GtkLabel#label.title"); gtk::GtkCssContext button_context = gtk::AppendCssNodeToStyleContext( headerbar_context, "GtkButton#button.image-button"); gtk_style_context_set_parent(headerbar_context, window_context); gtk_style_context_set_parent(title_context, headerbar_context); gtk_style_context_set_parent(button_context, headerbar_context); // ShouldPaintAsActive asks the widget, so assume active if the widget is not // set yet. if (GetWidget() != nullptr && !ShouldPaintAsActive()) { gtk_style_context_set_state(window_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(headerbar_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(title_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(button_context, GTK_STATE_FLAG_BACKDROP); } theme_values_.window_border_radius = frame_provider_->GetTopCornerRadiusDip(); gtk::GtkStyleContextGet(headerbar_context, "min-height", &theme_values_.titlebar_min_height, nullptr); theme_values_.titlebar_padding = gtk::GtkStyleContextGetPadding(headerbar_context); theme_values_.title_color = gtk::GtkStyleContextGetColor(title_context); theme_values_.title_padding = gtk::GtkStyleContextGetPadding(title_context); gtk::GtkStyleContextGet(button_context, "min-height", &theme_values_.button_min_size, nullptr); theme_values_.button_padding = gtk::GtkStyleContextGetPadding(button_context); title_->SetEnabledColor(theme_values_.title_color); InvalidateLayout(); SchedulePaint(); } ui::NavButtonProvider::FrameButtonDisplayType ClientFrameViewLinux::GetButtonTypeToSkip() const { return frame_->IsMaximized() ? ui::NavButtonProvider::FrameButtonDisplayType::kMaximize : ui::NavButtonProvider::FrameButtonDisplayType::kRestore; } void ClientFrameViewLinux::UpdateButtonImages() { nav_button_provider_->RedrawImages(theme_values_.button_min_size, frame_->IsMaximized(), ShouldPaintAsActive()); ui::NavButtonProvider::FrameButtonDisplayType skip_type = GetButtonTypeToSkip(); for (NavButton& button : nav_buttons_) { if (button.type == skip_type) { continue; } for (size_t state_id = 0; state_id < views::Button::STATE_COUNT; state_id++) { views::Button::ButtonState state = static_cast<views::Button::ButtonState>(state_id); button.button->SetImage( state, nav_button_provider_->GetImage( button.type, ButtonStateToNavButtonProviderState(state))); } } } void ClientFrameViewLinux::LayoutButtons() { for (NavButton& button : nav_buttons_) { button.button->SetVisible(false); } gfx::Rect remaining_content_bounds = GetTitlebarContentBounds(); LayoutButtonsOnSide(ButtonSide::kLeading, &remaining_content_bounds); LayoutButtonsOnSide(ButtonSide::kTrailing, &remaining_content_bounds); } void ClientFrameViewLinux::LayoutButtonsOnSide( ButtonSide side, gfx::Rect* remaining_content_bounds) { ui::NavButtonProvider::FrameButtonDisplayType skip_type = GetButtonTypeToSkip(); std::vector<views::FrameButton> frame_buttons; switch (side) { case ButtonSide::kLeading: frame_buttons = leading_frame_buttons_; break; case ButtonSide::kTrailing: frame_buttons = trailing_frame_buttons_; // We always lay buttons out going from the edge towards the center, but // they are given to us as left-to-right, so reverse them. std::reverse(frame_buttons.begin(), frame_buttons.end()); break; default: NOTREACHED(); } for (views::FrameButton frame_button : frame_buttons) { auto* button = std::find_if( nav_buttons_.begin(), nav_buttons_.end(), [&](const NavButton& test) { return test.type != skip_type && test.frame_button == frame_button; }); CHECK(button != nav_buttons_.end()) << "Failed to find frame button: " << static_cast<int>(frame_button); if (button->type == skip_type) { continue; } button->button->SetVisible(true); int button_width = theme_values_.button_min_size; int next_button_offset = button_width + nav_button_provider_->GetInterNavButtonSpacing(); int x_position = 0; gfx::Insets inset_after_placement; switch (side) { case ButtonSide::kLeading: x_position = remaining_content_bounds->x(); inset_after_placement.set_left(next_button_offset); break; case ButtonSide::kTrailing: x_position = remaining_content_bounds->right() - button_width; inset_after_placement.set_right(next_button_offset); break; default: NOTREACHED(); } button->button->SetBounds(x_position, remaining_content_bounds->y(), button_width, remaining_content_bounds->height()); remaining_content_bounds->Inset(inset_after_placement); } } gfx::Rect ClientFrameViewLinux::GetTitlebarBounds() const { if (frame_->IsFullscreen()) { return gfx::Rect(); } int font_height = gfx::FontList().GetHeight(); int titlebar_height = std::max(font_height, theme_values_.titlebar_min_height) + GetTitlebarContentInsets().height(); gfx::Insets decoration_insets = GetBorderDecorationInsets(); // We add the inset height here, so the .Inset() that follows won't reduce it // to be too small. gfx::Rect titlebar(width(), titlebar_height + decoration_insets.height()); titlebar.Inset(decoration_insets); return titlebar; } gfx::Insets ClientFrameViewLinux::GetTitlebarContentInsets() const { return theme_values_.titlebar_padding + nav_button_provider_->GetTopAreaSpacing(); } gfx::Rect ClientFrameViewLinux::GetTitlebarContentBounds() const { gfx::Rect titlebar(GetTitlebarBounds()); titlebar.Inset(GetTitlebarContentInsets()); return titlebar; } gfx::Size ClientFrameViewLinux::SizeWithDecorations(gfx::Size size) const { gfx::Insets decoration_insets = GetBorderDecorationInsets(); size.Enlarge(0, GetTitlebarBounds().height()); size.Enlarge(decoration_insets.width(), decoration_insets.height()); return size; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,820
[Bug]: wayland window decorations mangled and not clickable
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.7 ### What operating system are you using? Ubuntu ### Operating System Version 22.04 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.0-alpha.3 ### Expected Behavior Running under wayland natively (`--ozone-platform=wayland`) and enabling window decorations (`app.commandLine.appendSwitch('enable-features', 'WaylandWindowDecorations');` in main.js) should show a title bar which is clickable. Below is from 19.0.0-alpha.3 where it still worked: ![grafik](https://user-images.githubusercontent.com/1392875/177206042-21015934-5a2b-4484-bc5c-111198be4008.png) ### Actual Behavior Running under wayland natively (`--ozone-platform=wayland`) and enabling window decorations (`app.commandLine.appendSwitch('enable-features', 'WaylandWindowDecorations');` in main.js) shows mangled transparent border on the left side instead of a title bar and is not clickable: On **electron 19** is broke during the alpha and beta cycle: Below is from 19.0.0-alpha.4 where it first broke, here the buttons are still clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205464-db1274be-63dc-4d5d-93e2-14157984966d.png) Starting with 19.0.0-beta.4 the buttons are also no longer clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205697-3e1d4362-2cd3-4ceb-a4f1-5ee6ef68643f.png) With 19.0.0 up and until 19.0.7 the same, broken titlebar and not clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205907-2ed403b8-df96-4c9e-8292-52092cb4db8b.png) On **electron 18-x-y** it also broke between 18.2.0 and 18.2.1, but only the buttons cannot be clicked any longer: 18.2.0 still everything ok, titlebar there and clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205350-a175f92b-5b28-40e3-a108-c05e6b87aa7d.png) 18.2.1: Titlebar still there, but no longer clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205401-2dafdd0f-a8de-4a39-8cec-e101bcfb74e5.png) Up and including 18.3.5 the titlebar stays there, but not clickable: ![grafik](https://user-images.githubusercontent.com/1392875/177205824-60381433-c39b-440d-9aa2-a7c62592f642.png) ### Testcase Gist URL https://gist.github.com/csett86/5d45c47cb1d5331b9ede0788ff5ae284 ### Additional Information To reproduce with the gist, you need to add ```--ozone-platform=wayland``` to the user-provided flags, as I could find a way to add this to the fiddle (the WaylandWindowDecorations are part of the fiddle): ![grafik](https://user-images.githubusercontent.com/1392875/177206134-6371daec-5e63-4127-a344-0bf72ffba907.png)
https://github.com/electron/electron/issues/34820
https://github.com/electron/electron/pull/34955
4e8480b15b63cf71648f8f9357713b8827dec27c
7b8fb2b07418c7bad6ce811ca75c926ee53663fc
2022-07-04T18:59:46Z
c++
2022-08-03T08:51:52Z
shell/browser/ui/views/client_frame_view_linux.h
// Copyright (c) 2021 Ryan Gonzalez. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_UI_VIEWS_CLIENT_FRAME_VIEW_LINUX_H_ #define ELECTRON_SHELL_BROWSER_UI_VIEWS_CLIENT_FRAME_VIEW_LINUX_H_ #include <array> #include <memory> #include <vector> #include "base/scoped_observation.h" #include "shell/browser/ui/views/frameless_view.h" #include "ui/linux/linux_ui.h" #include "ui/linux/nav_button_provider.h" #include "ui/linux/window_button_order_observer.h" #include "ui/linux/window_frame_provider.h" #include "ui/native_theme/native_theme.h" #include "ui/native_theme/native_theme_observer.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/label.h" #include "ui/views/widget/widget.h" #include "ui/views/window/frame_buttons.h" namespace electron { class ClientFrameViewLinux : public FramelessView, public ui::NativeThemeObserver, public ui::WindowButtonOrderObserver { public: static const char kViewClassName[]; ClientFrameViewLinux(); ~ClientFrameViewLinux() override; void Init(NativeWindowViews* window, views::Widget* frame) override; // These are here for ElectronDesktopWindowTreeHostLinux to use. gfx::Insets GetBorderDecorationInsets() const; gfx::Insets GetInputInsets() const; gfx::Rect GetWindowContentBounds() const; SkRRect GetRoundedWindowContentBounds() const; protected: // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override; // views::WindowButtonOrderObserver: void OnWindowButtonOrderingChange() override; // Overridden from FramelessView: int ResizingBorderHitTest(const gfx::Point& point) override; // Overridden from views::NonClientFrameView: gfx::Rect GetBoundsForClientView() const override; gfx::Rect GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const override; int NonClientHitTest(const gfx::Point& point) override; void GetWindowMask(const gfx::Size& size, SkPath* window_mask) override; void UpdateWindowTitle() override; void SizeConstraintsChanged() override; // Overridden from View: gfx::Size CalculatePreferredSize() const override; gfx::Size GetMinimumSize() const override; gfx::Size GetMaximumSize() const override; void Layout() override; void OnPaint(gfx::Canvas* canvas) override; const char* GetClassName() const override; private: static constexpr int kNavButtonCount = 4; struct NavButton { ui::NavButtonProvider::FrameButtonDisplayType type; views::FrameButton frame_button; void (views::Widget::*callback)(); int accessibility_id; int hit_test_id; views::ImageButton* button{nullptr}; }; struct ThemeValues { float window_border_radius; int titlebar_min_height; gfx::Insets titlebar_padding; SkColor title_color; gfx::Insets title_padding; int button_min_size; gfx::Insets button_padding; }; void PaintAsActiveChanged(); void UpdateThemeValues(); enum class ButtonSide { kLeading, kTrailing }; ui::NavButtonProvider::FrameButtonDisplayType GetButtonTypeToSkip() const; void UpdateButtonImages(); void LayoutButtons(); void LayoutButtonsOnSide(ButtonSide side, gfx::Rect* remaining_content_bounds); gfx::Rect GetTitlebarBounds() const; gfx::Insets GetTitlebarContentInsets() const; gfx::Rect GetTitlebarContentBounds() const; gfx::Size SizeWithDecorations(gfx::Size size) const; ui::NativeTheme* theme_; ThemeValues theme_values_; views::Label* title_; std::unique_ptr<ui::NavButtonProvider> nav_button_provider_; std::array<NavButton, kNavButtonCount> nav_buttons_; std::vector<views::FrameButton> leading_frame_buttons_; std::vector<views::FrameButton> trailing_frame_buttons_; bool host_supports_client_frame_shadow_ = false; ui::WindowFrameProvider* frame_provider_; base::ScopedObservation<ui::NativeTheme, ui::NativeThemeObserver> native_theme_observer_{this}; base::ScopedObservation<ui::LinuxUi, ui::WindowButtonOrderObserver, &ui::LinuxUi::AddWindowButtonOrderObserver, &ui::LinuxUi::RemoveWindowButtonOrderObserver> window_button_order_observer_{this}; base::CallbackListSubscription paint_as_active_changed_subscription_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_VIEWS_CLIENT_FRAME_VIEW_LINUX_H_
closed
electron/electron
https://github.com/electron/electron
33,161
[Bug]: Window has borders while maximized in 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 17.1.0 and 18.0.0-alpha.5 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior The window should have no borders when maximized. ### Actual Behavior Window has borders when maximized (at least in GNOME, I have not tested in other interfaces/window managers). ### Testcase Gist URL _No response_ ### Additional Information To reproduce: - Use a Wayland environment. - Start the Electron demo app with the flags: `--enable-features=WaylandWindowDecorations --ozone-platform=wayland`. - Maximize the window. - See that the window isn't really maximized and there are still borders. Some notes: - The issue is not reproducible in Chromium 99.0.4844.51 with the same start flags, so that's probably not a bug in the window manager. - When removing the `WaylandWindowDecorations` feature flag, window maximizes correctly under Wayland (though there are no window decorations, so I have to maximize window using keyboard). - Maybe CC #29618 author? ![Screenshot](https://user-images.githubusercontent.com/29029632/156944326-4ac421cc-a2c1-4099-bf12-f0af1c29de4a.png)
https://github.com/electron/electron/issues/33161
https://github.com/electron/electron/pull/34955
4e8480b15b63cf71648f8f9357713b8827dec27c
7b8fb2b07418c7bad6ce811ca75c926ee53663fc
2022-03-06T22:40:31Z
c++
2022-08-03T08:51:52Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch don_t_use_potentially_null_getwebframe_-_view_when_get_blink.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch fix_allow_guest_webcontents_to_enter_fullscreen.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch
closed
electron/electron
https://github.com/electron/electron
33,161
[Bug]: Window has borders while maximized in 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 17.1.0 and 18.0.0-alpha.5 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior The window should have no borders when maximized. ### Actual Behavior Window has borders when maximized (at least in GNOME, I have not tested in other interfaces/window managers). ### Testcase Gist URL _No response_ ### Additional Information To reproduce: - Use a Wayland environment. - Start the Electron demo app with the flags: `--enable-features=WaylandWindowDecorations --ozone-platform=wayland`. - Maximize the window. - See that the window isn't really maximized and there are still borders. Some notes: - The issue is not reproducible in Chromium 99.0.4844.51 with the same start flags, so that's probably not a bug in the window manager. - When removing the `WaylandWindowDecorations` feature flag, window maximizes correctly under Wayland (though there are no window decorations, so I have to maximize window using keyboard). - Maybe CC #29618 author? ![Screenshot](https://user-images.githubusercontent.com/29029632/156944326-4ac421cc-a2c1-4099-bf12-f0af1c29de4a.png)
https://github.com/electron/electron/issues/33161
https://github.com/electron/electron/pull/34955
4e8480b15b63cf71648f8f9357713b8827dec27c
7b8fb2b07418c7bad6ce811ca75c926ee53663fc
2022-03-06T22:40:31Z
c++
2022-08-03T08:51:52Z
patches/chromium/add_maximized_parameter_to_linuxui_getwindowframeprovider.patch
closed
electron/electron
https://github.com/electron/electron
33,161
[Bug]: Window has borders while maximized in 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 17.1.0 and 18.0.0-alpha.5 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior The window should have no borders when maximized. ### Actual Behavior Window has borders when maximized (at least in GNOME, I have not tested in other interfaces/window managers). ### Testcase Gist URL _No response_ ### Additional Information To reproduce: - Use a Wayland environment. - Start the Electron demo app with the flags: `--enable-features=WaylandWindowDecorations --ozone-platform=wayland`. - Maximize the window. - See that the window isn't really maximized and there are still borders. Some notes: - The issue is not reproducible in Chromium 99.0.4844.51 with the same start flags, so that's probably not a bug in the window manager. - When removing the `WaylandWindowDecorations` feature flag, window maximizes correctly under Wayland (though there are no window decorations, so I have to maximize window using keyboard). - Maybe CC #29618 author? ![Screenshot](https://user-images.githubusercontent.com/29029632/156944326-4ac421cc-a2c1-4099-bf12-f0af1c29de4a.png)
https://github.com/electron/electron/issues/33161
https://github.com/electron/electron/pull/34955
4e8480b15b63cf71648f8f9357713b8827dec27c
7b8fb2b07418c7bad6ce811ca75c926ee53663fc
2022-03-06T22:40:31Z
c++
2022-08-03T08:51:52Z
shell/browser/ui/views/client_frame_view_linux.cc
// Copyright (c) 2021 Ryan Gonzalez. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/views/client_frame_view_linux.h" #include <algorithm> #include "base/strings/utf_string_conversions.h" #include "cc/paint/paint_filter.h" #include "cc/paint/paint_flags.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "ui/base/hit_test.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/canvas.h" #include "ui/gfx/font_list.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/skia_util.h" #include "ui/gfx/text_constants.h" #include "ui/gtk/gtk_compat.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #include "ui/linux/linux_ui.h" #include "ui/linux/nav_button_provider.h" #include "ui/native_theme/native_theme.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/style/typography.h" #include "ui/views/widget/widget.h" #include "ui/views/window/frame_buttons.h" #include "ui/views/window/window_button_order_provider.h" namespace electron { namespace { // These values should be the same as Chromium uses. constexpr int kResizeOutsideBorderSize = 10; constexpr int kResizeInsideBoundsSize = 5; ui::NavButtonProvider::ButtonState ButtonStateToNavButtonProviderState( views::Button::ButtonState state) { switch (state) { case views::Button::STATE_NORMAL: return ui::NavButtonProvider::ButtonState::kNormal; case views::Button::STATE_HOVERED: return ui::NavButtonProvider::ButtonState::kHovered; case views::Button::STATE_PRESSED: return ui::NavButtonProvider::ButtonState::kPressed; case views::Button::STATE_DISABLED: return ui::NavButtonProvider::ButtonState::kDisabled; case views::Button::STATE_COUNT: default: NOTREACHED(); return ui::NavButtonProvider::ButtonState::kNormal; } } } // namespace // static const char ClientFrameViewLinux::kViewClassName[] = "ClientFrameView"; ClientFrameViewLinux::ClientFrameViewLinux() : theme_(ui::NativeTheme::GetInstanceForNativeUi()), nav_button_provider_(ui::LinuxUi::instance()->CreateNavButtonProvider()), nav_buttons_{ NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kClose, views::FrameButton::kClose, &views::Widget::Close, IDS_APP_ACCNAME_CLOSE, HTCLOSE}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kMaximize, views::FrameButton::kMaximize, &views::Widget::Maximize, IDS_APP_ACCNAME_MAXIMIZE, HTMAXBUTTON}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kRestore, views::FrameButton::kMaximize, &views::Widget::Restore, IDS_APP_ACCNAME_RESTORE, HTMAXBUTTON}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kMinimize, views::FrameButton::kMinimize, &views::Widget::Minimize, IDS_APP_ACCNAME_MINIMIZE, HTMINBUTTON}, }, trailing_frame_buttons_{views::FrameButton::kMinimize, views::FrameButton::kMaximize, views::FrameButton::kClose} { for (auto& button : nav_buttons_) { button.button = new views::ImageButton(); button.button->SetImageVerticalAlignment(views::ImageButton::ALIGN_MIDDLE); button.button->SetAccessibleName( l10n_util::GetStringUTF16(button.accessibility_id)); AddChildView(button.button); } title_ = new views::Label(); title_->SetSubpixelRenderingEnabled(false); title_->SetAutoColorReadabilityEnabled(false); title_->SetHorizontalAlignment(gfx::ALIGN_CENTER); title_->SetVerticalAlignment(gfx::ALIGN_MIDDLE); title_->SetTextStyle(views::style::STYLE_TAB_ACTIVE); AddChildView(title_); native_theme_observer_.Observe(theme_); if (ui::LinuxUi* ui = ui::LinuxUi::instance()) { ui->AddWindowButtonOrderObserver(this); OnWindowButtonOrderingChange(); } } ClientFrameViewLinux::~ClientFrameViewLinux() { if (ui::LinuxUi* ui = ui::LinuxUi::instance()) ui->RemoveWindowButtonOrderObserver(this); theme_->RemoveObserver(this); } void ClientFrameViewLinux::Init(NativeWindowViews* window, views::Widget* frame) { FramelessView::Init(window, frame); // Unretained() is safe because the subscription is saved into an instance // member and thus will be cancelled upon the instance's destruction. paint_as_active_changed_subscription_ = frame_->RegisterPaintAsActiveChangedCallback(base::BindRepeating( &ClientFrameViewLinux::PaintAsActiveChanged, base::Unretained(this))); auto* tree_host = static_cast<ElectronDesktopWindowTreeHostLinux*>( ElectronDesktopWindowTreeHostLinux::GetHostForWidget( window->GetAcceleratedWidget())); host_supports_client_frame_shadow_ = tree_host->SupportsClientFrameShadow(); frame_provider_ = ui::LinuxUi::instance()->GetWindowFrameProvider( !host_supports_client_frame_shadow_); UpdateWindowTitle(); for (auto& button : nav_buttons_) { // Unretained() is safe because the buttons are added as children to, and // thus owned by, this view. Thus, the buttons themselves will be destroyed // when this view is destroyed, and the frame's life must never outlive the // view. button.button->SetCallback( base::BindRepeating(button.callback, base::Unretained(frame))); } UpdateThemeValues(); } gfx::Insets ClientFrameViewLinux::GetBorderDecorationInsets() const { return frame_provider_->GetFrameThicknessDip(); } gfx::Insets ClientFrameViewLinux::GetInputInsets() const { return gfx::Insets( host_supports_client_frame_shadow_ ? -kResizeOutsideBorderSize : 0); } gfx::Rect ClientFrameViewLinux::GetWindowContentBounds() const { gfx::Rect content_bounds = bounds(); content_bounds.Inset(GetBorderDecorationInsets()); return content_bounds; } SkRRect ClientFrameViewLinux::GetRoundedWindowContentBounds() const { SkRect rect = gfx::RectToSkRect(GetWindowContentBounds()); SkRRect rrect; if (!frame_->IsMaximized()) { SkPoint round_point{theme_values_.window_border_radius, theme_values_.window_border_radius}; SkPoint radii[] = {round_point, round_point, {}, {}}; rrect.setRectRadii(rect, radii); } else { rrect.setRect(rect); } return rrect; } void ClientFrameViewLinux::OnNativeThemeUpdated( ui::NativeTheme* observed_theme) { UpdateThemeValues(); } void ClientFrameViewLinux::OnWindowButtonOrderingChange() { auto* provider = views::WindowButtonOrderProvider::GetInstance(); leading_frame_buttons_ = provider->leading_buttons(); trailing_frame_buttons_ = provider->trailing_buttons(); InvalidateLayout(); } int ClientFrameViewLinux::ResizingBorderHitTest(const gfx::Point& point) { return ResizingBorderHitTestImpl( point, GetBorderDecorationInsets() + gfx::Insets(kResizeInsideBoundsSize)); } gfx::Rect ClientFrameViewLinux::GetBoundsForClientView() const { gfx::Rect client_bounds = bounds(); if (!frame_->IsFullscreen()) { client_bounds.Inset(GetBorderDecorationInsets()); client_bounds.Inset( gfx::Insets::TLBR(0, GetTitlebarBounds().height(), 0, 0)); } return client_bounds; } gfx::Rect ClientFrameViewLinux::GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const { gfx::Insets insets = bounds().InsetsFrom(GetBoundsForClientView()); return gfx::Rect(std::max(0, client_bounds.x() - insets.left()), std::max(0, client_bounds.y() - insets.top()), client_bounds.width() + insets.width(), client_bounds.height() + insets.height()); } int ClientFrameViewLinux::NonClientHitTest(const gfx::Point& point) { int component = ResizingBorderHitTest(point); if (component != HTNOWHERE) { return component; } for (auto& button : nav_buttons_) { if (button.button->GetVisible() && button.button->GetMirroredBounds().Contains(point)) { return button.hit_test_id; } } if (GetTitlebarBounds().Contains(point)) { return HTCAPTION; } return FramelessView::NonClientHitTest(point); } void ClientFrameViewLinux::GetWindowMask(const gfx::Size& size, SkPath* window_mask) { // Nothing to do here, as transparency is used for decorations, not masks. } void ClientFrameViewLinux::UpdateWindowTitle() { title_->SetText(base::UTF8ToUTF16(window_->GetTitle())); } void ClientFrameViewLinux::SizeConstraintsChanged() { InvalidateLayout(); } gfx::Size ClientFrameViewLinux::CalculatePreferredSize() const { return SizeWithDecorations(FramelessView::CalculatePreferredSize()); } gfx::Size ClientFrameViewLinux::GetMinimumSize() const { return SizeWithDecorations(FramelessView::GetMinimumSize()); } gfx::Size ClientFrameViewLinux::GetMaximumSize() const { return SizeWithDecorations(FramelessView::GetMaximumSize()); } void ClientFrameViewLinux::Layout() { FramelessView::Layout(); if (frame_->IsFullscreen()) { // Just hide everything and return. for (NavButton& button : nav_buttons_) { button.button->SetVisible(false); } title_->SetVisible(false); return; } UpdateButtonImages(); LayoutButtons(); gfx::Rect title_bounds(GetTitlebarContentBounds()); title_bounds.Inset(theme_values_.title_padding); title_->SetVisible(true); title_->SetBounds(title_bounds.x(), title_bounds.y(), title_bounds.width(), title_bounds.height()); } void ClientFrameViewLinux::OnPaint(gfx::Canvas* canvas) { if (!frame_->IsFullscreen()) { frame_provider_->PaintWindowFrame(canvas, GetLocalBounds(), GetTitlebarBounds().bottom(), ShouldPaintAsActive()); } } const char* ClientFrameViewLinux::GetClassName() const { return kViewClassName; } void ClientFrameViewLinux::PaintAsActiveChanged() { UpdateThemeValues(); } void ClientFrameViewLinux::UpdateThemeValues() { gtk::GtkCssContext window_context = gtk::AppendCssNodeToStyleContext({}, "GtkWindow#window.background.csd"); gtk::GtkCssContext headerbar_context = gtk::AppendCssNodeToStyleContext( {}, "GtkHeaderBar#headerbar.default-decoration.titlebar"); gtk::GtkCssContext title_context = gtk::AppendCssNodeToStyleContext( headerbar_context, "GtkLabel#label.title"); gtk::GtkCssContext button_context = gtk::AppendCssNodeToStyleContext( headerbar_context, "GtkButton#button.image-button"); gtk_style_context_set_parent(headerbar_context, window_context); gtk_style_context_set_parent(title_context, headerbar_context); gtk_style_context_set_parent(button_context, headerbar_context); // ShouldPaintAsActive asks the widget, so assume active if the widget is not // set yet. if (GetWidget() != nullptr && !ShouldPaintAsActive()) { gtk_style_context_set_state(window_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(headerbar_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(title_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(button_context, GTK_STATE_FLAG_BACKDROP); } theme_values_.window_border_radius = frame_provider_->GetTopCornerRadiusDip(); gtk::GtkStyleContextGet(headerbar_context, "min-height", &theme_values_.titlebar_min_height, nullptr); theme_values_.titlebar_padding = gtk::GtkStyleContextGetPadding(headerbar_context); theme_values_.title_color = gtk::GtkStyleContextGetColor(title_context); theme_values_.title_padding = gtk::GtkStyleContextGetPadding(title_context); gtk::GtkStyleContextGet(button_context, "min-height", &theme_values_.button_min_size, nullptr); theme_values_.button_padding = gtk::GtkStyleContextGetPadding(button_context); title_->SetEnabledColor(theme_values_.title_color); InvalidateLayout(); SchedulePaint(); } ui::NavButtonProvider::FrameButtonDisplayType ClientFrameViewLinux::GetButtonTypeToSkip() const { return frame_->IsMaximized() ? ui::NavButtonProvider::FrameButtonDisplayType::kMaximize : ui::NavButtonProvider::FrameButtonDisplayType::kRestore; } void ClientFrameViewLinux::UpdateButtonImages() { nav_button_provider_->RedrawImages(theme_values_.button_min_size, frame_->IsMaximized(), ShouldPaintAsActive()); ui::NavButtonProvider::FrameButtonDisplayType skip_type = GetButtonTypeToSkip(); for (NavButton& button : nav_buttons_) { if (button.type == skip_type) { continue; } for (size_t state_id = 0; state_id < views::Button::STATE_COUNT; state_id++) { views::Button::ButtonState state = static_cast<views::Button::ButtonState>(state_id); button.button->SetImage( state, nav_button_provider_->GetImage( button.type, ButtonStateToNavButtonProviderState(state))); } } } void ClientFrameViewLinux::LayoutButtons() { for (NavButton& button : nav_buttons_) { button.button->SetVisible(false); } gfx::Rect remaining_content_bounds = GetTitlebarContentBounds(); LayoutButtonsOnSide(ButtonSide::kLeading, &remaining_content_bounds); LayoutButtonsOnSide(ButtonSide::kTrailing, &remaining_content_bounds); } void ClientFrameViewLinux::LayoutButtonsOnSide( ButtonSide side, gfx::Rect* remaining_content_bounds) { ui::NavButtonProvider::FrameButtonDisplayType skip_type = GetButtonTypeToSkip(); std::vector<views::FrameButton> frame_buttons; switch (side) { case ButtonSide::kLeading: frame_buttons = leading_frame_buttons_; break; case ButtonSide::kTrailing: frame_buttons = trailing_frame_buttons_; // We always lay buttons out going from the edge towards the center, but // they are given to us as left-to-right, so reverse them. std::reverse(frame_buttons.begin(), frame_buttons.end()); break; default: NOTREACHED(); } for (views::FrameButton frame_button : frame_buttons) { auto* button = std::find_if( nav_buttons_.begin(), nav_buttons_.end(), [&](const NavButton& test) { return test.type != skip_type && test.frame_button == frame_button; }); CHECK(button != nav_buttons_.end()) << "Failed to find frame button: " << static_cast<int>(frame_button); if (button->type == skip_type) { continue; } button->button->SetVisible(true); int button_width = theme_values_.button_min_size; int next_button_offset = button_width + nav_button_provider_->GetInterNavButtonSpacing(); int x_position = 0; gfx::Insets inset_after_placement; switch (side) { case ButtonSide::kLeading: x_position = remaining_content_bounds->x(); inset_after_placement.set_left(next_button_offset); break; case ButtonSide::kTrailing: x_position = remaining_content_bounds->right() - button_width; inset_after_placement.set_right(next_button_offset); break; default: NOTREACHED(); } button->button->SetBounds(x_position, remaining_content_bounds->y(), button_width, remaining_content_bounds->height()); remaining_content_bounds->Inset(inset_after_placement); } } gfx::Rect ClientFrameViewLinux::GetTitlebarBounds() const { if (frame_->IsFullscreen()) { return gfx::Rect(); } int font_height = gfx::FontList().GetHeight(); int titlebar_height = std::max(font_height, theme_values_.titlebar_min_height) + GetTitlebarContentInsets().height(); gfx::Insets decoration_insets = GetBorderDecorationInsets(); // We add the inset height here, so the .Inset() that follows won't reduce it // to be too small. gfx::Rect titlebar(width(), titlebar_height + decoration_insets.height()); titlebar.Inset(decoration_insets); return titlebar; } gfx::Insets ClientFrameViewLinux::GetTitlebarContentInsets() const { return theme_values_.titlebar_padding + nav_button_provider_->GetTopAreaSpacing(); } gfx::Rect ClientFrameViewLinux::GetTitlebarContentBounds() const { gfx::Rect titlebar(GetTitlebarBounds()); titlebar.Inset(GetTitlebarContentInsets()); return titlebar; } gfx::Size ClientFrameViewLinux::SizeWithDecorations(gfx::Size size) const { gfx::Insets decoration_insets = GetBorderDecorationInsets(); size.Enlarge(0, GetTitlebarBounds().height()); size.Enlarge(decoration_insets.width(), decoration_insets.height()); return size; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,161
[Bug]: Window has borders while maximized in 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 17.1.0 and 18.0.0-alpha.5 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior The window should have no borders when maximized. ### Actual Behavior Window has borders when maximized (at least in GNOME, I have not tested in other interfaces/window managers). ### Testcase Gist URL _No response_ ### Additional Information To reproduce: - Use a Wayland environment. - Start the Electron demo app with the flags: `--enable-features=WaylandWindowDecorations --ozone-platform=wayland`. - Maximize the window. - See that the window isn't really maximized and there are still borders. Some notes: - The issue is not reproducible in Chromium 99.0.4844.51 with the same start flags, so that's probably not a bug in the window manager. - When removing the `WaylandWindowDecorations` feature flag, window maximizes correctly under Wayland (though there are no window decorations, so I have to maximize window using keyboard). - Maybe CC #29618 author? ![Screenshot](https://user-images.githubusercontent.com/29029632/156944326-4ac421cc-a2c1-4099-bf12-f0af1c29de4a.png)
https://github.com/electron/electron/issues/33161
https://github.com/electron/electron/pull/34955
4e8480b15b63cf71648f8f9357713b8827dec27c
7b8fb2b07418c7bad6ce811ca75c926ee53663fc
2022-03-06T22:40:31Z
c++
2022-08-03T08:51:52Z
shell/browser/ui/views/client_frame_view_linux.h
// Copyright (c) 2021 Ryan Gonzalez. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_UI_VIEWS_CLIENT_FRAME_VIEW_LINUX_H_ #define ELECTRON_SHELL_BROWSER_UI_VIEWS_CLIENT_FRAME_VIEW_LINUX_H_ #include <array> #include <memory> #include <vector> #include "base/scoped_observation.h" #include "shell/browser/ui/views/frameless_view.h" #include "ui/linux/linux_ui.h" #include "ui/linux/nav_button_provider.h" #include "ui/linux/window_button_order_observer.h" #include "ui/linux/window_frame_provider.h" #include "ui/native_theme/native_theme.h" #include "ui/native_theme/native_theme_observer.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/label.h" #include "ui/views/widget/widget.h" #include "ui/views/window/frame_buttons.h" namespace electron { class ClientFrameViewLinux : public FramelessView, public ui::NativeThemeObserver, public ui::WindowButtonOrderObserver { public: static const char kViewClassName[]; ClientFrameViewLinux(); ~ClientFrameViewLinux() override; void Init(NativeWindowViews* window, views::Widget* frame) override; // These are here for ElectronDesktopWindowTreeHostLinux to use. gfx::Insets GetBorderDecorationInsets() const; gfx::Insets GetInputInsets() const; gfx::Rect GetWindowContentBounds() const; SkRRect GetRoundedWindowContentBounds() const; protected: // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override; // views::WindowButtonOrderObserver: void OnWindowButtonOrderingChange() override; // Overridden from FramelessView: int ResizingBorderHitTest(const gfx::Point& point) override; // Overridden from views::NonClientFrameView: gfx::Rect GetBoundsForClientView() const override; gfx::Rect GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const override; int NonClientHitTest(const gfx::Point& point) override; void GetWindowMask(const gfx::Size& size, SkPath* window_mask) override; void UpdateWindowTitle() override; void SizeConstraintsChanged() override; // Overridden from View: gfx::Size CalculatePreferredSize() const override; gfx::Size GetMinimumSize() const override; gfx::Size GetMaximumSize() const override; void Layout() override; void OnPaint(gfx::Canvas* canvas) override; const char* GetClassName() const override; private: static constexpr int kNavButtonCount = 4; struct NavButton { ui::NavButtonProvider::FrameButtonDisplayType type; views::FrameButton frame_button; void (views::Widget::*callback)(); int accessibility_id; int hit_test_id; views::ImageButton* button{nullptr}; }; struct ThemeValues { float window_border_radius; int titlebar_min_height; gfx::Insets titlebar_padding; SkColor title_color; gfx::Insets title_padding; int button_min_size; gfx::Insets button_padding; }; void PaintAsActiveChanged(); void UpdateThemeValues(); enum class ButtonSide { kLeading, kTrailing }; ui::NavButtonProvider::FrameButtonDisplayType GetButtonTypeToSkip() const; void UpdateButtonImages(); void LayoutButtons(); void LayoutButtonsOnSide(ButtonSide side, gfx::Rect* remaining_content_bounds); gfx::Rect GetTitlebarBounds() const; gfx::Insets GetTitlebarContentInsets() const; gfx::Rect GetTitlebarContentBounds() const; gfx::Size SizeWithDecorations(gfx::Size size) const; ui::NativeTheme* theme_; ThemeValues theme_values_; views::Label* title_; std::unique_ptr<ui::NavButtonProvider> nav_button_provider_; std::array<NavButton, kNavButtonCount> nav_buttons_; std::vector<views::FrameButton> leading_frame_buttons_; std::vector<views::FrameButton> trailing_frame_buttons_; bool host_supports_client_frame_shadow_ = false; ui::WindowFrameProvider* frame_provider_; base::ScopedObservation<ui::NativeTheme, ui::NativeThemeObserver> native_theme_observer_{this}; base::ScopedObservation<ui::LinuxUi, ui::WindowButtonOrderObserver, &ui::LinuxUi::AddWindowButtonOrderObserver, &ui::LinuxUi::RemoveWindowButtonOrderObserver> window_button_order_observer_{this}; base::CallbackListSubscription paint_as_active_changed_subscription_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_VIEWS_CLIENT_FRAME_VIEW_LINUX_H_
closed
electron/electron
https://github.com/electron/electron
14,261
Having config menu popping up above bottom of windows instead of having to scroll.
**Is your feature request related to a problem? Please describe.** I use VS Code maximized or full screen, and clicking on the config gear always bring a truncated menu. I'd rather have it in full and higher because I have to scroll every time. I filed this previously on VS Code and they correctly redirected me here: https://github.com/Microsoft/vscode/issues/56921 **Describe the solution you'd like** Having config menu popping up above bottom and expanded in full instead of having to scroll. **Describe alternatives you've considered** I can scroll instead. **Additional context** I'm using MacOS 10.13.16 Showing might help, please see my two screen shots. Thank you for your time. <img width="285" alt="44414137-088e5800-a53b-11e8-8228-76cda8f27744" src="https://user-images.githubusercontent.com/1154213/44468739-e99fcc80-a5f3-11e8-9259-809c696bee0a.png"> <img width="210" alt="44414136-07f5c180-a53b-11e8-9fc0-39286d6a14d3" src="https://user-images.githubusercontent.com/1154213/44468740-e99fcc80-a5f3-11e8-9278-4c1419fc3b88.png">
https://github.com/electron/electron/issues/14261
https://github.com/electron/electron/pull/35194
7b8fb2b07418c7bad6ce811ca75c926ee53663fc
afa4f5052bf5984821b01729a94dcd5b0e04d794
2018-08-22T14:15:16Z
c++
2022-08-03T08:52:42Z
shell/browser/api/electron_api_menu_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. #import "shell/browser/api/electron_api_menu_mac.h" #include <string> #include <utility> #include "base/mac/scoped_sending_event.h" #include "base/strings/sys_string_conversions.h" #include "base/task/current_thread.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/web_contents.h" #include "shell/browser/native_window.h" #include "shell/browser/unresponsive_suppressor.h" #include "shell/common/keyboard_util.h" #include "shell/common/node_includes.h" namespace { static scoped_nsobject<NSMenu> applicationMenu_; ui::Accelerator GetAcceleratorFromKeyEquivalentAndModifierMask( NSString* key_equivalent, NSUInteger modifier_mask) { absl::optional<char16_t> shifted_char; ui::KeyboardCode code = electron::KeyboardCodeFromStr( base::SysNSStringToUTF8(key_equivalent), &shifted_char); int modifiers = 0; if (modifier_mask & NSEventModifierFlagShift) modifiers |= ui::EF_SHIFT_DOWN; if (modifier_mask & NSEventModifierFlagControl) modifiers |= ui::EF_CONTROL_DOWN; if (modifier_mask & NSEventModifierFlagOption) modifiers |= ui::EF_ALT_DOWN; if (modifier_mask & NSEventModifierFlagCommand) modifiers |= ui::EF_COMMAND_DOWN; return ui::Accelerator(code, modifiers); } } // namespace namespace electron::api { MenuMac::MenuMac(gin::Arguments* args) : Menu(args) {} MenuMac::~MenuMac() = default; void MenuMac::PopupAt(BaseWindow* window, int x, int y, int positioning_item, base::OnceClosure callback) { NativeWindow* native_window = window->window(); if (!native_window) return; // Make sure the Menu object would not be garbage-collected until the callback // has run. base::OnceClosure callback_with_ref = BindSelfToClosure(std::move(callback)); auto popup = base::BindOnce(&MenuMac::PopupOnUI, weak_factory_.GetWeakPtr(), native_window->GetWeakPtr(), window->weak_map_id(), x, y, positioning_item, std::move(callback_with_ref)); base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(popup)); } v8::Local<v8::Value> Menu::GetUserAcceleratorAt(int command_id) const { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); if (![NSMenuItem usesUserKeyEquivalents]) return v8::Null(isolate); auto controller = base::scoped_nsobject<ElectronMenuController>( [[ElectronMenuController alloc] initWithModel:model() useDefaultAccelerator:NO]); int command_index = GetIndexOfCommandId(command_id); if (command_index == -1) return v8::Null(isolate); base::scoped_nsobject<NSMenuItem> item = [controller makeMenuItemForIndex:command_index fromModel:model()]; if ([[item userKeyEquivalent] length] == 0) return v8::Null(isolate); NSString* user_key_equivalent = [item keyEquivalent]; NSUInteger user_modifier_mask = [item keyEquivalentModifierMask]; ui::Accelerator accelerator = GetAcceleratorFromKeyEquivalentAndModifierMask( user_key_equivalent, user_modifier_mask); return gin::ConvertToV8(isolate, accelerator.GetShortcutText()); } void MenuMac::PopupOnUI(const base::WeakPtr<NativeWindow>& native_window, int32_t window_id, int x, int y, int positioning_item, base::OnceClosure callback) { if (!native_window) return; NSWindow* nswindow = native_window->GetNativeWindow().GetNativeNSWindow(); base::OnceClosure close_callback = base::BindOnce(&MenuMac::OnClosed, weak_factory_.GetWeakPtr(), window_id, std::move(callback)); popup_controllers_[window_id] = base::scoped_nsobject<ElectronMenuController>( [[ElectronMenuController alloc] initWithModel:model() useDefaultAccelerator:NO]); NSMenu* menu = [popup_controllers_[window_id] menu]; NSView* view = [nswindow contentView]; // Which menu item to show. NSMenuItem* item = nil; if (positioning_item < [menu numberOfItems] && positioning_item >= 0) item = [menu itemAtIndex:positioning_item]; // (-1, -1) means showing on mouse location. NSPoint position; if (x == -1 || y == -1) { position = [view convertPoint:[nswindow mouseLocationOutsideOfEventStream] fromView:nil]; } else { position = NSMakePoint(x, [view frame].size.height - y); } // If no preferred item is specified, try to show all of the menu items. if (!item) { CGFloat windowBottom = CGRectGetMinY([view window].frame); CGFloat lowestMenuPoint = windowBottom + position.y - [menu size].height; CGFloat screenBottom = CGRectGetMinY([view window].screen.frame); CGFloat distanceFromBottom = lowestMenuPoint - screenBottom; if (distanceFromBottom < 0) position.y = position.y - distanceFromBottom + 4; } // Place the menu left of cursor if it is overflowing off right of screen. CGFloat windowLeft = CGRectGetMinX([view window].frame); CGFloat rightmostMenuPoint = windowLeft + position.x + [menu size].width; CGFloat screenRight = CGRectGetMaxX([view window].screen.frame); if (rightmostMenuPoint > screenRight) position.x = position.x - [menu size].width; [popup_controllers_[window_id] setCloseCallback:std::move(close_callback)]; // Make sure events can be pumped while the menu is up. base::CurrentThread::ScopedNestableTaskAllower allow; // One of the events that could be pumped is |window.close()|. // User-initiated event-tracking loops protect against this by // setting flags in -[CrApplication sendEvent:], but since // web-content menus are initiated by IPC message the setup has to // be done manually. base::mac::ScopedSendingEvent sendingEventScoper; // Don't emit unresponsive event when showing menu. electron::UnresponsiveSuppressor suppressor; [menu popUpMenuPositioningItem:item atLocation:position inView:view]; } void MenuMac::ClosePopupAt(int32_t window_id) { auto close_popup = base::BindOnce(&MenuMac::ClosePopupOnUI, weak_factory_.GetWeakPtr(), window_id); base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(close_popup)); } std::u16string MenuMac::GetAcceleratorTextAtForTesting(int index) const { // A least effort to get the real shortcut text of NSMenuItem, the code does // not need to be perfect since it is test only. base::scoped_nsobject<ElectronMenuController> controller( [[ElectronMenuController alloc] initWithModel:model() useDefaultAccelerator:NO]); NSMenuItem* item = [[controller menu] itemAtIndex:index]; std::u16string text; NSEventModifierFlags modifiers = [item keyEquivalentModifierMask]; if (modifiers & NSEventModifierFlagControl) text += u"Ctrl"; if (modifiers & NSEventModifierFlagShift) { if (!text.empty()) text += u"+"; text += u"Shift"; } if (modifiers & NSEventModifierFlagOption) { if (!text.empty()) text += u"+"; text += u"Alt"; } if (modifiers & NSEventModifierFlagCommand) { if (!text.empty()) text += u"+"; text += u"Command"; } if (!text.empty()) text += u"+"; auto key = base::ToUpperASCII(base::SysNSStringToUTF16([item keyEquivalent])); if (key == u"\t") text += u"Tab"; else text += key; return text; } void MenuMac::ClosePopupOnUI(int32_t window_id) { auto controller = popup_controllers_.find(window_id); if (controller != popup_controllers_.end()) { // Close the controller for the window. [controller->second cancel]; } else if (window_id == -1) { // Or just close all opened controllers. for (auto it = popup_controllers_.begin(); it != popup_controllers_.end();) { // The iterator is invalidated after the call. [(it++)->second cancel]; } } } void MenuMac::OnClosed(int32_t window_id, base::OnceClosure callback) { popup_controllers_.erase(window_id); std::move(callback).Run(); } // static void Menu::SetApplicationMenu(Menu* base_menu) { MenuMac* menu = static_cast<MenuMac*>(base_menu); base::scoped_nsobject<ElectronMenuController> menu_controller( [[ElectronMenuController alloc] initWithModel:menu->model_.get() useDefaultAccelerator:YES]); NSRunLoop* currentRunLoop = [NSRunLoop currentRunLoop]; [currentRunLoop cancelPerformSelector:@selector(setMainMenu:) target:NSApp argument:applicationMenu_]; applicationMenu_.reset([[menu_controller menu] retain]); [[NSRunLoop currentRunLoop] performSelector:@selector(setMainMenu:) target:NSApp argument:applicationMenu_ order:0 modes:[NSArray arrayWithObject:NSDefaultRunLoopMode]]; // Ensure the menu_controller_ is destroyed after main menu is set. menu_controller.swap(menu->menu_controller_); } // static void Menu::SendActionToFirstResponder(const std::string& action) { SEL selector = NSSelectorFromString(base::SysUTF8ToNSString(action)); [NSApp sendAction:selector to:nil from:[NSApp mainMenu]]; } // static gin::Handle<Menu> Menu::New(gin::Arguments* args) { auto handle = gin::CreateHandle(args->isolate(), static_cast<Menu*>(new MenuMac(args))); gin_helper::CallMethod(args->isolate(), handle.get(), "_init"); return handle; } } // namespace electron::api
closed
electron/electron
https://github.com/electron/electron
14,261
Having config menu popping up above bottom of windows instead of having to scroll.
**Is your feature request related to a problem? Please describe.** I use VS Code maximized or full screen, and clicking on the config gear always bring a truncated menu. I'd rather have it in full and higher because I have to scroll every time. I filed this previously on VS Code and they correctly redirected me here: https://github.com/Microsoft/vscode/issues/56921 **Describe the solution you'd like** Having config menu popping up above bottom and expanded in full instead of having to scroll. **Describe alternatives you've considered** I can scroll instead. **Additional context** I'm using MacOS 10.13.16 Showing might help, please see my two screen shots. Thank you for your time. <img width="285" alt="44414137-088e5800-a53b-11e8-8228-76cda8f27744" src="https://user-images.githubusercontent.com/1154213/44468739-e99fcc80-a5f3-11e8-9259-809c696bee0a.png"> <img width="210" alt="44414136-07f5c180-a53b-11e8-9fc0-39286d6a14d3" src="https://user-images.githubusercontent.com/1154213/44468740-e99fcc80-a5f3-11e8-9278-4c1419fc3b88.png">
https://github.com/electron/electron/issues/14261
https://github.com/electron/electron/pull/35194
7b8fb2b07418c7bad6ce811ca75c926ee53663fc
afa4f5052bf5984821b01729a94dcd5b0e04d794
2018-08-22T14:15:16Z
c++
2022-08-03T08:52:42Z
shell/browser/api/electron_api_menu_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. #import "shell/browser/api/electron_api_menu_mac.h" #include <string> #include <utility> #include "base/mac/scoped_sending_event.h" #include "base/strings/sys_string_conversions.h" #include "base/task/current_thread.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/web_contents.h" #include "shell/browser/native_window.h" #include "shell/browser/unresponsive_suppressor.h" #include "shell/common/keyboard_util.h" #include "shell/common/node_includes.h" namespace { static scoped_nsobject<NSMenu> applicationMenu_; ui::Accelerator GetAcceleratorFromKeyEquivalentAndModifierMask( NSString* key_equivalent, NSUInteger modifier_mask) { absl::optional<char16_t> shifted_char; ui::KeyboardCode code = electron::KeyboardCodeFromStr( base::SysNSStringToUTF8(key_equivalent), &shifted_char); int modifiers = 0; if (modifier_mask & NSEventModifierFlagShift) modifiers |= ui::EF_SHIFT_DOWN; if (modifier_mask & NSEventModifierFlagControl) modifiers |= ui::EF_CONTROL_DOWN; if (modifier_mask & NSEventModifierFlagOption) modifiers |= ui::EF_ALT_DOWN; if (modifier_mask & NSEventModifierFlagCommand) modifiers |= ui::EF_COMMAND_DOWN; return ui::Accelerator(code, modifiers); } } // namespace namespace electron::api { MenuMac::MenuMac(gin::Arguments* args) : Menu(args) {} MenuMac::~MenuMac() = default; void MenuMac::PopupAt(BaseWindow* window, int x, int y, int positioning_item, base::OnceClosure callback) { NativeWindow* native_window = window->window(); if (!native_window) return; // Make sure the Menu object would not be garbage-collected until the callback // has run. base::OnceClosure callback_with_ref = BindSelfToClosure(std::move(callback)); auto popup = base::BindOnce(&MenuMac::PopupOnUI, weak_factory_.GetWeakPtr(), native_window->GetWeakPtr(), window->weak_map_id(), x, y, positioning_item, std::move(callback_with_ref)); base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(popup)); } v8::Local<v8::Value> Menu::GetUserAcceleratorAt(int command_id) const { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); if (![NSMenuItem usesUserKeyEquivalents]) return v8::Null(isolate); auto controller = base::scoped_nsobject<ElectronMenuController>( [[ElectronMenuController alloc] initWithModel:model() useDefaultAccelerator:NO]); int command_index = GetIndexOfCommandId(command_id); if (command_index == -1) return v8::Null(isolate); base::scoped_nsobject<NSMenuItem> item = [controller makeMenuItemForIndex:command_index fromModel:model()]; if ([[item userKeyEquivalent] length] == 0) return v8::Null(isolate); NSString* user_key_equivalent = [item keyEquivalent]; NSUInteger user_modifier_mask = [item keyEquivalentModifierMask]; ui::Accelerator accelerator = GetAcceleratorFromKeyEquivalentAndModifierMask( user_key_equivalent, user_modifier_mask); return gin::ConvertToV8(isolate, accelerator.GetShortcutText()); } void MenuMac::PopupOnUI(const base::WeakPtr<NativeWindow>& native_window, int32_t window_id, int x, int y, int positioning_item, base::OnceClosure callback) { if (!native_window) return; NSWindow* nswindow = native_window->GetNativeWindow().GetNativeNSWindow(); base::OnceClosure close_callback = base::BindOnce(&MenuMac::OnClosed, weak_factory_.GetWeakPtr(), window_id, std::move(callback)); popup_controllers_[window_id] = base::scoped_nsobject<ElectronMenuController>( [[ElectronMenuController alloc] initWithModel:model() useDefaultAccelerator:NO]); NSMenu* menu = [popup_controllers_[window_id] menu]; NSView* view = [nswindow contentView]; // Which menu item to show. NSMenuItem* item = nil; if (positioning_item < [menu numberOfItems] && positioning_item >= 0) item = [menu itemAtIndex:positioning_item]; // (-1, -1) means showing on mouse location. NSPoint position; if (x == -1 || y == -1) { position = [view convertPoint:[nswindow mouseLocationOutsideOfEventStream] fromView:nil]; } else { position = NSMakePoint(x, [view frame].size.height - y); } // If no preferred item is specified, try to show all of the menu items. if (!item) { CGFloat windowBottom = CGRectGetMinY([view window].frame); CGFloat lowestMenuPoint = windowBottom + position.y - [menu size].height; CGFloat screenBottom = CGRectGetMinY([view window].screen.frame); CGFloat distanceFromBottom = lowestMenuPoint - screenBottom; if (distanceFromBottom < 0) position.y = position.y - distanceFromBottom + 4; } // Place the menu left of cursor if it is overflowing off right of screen. CGFloat windowLeft = CGRectGetMinX([view window].frame); CGFloat rightmostMenuPoint = windowLeft + position.x + [menu size].width; CGFloat screenRight = CGRectGetMaxX([view window].screen.frame); if (rightmostMenuPoint > screenRight) position.x = position.x - [menu size].width; [popup_controllers_[window_id] setCloseCallback:std::move(close_callback)]; // Make sure events can be pumped while the menu is up. base::CurrentThread::ScopedNestableTaskAllower allow; // One of the events that could be pumped is |window.close()|. // User-initiated event-tracking loops protect against this by // setting flags in -[CrApplication sendEvent:], but since // web-content menus are initiated by IPC message the setup has to // be done manually. base::mac::ScopedSendingEvent sendingEventScoper; // Don't emit unresponsive event when showing menu. electron::UnresponsiveSuppressor suppressor; [menu popUpMenuPositioningItem:item atLocation:position inView:view]; } void MenuMac::ClosePopupAt(int32_t window_id) { auto close_popup = base::BindOnce(&MenuMac::ClosePopupOnUI, weak_factory_.GetWeakPtr(), window_id); base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(close_popup)); } std::u16string MenuMac::GetAcceleratorTextAtForTesting(int index) const { // A least effort to get the real shortcut text of NSMenuItem, the code does // not need to be perfect since it is test only. base::scoped_nsobject<ElectronMenuController> controller( [[ElectronMenuController alloc] initWithModel:model() useDefaultAccelerator:NO]); NSMenuItem* item = [[controller menu] itemAtIndex:index]; std::u16string text; NSEventModifierFlags modifiers = [item keyEquivalentModifierMask]; if (modifiers & NSEventModifierFlagControl) text += u"Ctrl"; if (modifiers & NSEventModifierFlagShift) { if (!text.empty()) text += u"+"; text += u"Shift"; } if (modifiers & NSEventModifierFlagOption) { if (!text.empty()) text += u"+"; text += u"Alt"; } if (modifiers & NSEventModifierFlagCommand) { if (!text.empty()) text += u"+"; text += u"Command"; } if (!text.empty()) text += u"+"; auto key = base::ToUpperASCII(base::SysNSStringToUTF16([item keyEquivalent])); if (key == u"\t") text += u"Tab"; else text += key; return text; } void MenuMac::ClosePopupOnUI(int32_t window_id) { auto controller = popup_controllers_.find(window_id); if (controller != popup_controllers_.end()) { // Close the controller for the window. [controller->second cancel]; } else if (window_id == -1) { // Or just close all opened controllers. for (auto it = popup_controllers_.begin(); it != popup_controllers_.end();) { // The iterator is invalidated after the call. [(it++)->second cancel]; } } } void MenuMac::OnClosed(int32_t window_id, base::OnceClosure callback) { popup_controllers_.erase(window_id); std::move(callback).Run(); } // static void Menu::SetApplicationMenu(Menu* base_menu) { MenuMac* menu = static_cast<MenuMac*>(base_menu); base::scoped_nsobject<ElectronMenuController> menu_controller( [[ElectronMenuController alloc] initWithModel:menu->model_.get() useDefaultAccelerator:YES]); NSRunLoop* currentRunLoop = [NSRunLoop currentRunLoop]; [currentRunLoop cancelPerformSelector:@selector(setMainMenu:) target:NSApp argument:applicationMenu_]; applicationMenu_.reset([[menu_controller menu] retain]); [[NSRunLoop currentRunLoop] performSelector:@selector(setMainMenu:) target:NSApp argument:applicationMenu_ order:0 modes:[NSArray arrayWithObject:NSDefaultRunLoopMode]]; // Ensure the menu_controller_ is destroyed after main menu is set. menu_controller.swap(menu->menu_controller_); } // static void Menu::SendActionToFirstResponder(const std::string& action) { SEL selector = NSSelectorFromString(base::SysUTF8ToNSString(action)); [NSApp sendAction:selector to:nil from:[NSApp mainMenu]]; } // static gin::Handle<Menu> Menu::New(gin::Arguments* args) { auto handle = gin::CreateHandle(args->isolate(), static_cast<Menu*>(new MenuMac(args))); gin_helper::CallMethod(args->isolate(), handle.get(), "_init"); return handle; } } // namespace electron::api
closed
electron/electron
https://github.com/electron/electron
33,686
[Bug]: app.relaunch loses args when execPath specified.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.1 ### What operating system are you using? macOS ### Operating System Version 10.14.6 ### What arch are you using? x64 ### Last Known Working Electron version 17.0.0-alpha.3 ### Expected Behavior When invoking `app.relaunch` and specifying both `execPath` and `args`, I expect the args to be passed to the new process. ### Actual Behavior The binary specified by `execPath` is spawned as a new process, but the `args` are not applied. ### Testcase Gist URL https://gist.github.com/p120ph37/98cf0fb13790feed702f3e90cbddfbf6 ### Additional Information This bug was introduced in `17.0.0-alpha.4`, and is present in all newer stable versions up to and including at least `19.0.0-alpha.1` Also note that `app.relaunch()` doesn't work at all from within Electron Fiddle, so to run this gist, you must launch Electron directly (e.g.: via `npm start`).
https://github.com/electron/electron/issues/33686
https://github.com/electron/electron/pull/35108
34b985c5560aac4bb86d3697f8358647d38e79a7
91f9436ad8e6028bf2909008e5814867289b9310
2022-04-08T22:21:17Z
c++
2022-08-08T08:12:06Z
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/callback_helpers.h" #include "base/command_line.h" #include "base/containers/span.h" #include "base/environment.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/path_service.h" #include "base/system/sys_info.h" #include "base/values.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_web_contents.h" #include "shell/browser/api/gpuinfo_manager.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/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/platform_util.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) { std::string item_type; if (!ConvertFromV8(isolate, val, &item_type)) return false; if (item_type == "task") *out = JumpListItem::Type::kTask; else if (item_type == "separator") *out = JumpListItem::Type::kSeparator; else if (item_type == "file") *out = JumpListItem::Type::kFile; else return false; return true; } static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, JumpListItem::Type val) { std::string item_type; switch (val) { case JumpListItem::Type::kTask: item_type = "task"; break; case JumpListItem::Type::kSeparator: item_type = "separator"; break; case JumpListItem::Type::kFile: item_type = "file"; break; } return gin::ConvertToV8(isolate, item_type); } }; 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) { gin_helper::Dictionary dict = gin::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) { std::string category_type; if (!ConvertFromV8(isolate, val, &category_type)) return false; if (category_type == "tasks") *out = JumpListCategory::Type::kTasks; else if (category_type == "frequent") *out = JumpListCategory::Type::kFrequent; else if (category_type == "recent") *out = JumpListCategory::Type::kRecent; else if (category_type == "custom") *out = JumpListCategory::Type::kCustom; else return false; return true; } static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, JumpListCategory::Type val) { std::string category_type; switch (val) { case JumpListCategory::Type::kTasks: category_type = "tasks"; break; case JumpListCategory::Type::kFrequent: category_type = "frequent"; break; case JumpListCategory::Type::kRecent: category_type = "recent"; break; case JumpListCategory::Type::kCustom: category_type = "custom"; break; } return gin::ConvertToV8(isolate, category_type); } }; 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) { gin_helper::Dictionary dict = gin::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) { gin_helper::Dictionary dict = gin::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) { std::string s; if (!ConvertFromV8(isolate, val, &s)) return false; if (s == "off") { *out = net::SecureDnsMode::kOff; return true; } else if (s == "automatic") { *out = net::SecureDnsMode::kAutomatic; return true; } else if (s == "secure") { *out = net::SecureDnsMode::kSecure; return true; } return false; } }; } // 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(const std::string& name) { if (name == "appData") return DIR_APP_DATA; else if (name == "sessionData") return DIR_SESSION_DATA; else if (name == "userData") return chrome::DIR_USER_DATA; else if (name == "cache") #if BUILDFLAG(IS_POSIX) return base::DIR_CACHE; #else return base::DIR_ROAMING_APP_DATA; #endif else if (name == "userCache") return DIR_USER_CACHE; else if (name == "logs") return DIR_APP_LOGS; else if (name == "crashDumps") return DIR_CRASH_DUMPS; else if (name == "home") return base::DIR_HOME; else if (name == "temp") return base::DIR_TEMP; else if (name == "userDesktop" || name == "desktop") return base::DIR_USER_DESKTOP; else if (name == "exe") return base::FILE_EXE; else if (name == "module") return base::FILE_MODULE; else if (name == "documents") return chrome::DIR_USER_DOCUMENTS; else if (name == "downloads") return chrome::DIR_DEFAULT_DOWNLOADS; else if (name == "music") return chrome::DIR_USER_MUSIC; else if (name == "pictures") return chrome::DIR_USER_PICTURES; else if (name == "videos") return chrome::DIR_USER_VIDEOS; #if BUILDFLAG(IS_WIN) else if (name == "recent") return electron::DIR_RECENT; #endif else return -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::ThreadTaskRunnerHandle::Get()); // 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; std::string* cert_path_ptr = options.FindStringKey("certificate"); if (cert_path_ptr) cert_path = *cert_path_ptr; std::string* pwd = options.FindStringKey("password"); if (pwd) password = base::UTF8ToUTF16(*pwd); 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_) { process_singleton_->OnBrowserReady(); } } 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"); } #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::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); } 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; } { base::ThreadRestrictions::ScopedAllowIO allow_io; 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")); { base::ThreadRestrictions::ScopedAllowIO allow_io; 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::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), &region); } #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::LOCK_ERROR: case ProcessSingleton::NotifyResult::PROFILE_IN_USE: case ProcessSingleton::NotifyResult::PROCESS_NOTIFIED: { process_singleton_.reset(); return false; } case ProcessSingleton::NotifyResult::PROCESS_NONE: default: // Shouldn't be needed, but VS warns if it is not there. return true; } } 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)) { if (options.Get("execPath", &exec_path) || options.Get("args", &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, &current_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(); gin_helper::Dictionary dict = gin::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_) { gin_helper::Dictionary pid_dict = gin::Dictionary::CreateEmpty(isolate); gin_helper::Dictionary cpu_dict = gin::Dictionary::CreateEmpty(isolate); pid_dict.SetHidden("simple", true); cpu_dict.SetHidden("simple", true); 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(); gin_helper::Dictionary memory_dict = gin::Dictionary::CreateEmpty(isolate); memory_dict.SetHidden("simple", true); 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 { USHORT processMachine = 0; USHORT nativeMachine = 0; auto IsWow64Process2 = reinterpret_cast<decltype(&::IsWow64Process2)>( GetProcAddress(GetModuleHandle(L"kernel32.dll"), "IsWow64Process2")); if (IsWow64Process2 == nullptr) { return false; } if (!IsWow64Process2(GetCurrentProcess(), &processMachine, &nativeMachine)) { return false; } return nativeMachine == IMAGE_FILE_MACHINE_ARM64; } #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()); gin_helper::Dictionary dock_obj = gin::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("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 defined(MAS_BUILD) .SetMethod("startAccessingSecurityScopedResource", &App::StartAccessingSecurityScopedResource) #endif #if BUILDFLAG(IS_MAC) .SetProperty("dock", &App::GetDockAPI) .SetProperty("runningUnderRosettaTranslation", &App::IsRunningUnderRosettaTranslation) #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_MODULE_CONTEXT_AWARE(electron_browser_app, Initialize)
closed
electron/electron
https://github.com/electron/electron
33,686
[Bug]: app.relaunch loses args when execPath specified.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.1 ### What operating system are you using? macOS ### Operating System Version 10.14.6 ### What arch are you using? x64 ### Last Known Working Electron version 17.0.0-alpha.3 ### Expected Behavior When invoking `app.relaunch` and specifying both `execPath` and `args`, I expect the args to be passed to the new process. ### Actual Behavior The binary specified by `execPath` is spawned as a new process, but the `args` are not applied. ### Testcase Gist URL https://gist.github.com/p120ph37/98cf0fb13790feed702f3e90cbddfbf6 ### Additional Information This bug was introduced in `17.0.0-alpha.4`, and is present in all newer stable versions up to and including at least `19.0.0-alpha.1` Also note that `app.relaunch()` doesn't work at all from within Electron Fiddle, so to run this gist, you must launch Electron directly (e.g.: via `npm start`).
https://github.com/electron/electron/issues/33686
https://github.com/electron/electron/pull/35108
34b985c5560aac4bb86d3697f8358647d38e79a7
91f9436ad8e6028bf2909008e5814867289b9310
2022-04-08T22:21:17Z
c++
2022-08-08T08:12:06Z
spec-main/api-app-spec.ts
import { assert, expect } from 'chai'; import * as cp from 'child_process'; import * as https from 'https'; import * as http from 'http'; import * as net from 'net'; import * as fs from 'fs-extra'; import * as path from 'path'; import { promisify } from 'util'; import { app, BrowserWindow, Menu, session, net as electronNet } from 'electron/main'; import { emittedOnce } from './events-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; import { ifdescribe, ifit, waitUntil } from './spec-helpers'; import split = require('split') const fixturesPath = path.resolve(__dirname, '../spec/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((done) => { 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>'); } }); server.listen(0, '127.0.0.1', () => { const port = (server.address() as net.AddressInfo).port; secureUrl = `https://127.0.0.1:${port}`; done(); }); }); 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.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 emittedOnce(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 emittedOnce(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'); }); it('exits gracefully', async function () { if (!['darwin', 'linux'].includes(process.platform)) { this.skip(); return; } 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 emittedOnce(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 emittedOnce(first.stdout, 'data'); // Start second app when received output. const second = cp.spawn(process.execPath, [appPath]); const [code2] = await emittedOnce(second, 'exit'); expect(code2).to.equal(1); const [code1] = await emittedOnce(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 emittedOnce(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 = emittedOnce(first, 'exit'); // Wait for the first app to boot. const firstStdoutLines = first.stdout.pipe(split()); while ((await emittedOnce(firstStdoutLines, 'data')).toString() !== 'started') { // wait. } const additionalDataPromise = emittedOnce(firstStdoutLines, 'data'); const secondInstanceArgs = [process.execPath, appPath, ...testArgs.args, '--some-switch', 'some-arg']; const second = cp.spawn(secondInstanceArgs[0], secondInstanceArgs.slice(1)); const secondExited = emittedOnce(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 (e) { // 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) === 'false' && state === 'none') { state = 'first-launch'; } else if (String(data) === 'true' && state === 'first-launch') { done(); } else { done(`Unexpected state: "${state}", data: "${data}"`); } }); }); const appPath = path.join(fixturesPath, 'api', 'relaunch'); const child = cp.spawn(process.execPath, [appPath]); 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}"`); } }); }); }); describe('app.setUserActivity(type, userInfo)', () => { before(function () { if (process.platform !== 'darwin') { this.skip(); } }); 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 emittedOnce(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 emittedOnce(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 = emittedOnce(app, 'browser-window-focus'); 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 = emittedOnce(app, 'browser-window-blur'); 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 = emittedOnce(app, 'browser-window-created'); 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 = emittedOnce(app, 'web-contents-created'); 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'); const emitted = emittedOnce(app, 'renderer-process-crashed'); w.webContents.executeJavaScript('process.crash()'); const [, webContents] = await emitted; expect(webContents).to.equal(w.webContents); }); // 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 = emittedOnce(app, 'render-process-gone'); 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); }); it('correctly sets and unsets the LoginItem as hidden', function () { if (process.platform !== 'darwin') this.skip(); 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 emittedOnce(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 emittedOnce(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 emittedOnce(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/); }); }); describe('select-client-certificate event', () => { let w: BrowserWindow; before(function () { if (process.platform === 'linux') { this.skip(); } 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'); }); }); describe('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 () { if (process.platform !== 'win32') { this.skip(); } else { 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.find(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.find(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.find(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()', () => { it('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. if (process.platform === 'linux') { this.skip(); } const protocols = [ 'http://', 'https://' ]; protocols.forEach((protocol) => { 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 emittedOnce(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 emittedOnce(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 emittedOnce(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 emittedOnce(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 return Promise.reject(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); }); }); describe('sandbox options', () => { 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) { if (process.platform === 'linux' && (process.arch === 'arm64' || process.arch === 'arm')) { // 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. this.skip(); } fs.unlink(socketPath, () => { server = net.createServer(); server.listen(socketPath); done(); }); }); afterEach(done => { if (appProcess != null) appProcess.kill(); server.close(() => { if (process.platform === 'win32') { done(); } else { fs.unlink(socketPath, () => 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(); }); }); }); const dockDescribe = process.platform === 'darwin' ? describe : describe.skip; dockDescribe('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('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((done) => { server = http.createServer((request, response) => { if (request.headers.authorization) { return response.end('ok'); } response .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }) .end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as net.AddressInfo).port; done(); }); }); 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 emittedOnce(app, 'login'); 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 emittedOnce(appProcess.stdout, 'end'); return JSON.parse(output); }
closed
electron/electron
https://github.com/electron/electron
33,686
[Bug]: app.relaunch loses args when execPath specified.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.1 ### What operating system are you using? macOS ### Operating System Version 10.14.6 ### What arch are you using? x64 ### Last Known Working Electron version 17.0.0-alpha.3 ### Expected Behavior When invoking `app.relaunch` and specifying both `execPath` and `args`, I expect the args to be passed to the new process. ### Actual Behavior The binary specified by `execPath` is spawned as a new process, but the `args` are not applied. ### Testcase Gist URL https://gist.github.com/p120ph37/98cf0fb13790feed702f3e90cbddfbf6 ### Additional Information This bug was introduced in `17.0.0-alpha.4`, and is present in all newer stable versions up to and including at least `19.0.0-alpha.1` Also note that `app.relaunch()` doesn't work at all from within Electron Fiddle, so to run this gist, you must launch Electron directly (e.g.: via `npm start`).
https://github.com/electron/electron/issues/33686
https://github.com/electron/electron/pull/35108
34b985c5560aac4bb86d3697f8358647d38e79a7
91f9436ad8e6028bf2909008e5814867289b9310
2022-04-08T22:21:17Z
c++
2022-08-08T08:12:06Z
spec/fixtures/api/relaunch/main.js
const { app } = require('electron'); const net = require('net'); const socketPath = process.platform === 'win32' ? '\\\\.\\pipe\\electron-app-relaunch' : '/tmp/electron-app-relaunch'; process.on('uncaughtException', () => { app.exit(1); }); app.whenReady().then(() => { const lastArg = process.argv[process.argv.length - 1]; const client = net.connect(socketPath); client.once('connect', () => { client.end(String(lastArg === '--second')); }); client.once('end', () => { if (lastArg !== '--second') { app.relaunch({ args: process.argv.slice(1).concat('--second') }); } app.exit(0); }); });
closed
electron/electron
https://github.com/electron/electron
33,686
[Bug]: app.relaunch loses args when execPath specified.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.1 ### What operating system are you using? macOS ### Operating System Version 10.14.6 ### What arch are you using? x64 ### Last Known Working Electron version 17.0.0-alpha.3 ### Expected Behavior When invoking `app.relaunch` and specifying both `execPath` and `args`, I expect the args to be passed to the new process. ### Actual Behavior The binary specified by `execPath` is spawned as a new process, but the `args` are not applied. ### Testcase Gist URL https://gist.github.com/p120ph37/98cf0fb13790feed702f3e90cbddfbf6 ### Additional Information This bug was introduced in `17.0.0-alpha.4`, and is present in all newer stable versions up to and including at least `19.0.0-alpha.1` Also note that `app.relaunch()` doesn't work at all from within Electron Fiddle, so to run this gist, you must launch Electron directly (e.g.: via `npm start`).
https://github.com/electron/electron/issues/33686
https://github.com/electron/electron/pull/35108
34b985c5560aac4bb86d3697f8358647d38e79a7
91f9436ad8e6028bf2909008e5814867289b9310
2022-04-08T22:21:17Z
c++
2022-08-08T08:12:06Z
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/callback_helpers.h" #include "base/command_line.h" #include "base/containers/span.h" #include "base/environment.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/path_service.h" #include "base/system/sys_info.h" #include "base/values.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_web_contents.h" #include "shell/browser/api/gpuinfo_manager.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/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/platform_util.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) { std::string item_type; if (!ConvertFromV8(isolate, val, &item_type)) return false; if (item_type == "task") *out = JumpListItem::Type::kTask; else if (item_type == "separator") *out = JumpListItem::Type::kSeparator; else if (item_type == "file") *out = JumpListItem::Type::kFile; else return false; return true; } static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, JumpListItem::Type val) { std::string item_type; switch (val) { case JumpListItem::Type::kTask: item_type = "task"; break; case JumpListItem::Type::kSeparator: item_type = "separator"; break; case JumpListItem::Type::kFile: item_type = "file"; break; } return gin::ConvertToV8(isolate, item_type); } }; 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) { gin_helper::Dictionary dict = gin::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) { std::string category_type; if (!ConvertFromV8(isolate, val, &category_type)) return false; if (category_type == "tasks") *out = JumpListCategory::Type::kTasks; else if (category_type == "frequent") *out = JumpListCategory::Type::kFrequent; else if (category_type == "recent") *out = JumpListCategory::Type::kRecent; else if (category_type == "custom") *out = JumpListCategory::Type::kCustom; else return false; return true; } static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, JumpListCategory::Type val) { std::string category_type; switch (val) { case JumpListCategory::Type::kTasks: category_type = "tasks"; break; case JumpListCategory::Type::kFrequent: category_type = "frequent"; break; case JumpListCategory::Type::kRecent: category_type = "recent"; break; case JumpListCategory::Type::kCustom: category_type = "custom"; break; } return gin::ConvertToV8(isolate, category_type); } }; 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) { gin_helper::Dictionary dict = gin::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) { gin_helper::Dictionary dict = gin::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) { std::string s; if (!ConvertFromV8(isolate, val, &s)) return false; if (s == "off") { *out = net::SecureDnsMode::kOff; return true; } else if (s == "automatic") { *out = net::SecureDnsMode::kAutomatic; return true; } else if (s == "secure") { *out = net::SecureDnsMode::kSecure; return true; } return false; } }; } // 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(const std::string& name) { if (name == "appData") return DIR_APP_DATA; else if (name == "sessionData") return DIR_SESSION_DATA; else if (name == "userData") return chrome::DIR_USER_DATA; else if (name == "cache") #if BUILDFLAG(IS_POSIX) return base::DIR_CACHE; #else return base::DIR_ROAMING_APP_DATA; #endif else if (name == "userCache") return DIR_USER_CACHE; else if (name == "logs") return DIR_APP_LOGS; else if (name == "crashDumps") return DIR_CRASH_DUMPS; else if (name == "home") return base::DIR_HOME; else if (name == "temp") return base::DIR_TEMP; else if (name == "userDesktop" || name == "desktop") return base::DIR_USER_DESKTOP; else if (name == "exe") return base::FILE_EXE; else if (name == "module") return base::FILE_MODULE; else if (name == "documents") return chrome::DIR_USER_DOCUMENTS; else if (name == "downloads") return chrome::DIR_DEFAULT_DOWNLOADS; else if (name == "music") return chrome::DIR_USER_MUSIC; else if (name == "pictures") return chrome::DIR_USER_PICTURES; else if (name == "videos") return chrome::DIR_USER_VIDEOS; #if BUILDFLAG(IS_WIN) else if (name == "recent") return electron::DIR_RECENT; #endif else return -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::ThreadTaskRunnerHandle::Get()); // 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; std::string* cert_path_ptr = options.FindStringKey("certificate"); if (cert_path_ptr) cert_path = *cert_path_ptr; std::string* pwd = options.FindStringKey("password"); if (pwd) password = base::UTF8ToUTF16(*pwd); 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_) { process_singleton_->OnBrowserReady(); } } 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"); } #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::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); } 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; } { base::ThreadRestrictions::ScopedAllowIO allow_io; 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")); { base::ThreadRestrictions::ScopedAllowIO allow_io; 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::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), &region); } #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::LOCK_ERROR: case ProcessSingleton::NotifyResult::PROFILE_IN_USE: case ProcessSingleton::NotifyResult::PROCESS_NOTIFIED: { process_singleton_.reset(); return false; } case ProcessSingleton::NotifyResult::PROCESS_NONE: default: // Shouldn't be needed, but VS warns if it is not there. return true; } } 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)) { if (options.Get("execPath", &exec_path) || options.Get("args", &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, &current_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(); gin_helper::Dictionary dict = gin::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_) { gin_helper::Dictionary pid_dict = gin::Dictionary::CreateEmpty(isolate); gin_helper::Dictionary cpu_dict = gin::Dictionary::CreateEmpty(isolate); pid_dict.SetHidden("simple", true); cpu_dict.SetHidden("simple", true); 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(); gin_helper::Dictionary memory_dict = gin::Dictionary::CreateEmpty(isolate); memory_dict.SetHidden("simple", true); 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 { USHORT processMachine = 0; USHORT nativeMachine = 0; auto IsWow64Process2 = reinterpret_cast<decltype(&::IsWow64Process2)>( GetProcAddress(GetModuleHandle(L"kernel32.dll"), "IsWow64Process2")); if (IsWow64Process2 == nullptr) { return false; } if (!IsWow64Process2(GetCurrentProcess(), &processMachine, &nativeMachine)) { return false; } return nativeMachine == IMAGE_FILE_MACHINE_ARM64; } #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()); gin_helper::Dictionary dock_obj = gin::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("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 defined(MAS_BUILD) .SetMethod("startAccessingSecurityScopedResource", &App::StartAccessingSecurityScopedResource) #endif #if BUILDFLAG(IS_MAC) .SetProperty("dock", &App::GetDockAPI) .SetProperty("runningUnderRosettaTranslation", &App::IsRunningUnderRosettaTranslation) #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_MODULE_CONTEXT_AWARE(electron_browser_app, Initialize)
closed
electron/electron
https://github.com/electron/electron
33,686
[Bug]: app.relaunch loses args when execPath specified.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.1 ### What operating system are you using? macOS ### Operating System Version 10.14.6 ### What arch are you using? x64 ### Last Known Working Electron version 17.0.0-alpha.3 ### Expected Behavior When invoking `app.relaunch` and specifying both `execPath` and `args`, I expect the args to be passed to the new process. ### Actual Behavior The binary specified by `execPath` is spawned as a new process, but the `args` are not applied. ### Testcase Gist URL https://gist.github.com/p120ph37/98cf0fb13790feed702f3e90cbddfbf6 ### Additional Information This bug was introduced in `17.0.0-alpha.4`, and is present in all newer stable versions up to and including at least `19.0.0-alpha.1` Also note that `app.relaunch()` doesn't work at all from within Electron Fiddle, so to run this gist, you must launch Electron directly (e.g.: via `npm start`).
https://github.com/electron/electron/issues/33686
https://github.com/electron/electron/pull/35108
34b985c5560aac4bb86d3697f8358647d38e79a7
91f9436ad8e6028bf2909008e5814867289b9310
2022-04-08T22:21:17Z
c++
2022-08-08T08:12:06Z
spec-main/api-app-spec.ts
import { assert, expect } from 'chai'; import * as cp from 'child_process'; import * as https from 'https'; import * as http from 'http'; import * as net from 'net'; import * as fs from 'fs-extra'; import * as path from 'path'; import { promisify } from 'util'; import { app, BrowserWindow, Menu, session, net as electronNet } from 'electron/main'; import { emittedOnce } from './events-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; import { ifdescribe, ifit, waitUntil } from './spec-helpers'; import split = require('split') const fixturesPath = path.resolve(__dirname, '../spec/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((done) => { 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>'); } }); server.listen(0, '127.0.0.1', () => { const port = (server.address() as net.AddressInfo).port; secureUrl = `https://127.0.0.1:${port}`; done(); }); }); 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.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 emittedOnce(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 emittedOnce(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'); }); it('exits gracefully', async function () { if (!['darwin', 'linux'].includes(process.platform)) { this.skip(); return; } 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 emittedOnce(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 emittedOnce(first.stdout, 'data'); // Start second app when received output. const second = cp.spawn(process.execPath, [appPath]); const [code2] = await emittedOnce(second, 'exit'); expect(code2).to.equal(1); const [code1] = await emittedOnce(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 emittedOnce(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 = emittedOnce(first, 'exit'); // Wait for the first app to boot. const firstStdoutLines = first.stdout.pipe(split()); while ((await emittedOnce(firstStdoutLines, 'data')).toString() !== 'started') { // wait. } const additionalDataPromise = emittedOnce(firstStdoutLines, 'data'); const secondInstanceArgs = [process.execPath, appPath, ...testArgs.args, '--some-switch', 'some-arg']; const second = cp.spawn(secondInstanceArgs[0], secondInstanceArgs.slice(1)); const secondExited = emittedOnce(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 (e) { // 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) === 'false' && state === 'none') { state = 'first-launch'; } else if (String(data) === 'true' && state === 'first-launch') { done(); } else { done(`Unexpected state: "${state}", data: "${data}"`); } }); }); const appPath = path.join(fixturesPath, 'api', 'relaunch'); const child = cp.spawn(process.execPath, [appPath]); 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}"`); } }); }); }); describe('app.setUserActivity(type, userInfo)', () => { before(function () { if (process.platform !== 'darwin') { this.skip(); } }); 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 emittedOnce(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 emittedOnce(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 = emittedOnce(app, 'browser-window-focus'); 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 = emittedOnce(app, 'browser-window-blur'); 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 = emittedOnce(app, 'browser-window-created'); 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 = emittedOnce(app, 'web-contents-created'); 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'); const emitted = emittedOnce(app, 'renderer-process-crashed'); w.webContents.executeJavaScript('process.crash()'); const [, webContents] = await emitted; expect(webContents).to.equal(w.webContents); }); // 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 = emittedOnce(app, 'render-process-gone'); 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); }); it('correctly sets and unsets the LoginItem as hidden', function () { if (process.platform !== 'darwin') this.skip(); 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 emittedOnce(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 emittedOnce(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 emittedOnce(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/); }); }); describe('select-client-certificate event', () => { let w: BrowserWindow; before(function () { if (process.platform === 'linux') { this.skip(); } 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'); }); }); describe('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 () { if (process.platform !== 'win32') { this.skip(); } else { 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.find(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.find(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.find(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()', () => { it('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. if (process.platform === 'linux') { this.skip(); } const protocols = [ 'http://', 'https://' ]; protocols.forEach((protocol) => { 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 emittedOnce(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 emittedOnce(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 emittedOnce(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 emittedOnce(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 return Promise.reject(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); }); }); describe('sandbox options', () => { 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) { if (process.platform === 'linux' && (process.arch === 'arm64' || process.arch === 'arm')) { // 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. this.skip(); } fs.unlink(socketPath, () => { server = net.createServer(); server.listen(socketPath); done(); }); }); afterEach(done => { if (appProcess != null) appProcess.kill(); server.close(() => { if (process.platform === 'win32') { done(); } else { fs.unlink(socketPath, () => 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(); }); }); }); const dockDescribe = process.platform === 'darwin' ? describe : describe.skip; dockDescribe('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('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((done) => { server = http.createServer((request, response) => { if (request.headers.authorization) { return response.end('ok'); } response .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }) .end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as net.AddressInfo).port; done(); }); }); 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 emittedOnce(app, 'login'); 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 emittedOnce(appProcess.stdout, 'end'); return JSON.parse(output); }
closed
electron/electron
https://github.com/electron/electron
33,686
[Bug]: app.relaunch loses args when execPath specified.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.1 ### What operating system are you using? macOS ### Operating System Version 10.14.6 ### What arch are you using? x64 ### Last Known Working Electron version 17.0.0-alpha.3 ### Expected Behavior When invoking `app.relaunch` and specifying both `execPath` and `args`, I expect the args to be passed to the new process. ### Actual Behavior The binary specified by `execPath` is spawned as a new process, but the `args` are not applied. ### Testcase Gist URL https://gist.github.com/p120ph37/98cf0fb13790feed702f3e90cbddfbf6 ### Additional Information This bug was introduced in `17.0.0-alpha.4`, and is present in all newer stable versions up to and including at least `19.0.0-alpha.1` Also note that `app.relaunch()` doesn't work at all from within Electron Fiddle, so to run this gist, you must launch Electron directly (e.g.: via `npm start`).
https://github.com/electron/electron/issues/33686
https://github.com/electron/electron/pull/35108
34b985c5560aac4bb86d3697f8358647d38e79a7
91f9436ad8e6028bf2909008e5814867289b9310
2022-04-08T22:21:17Z
c++
2022-08-08T08:12:06Z
spec/fixtures/api/relaunch/main.js
const { app } = require('electron'); const net = require('net'); const socketPath = process.platform === 'win32' ? '\\\\.\\pipe\\electron-app-relaunch' : '/tmp/electron-app-relaunch'; process.on('uncaughtException', () => { app.exit(1); }); app.whenReady().then(() => { const lastArg = process.argv[process.argv.length - 1]; const client = net.connect(socketPath); client.once('connect', () => { client.end(String(lastArg === '--second')); }); client.once('end', () => { if (lastArg !== '--second') { app.relaunch({ args: process.argv.slice(1).concat('--second') }); } app.exit(0); }); });
closed
electron/electron
https://github.com/electron/electron
35,255
[Bug]: Wrong TypeScript type of ses.getStoragePath
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.1 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.5 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior The return type of `ses.getStoragePath()` should be `string | null`. This is returned when actually calling the function and is also described in https://github.com/electron/electron/blob/91f9436ad8e6028bf2909008e5814867289b9310/docs/api/session.md#sesgetstoragepath. ### Actual Behavior The generated TypeScript type definition says `ses.getStoragePath()` returns `void`, as can also be seen in https://unpkg.com/browse/[email protected]/electron.d.ts#L7763. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/35255
https://github.com/electron/electron/pull/35288
8646bf8d304d8dc97988227cdf76007c6fa4bfdf
1d95b98cc86a4b4ed757931fd38105b06e3e2556
2022-08-08T09:07:38Z
c++
2022-08-10T05:39:36Z
docs/api/session.md
# session > Manage browser sessions, cookies, cache, proxy settings, etc. Process: [Main](../glossary.md#main-process) The `session` module can be used to create new `Session` objects. You can also access the `session` of existing pages by using the `session` property of [`WebContents`](web-contents.md), or from the `session` module. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('http://github.com') const ses = win.webContents.session console.log(ses.getUserAgent()) ``` ## Methods The `session` module has the following methods: ### `session.fromPartition(partition[, options])` * `partition` string * `options` Object (optional) * `cache` boolean - Whether to enable cache. Returns `Session` - A session instance from `partition` string. When there is an existing `Session` with the same `partition`, it will be returned; otherwise a new `Session` instance will be created with `options`. If `partition` starts with `persist:`, the page will use a persistent session available to all pages in the app with the same `partition`. if there is no `persist:` prefix, the page will use an in-memory session. If the `partition` is empty then default session of the app will be returned. To create a `Session` with `options`, you have to ensure the `Session` with the `partition` has never been used before. There is no way to change the `options` of an existing `Session` object. ## Properties The `session` module has the following properties: ### `session.defaultSession` A `Session` object, the default session object of the app. ## Class: Session > Get and set properties of a session. Process: [Main](../glossary.md#main-process)<br /> _This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ You can create a `Session` object in the `session` module: ```javascript const { session } = require('electron') const ses = session.fromPartition('persist:name') console.log(ses.getUserAgent()) ``` ### Instance Events The following events are available on instances of `Session`: #### Event: 'will-download' Returns: * `event` Event * `item` [DownloadItem](download-item.md) * `webContents` [WebContents](web-contents.md) Emitted when Electron is about to download `item` in `webContents`. Calling `event.preventDefault()` will cancel the download and `item` will not be available from next tick of the process. ```javascript const { session } = require('electron') session.defaultSession.on('will-download', (event, item, webContents) => { event.preventDefault() require('got')(item.getURL()).then((response) => { require('fs').writeFileSync('/somewhere', response.body) }) }) ``` #### Event: 'extension-loaded' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is loaded. This occurs whenever an extension is added to the "enabled" set of extensions. This includes: * Extensions being loaded from `Session.loadExtension`. * Extensions being reloaded: * from a crash. * if the extension requested it ([`chrome.runtime.reload()`](https://developer.chrome.com/extensions/runtime#method-reload)). #### Event: 'extension-unloaded' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is unloaded. This occurs when `Session.removeExtension` is called. #### Event: 'extension-ready' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is loaded and all necessary browser state is initialized to support the start of the extension's background page. #### Event: 'preconnect' Returns: * `event` Event * `preconnectUrl` string - The URL being requested for preconnection by the renderer. * `allowCredentials` boolean - True if the renderer is requesting that the connection include credentials (see the [spec](https://w3c.github.io/resource-hints/#preconnect) for more details.) Emitted when a render process requests preconnection to a URL, generally due to a [resource hint](https://w3c.github.io/resource-hints/). #### Event: 'spellcheck-dictionary-initialized' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file has been successfully initialized. This occurs after the file has been downloaded. #### Event: 'spellcheck-dictionary-download-begin' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file starts downloading #### Event: 'spellcheck-dictionary-download-success' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file has been successfully downloaded #### Event: 'spellcheck-dictionary-download-failure' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file download fails. For details on the failure you should collect a netlog and inspect the download request. #### Event: 'select-hid-device' Returns: * `event` Event * `details` Object * `deviceList` [HIDDevice[]](structures/hid-device.md) * `frame` [WebFrameMain](web-frame-main.md) * `callback` Function * `deviceId` string | null (optional) Emitted when a HID device needs to be selected when a call to `navigator.hid.requestDevice` is made. `callback` should be called with `deviceId` to be selected; passing no arguments to `callback` will cancel the request. Additionally, permissioning on `navigator.hid` can be further managed by using [ses.setPermissionCheckHandler(handler)](#sessetpermissioncheckhandlerhandler) and [ses.setDevicePermissionHandler(handler)`](#sessetdevicepermissionhandlerhandler). ```javascript const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow() win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'hid') { // Add logic here to determine if permission should be given to allow HID selection return true } return false }) // Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } return false }) win.webContents.session.on('select-hid-device', (event, details, callback) => { event.preventDefault() const selectedDevice = details.deviceList.find((device) => { return device.vendorId === '9025' && device.productId === '67' }) callback(selectedPort?.deviceId) }) }) ``` #### Event: 'hid-device-added' Returns: * `event` Event * `details` Object * `device` [HIDDevice[]](structures/hid-device.md) * `frame` [WebFrameMain](web-frame-main.md) Emitted after `navigator.hid.requestDevice` has been called and `select-hid-device` has fired if a new device becomes available before the callback from `select-hid-device` is called. This event is intended for use when using a UI to ask users to pick a device so that the UI can be updated with the newly added device. #### Event: 'hid-device-removed' Returns: * `event` Event * `details` Object * `device` [HIDDevice[]](structures/hid-device.md) * `frame` [WebFrameMain](web-frame-main.md) Emitted after `navigator.hid.requestDevice` has been called and `select-hid-device` has fired if a device has been removed before the callback from `select-hid-device` is called. This event is intended for use when using a UI to ask users to pick a device so that the UI can be updated to remove the specified device. #### Event: 'hid-device-revoked' Returns: * `event` Event * `details` Object * `device` [HIDDevice[]](structures/hid-device.md) * `origin` string (optional) - The origin that the device has been revoked from. Emitted after `HIDDevice.forget()` has been called. This event can be used to help maintain persistent storage of permissions when `setDevicePermissionHandler` is used. #### Event: 'select-serial-port' Returns: * `event` Event * `portList` [SerialPort[]](structures/serial-port.md) * `webContents` [WebContents](web-contents.md) * `callback` Function * `portId` string Emitted when a serial port needs to be selected when a call to `navigator.serial.requestPort` is made. `callback` should be called with `portId` to be selected, passing an empty string to `callback` will cancel the request. Additionally, permissioning on `navigator.serial` can be managed by using [ses.setPermissionCheckHandler(handler)](#sessetpermissioncheckhandlerhandler) with the `serial` permission. ```javascript const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'serial') { // Add logic here to determine if permission should be given to allow serial selection return true } return false }) // Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'serial') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.serial.requestPort` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } return false }) win.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { event.preventDefault() const selectedPort = portList.find((device) => { return device.vendorId === '9025' && device.productId === '67' }) if (!selectedPort) { callback('') } else { callback(selectedPort.portId) } }) }) ``` #### Event: 'serial-port-added' Returns: * `event` Event * `port` [SerialPort](structures/serial-port.md) * `webContents` [WebContents](web-contents.md) Emitted after `navigator.serial.requestPort` has been called and `select-serial-port` has fired if a new serial port becomes available before the callback from `select-serial-port` is called. This event is intended for use when using a UI to ask users to pick a port so that the UI can be updated with the newly added port. #### Event: 'serial-port-removed' Returns: * `event` Event * `port` [SerialPort](structures/serial-port.md) * `webContents` [WebContents](web-contents.md) Emitted after `navigator.serial.requestPort` has been called and `select-serial-port` has fired if a serial port has been removed before the callback from `select-serial-port` is called. This event is intended for use when using a UI to ask users to pick a port so that the UI can be updated to remove the specified port. ### Instance Methods The following methods are available on instances of `Session`: #### `ses.getCacheSize()` Returns `Promise<Integer>` - the session's current cache size, in bytes. #### `ses.clearCache()` Returns `Promise<void>` - resolves when the cache clear operation is complete. Clears the session’s HTTP cache. #### `ses.clearStorageData([options])` * `options` Object (optional) * `origin` string (optional) - Should follow `window.location.origin`’s representation `scheme://host:port`. * `storages` string[] (optional) - The types of storages to clear, can contain: `appcache`, `cookies`, `filesystem`, `indexdb`, `localstorage`, `shadercache`, `websql`, `serviceworkers`, `cachestorage`. If not specified, clear all storage types. * `quotas` string[] (optional) - The types of quotas to clear, can contain: `temporary`, `persistent`, `syncable`. If not specified, clear all quotas. Returns `Promise<void>` - resolves when the storage data has been cleared. #### `ses.flushStorageData()` Writes any unwritten DOMStorage data to disk. #### `ses.setProxy(config)` * `config` Object * `mode` string (optional) - The proxy mode. Should be one of `direct`, `auto_detect`, `pac_script`, `fixed_servers` or `system`. If it's unspecified, it will be automatically determined based on other specified options. * `direct` In direct mode all connections are created directly, without any proxy involved. * `auto_detect` In auto_detect mode the proxy configuration is determined by a PAC script that can be downloaded at http://wpad/wpad.dat. * `pac_script` In pac_script mode the proxy configuration is determined by a PAC script that is retrieved from the URL specified in the `pacScript`. This is the default mode if `pacScript` is specified. * `fixed_servers` In fixed_servers mode the proxy configuration is specified in `proxyRules`. This is the default mode if `proxyRules` is specified. * `system` In system mode the proxy configuration is taken from the operating system. Note that the system mode is different from setting no proxy configuration. In the latter case, Electron falls back to the system settings only if no command-line options influence the proxy configuration. * `pacScript` string (optional) - The URL associated with the PAC file. * `proxyRules` string (optional) - Rules indicating which proxies to use. * `proxyBypassRules` string (optional) - Rules indicating which URLs should bypass the proxy settings. Returns `Promise<void>` - Resolves when the proxy setting process is complete. Sets the proxy settings. When `mode` is unspecified, `pacScript` and `proxyRules` are provided together, the `proxyRules` option is ignored and `pacScript` configuration is applied. You may need `ses.closeAllConnections` to close currently in flight connections to prevent pooled sockets using previous proxy from being reused by future requests. The `proxyRules` has to follow the rules below: ```sh proxyRules = schemeProxies[";"<schemeProxies>] schemeProxies = [<urlScheme>"="]<proxyURIList> urlScheme = "http" | "https" | "ftp" | "socks" proxyURIList = <proxyURL>[","<proxyURIList>] proxyURL = [<proxyScheme>"://"]<proxyHost>[":"<proxyPort>] ``` For example: * `http=foopy:80;ftp=foopy2` - Use HTTP proxy `foopy:80` for `http://` URLs, and HTTP proxy `foopy2:80` for `ftp://` URLs. * `foopy:80` - Use HTTP proxy `foopy:80` for all URLs. * `foopy:80,bar,direct://` - Use HTTP proxy `foopy:80` for all URLs, failing over to `bar` if `foopy:80` is unavailable, and after that using no proxy. * `socks4://foopy` - Use SOCKS v4 proxy `foopy:1080` for all URLs. * `http=foopy,socks5://bar.com` - Use HTTP proxy `foopy` for http URLs, and fail over to the SOCKS5 proxy `bar.com` if `foopy` is unavailable. * `http=foopy,direct://` - Use HTTP proxy `foopy` for http URLs, and use no proxy if `foopy` is unavailable. * `http=foopy;socks=foopy2` - Use HTTP proxy `foopy` for http URLs, and use `socks4://foopy2` for all other URLs. The `proxyBypassRules` is a comma separated list of rules described below: * `[ URL_SCHEME "://" ] HOSTNAME_PATTERN [ ":" <port> ]` Match all hostnames that match the pattern HOSTNAME_PATTERN. Examples: "foobar.com", "*foobar.com", "*.foobar.com", "*foobar.com:99", "https://x.*.y.com:99" * `"." HOSTNAME_SUFFIX_PATTERN [ ":" PORT ]` Match a particular domain suffix. Examples: ".google.com", ".com", "http://.google.com" * `[ SCHEME "://" ] IP_LITERAL [ ":" PORT ]` Match URLs which are IP address literals. Examples: "127.0.1", "[0:0::1]", "[::1]", "http://[::1]:99" * `IP_LITERAL "/" PREFIX_LENGTH_IN_BITS` Match any URL that is to an IP literal that falls between the given range. IP range is specified using CIDR notation. Examples: "192.168.1.1/16", "fefe:13::abc/33". * `<local>` Match local addresses. The meaning of `<local>` is whether the host matches one of: "127.0.0.1", "::1", "localhost". #### `ses.resolveProxy(url)` * `url` URL Returns `Promise<string>` - Resolves with the proxy information for `url`. #### `ses.forceReloadProxyConfig()` Returns `Promise<void>` - Resolves when the all internal states of proxy service is reset and the latest proxy configuration is reapplied if it's already available. The pac script will be fetched from `pacScript` again if the proxy mode is `pac_script`. #### `ses.setDownloadPath(path)` * `path` string - The download location. Sets download saving directory. By default, the download directory will be the `Downloads` under the respective app folder. #### `ses.enableNetworkEmulation(options)` * `options` Object * `offline` boolean (optional) - Whether to emulate network outage. Defaults to false. * `latency` Double (optional) - RTT in ms. Defaults to 0 which will disable latency throttling. * `downloadThroughput` Double (optional) - Download rate in Bps. Defaults to 0 which will disable download throttling. * `uploadThroughput` Double (optional) - Upload rate in Bps. Defaults to 0 which will disable upload throttling. Emulates network with the given configuration for the `session`. ```javascript // To emulate a GPRS connection with 50kbps throughput and 500 ms latency. window.webContents.session.enableNetworkEmulation({ latency: 500, downloadThroughput: 6400, uploadThroughput: 6400 }) // To emulate a network outage. window.webContents.session.enableNetworkEmulation({ offline: true }) ``` #### `ses.preconnect(options)` * `options` Object * `url` string - URL for preconnect. Only the origin is relevant for opening the socket. * `numSockets` number (optional) - number of sockets to preconnect. Must be between 1 and 6. Defaults to 1. Preconnects the given number of sockets to an origin. #### `ses.closeAllConnections()` Returns `Promise<void>` - Resolves when all connections are closed. **Note:** It will terminate / fail all requests currently in flight. #### `ses.disableNetworkEmulation()` Disables any network emulation already active for the `session`. Resets to the original network configuration. #### `ses.setCertificateVerifyProc(proc)` * `proc` Function | null * `request` Object * `hostname` string * `certificate` [Certificate](structures/certificate.md) * `validatedCertificate` [Certificate](structures/certificate.md) * `isIssuedByKnownRoot` boolean - `true` if Chromium recognises the root CA as a standard root. If it isn't then it's probably the case that this certificate was generated by a MITM proxy whose root has been installed locally (for example, by a corporate proxy). This should not be trusted if the `verificationResult` is not `OK`. * `verificationResult` string - `OK` if the certificate is trusted, otherwise an error like `CERT_REVOKED`. * `errorCode` Integer - Error code. * `callback` Function * `verificationResult` Integer - Value can be one of certificate error codes from [here](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h). Apart from the certificate error codes, the following special codes can be used. * `0` - Indicates success and disables Certificate Transparency verification. * `-2` - Indicates failure. * `-3` - Uses the verification result from chromium. Sets the certificate verify proc for `session`, the `proc` will be called with `proc(request, callback)` whenever a server certificate verification is requested. Calling `callback(0)` accepts the certificate, calling `callback(-2)` rejects it. Calling `setCertificateVerifyProc(null)` will revert back to default certificate verify proc. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.webContents.session.setCertificateVerifyProc((request, callback) => { const { hostname } = request if (hostname === 'github.com') { callback(0) } else { callback(-2) } }) ``` > **NOTE:** The result of this procedure is cached by the network service. #### `ses.setPermissionRequestHandler(handler)` * `handler` Function | null * `webContents` [WebContents](web-contents.md) - WebContents requesting the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin. * `permission` string - The type of requested permission. * `clipboard-read` - Request access to read from the clipboard. * `media` - Request access to media devices such as camera, microphone and speakers. * `display-capture` - Request access to capture the screen. * `mediaKeySystem` - Request access to DRM protected content. * `geolocation` - Request access to user's current location. * `notifications` - Request notification creation and the ability to display them in the user's system tray. * `midi` - Request MIDI access in the `webmidi` API. * `midiSysex` - Request the use of system exclusive messages in the `webmidi` API. * `pointerLock` - Request to directly interpret mouse movements as an input method. Click [here](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API) to know more. * `fullscreen` - Request for the app to enter fullscreen mode. * `openExternal` - Request to open links in external applications. * `unknown` - An unrecognized permission request * `callback` Function * `permissionGranted` boolean - Allow or deny the permission. * `details` Object - Some properties are only available on certain permission types. * `externalURL` string (optional) - The url of the `openExternal` request. * `securityOrigin` string (optional) - The security origin of the `media` request. * `mediaTypes` string[] (optional) - The types of media access being requested, elements can be `video` or `audio` * `requestingUrl` string - The last URL the requesting frame loaded * `isMainFrame` boolean - Whether the frame making the request is the main frame Sets the handler which can be used to respond to permission requests for the `session`. Calling `callback(true)` will allow the permission and `callback(false)` will reject it. To clear the handler, call `setPermissionRequestHandler(null)`. Please note that you must also implement `setPermissionCheckHandler` to get complete permission handling. Most web APIs do a permission check and then make a permission request if the check is denied. ```javascript const { session } = require('electron') session.fromPartition('some-partition').setPermissionRequestHandler((webContents, permission, callback) => { if (webContents.getURL() === 'some-host' && permission === 'notifications') { return callback(false) // denied. } callback(true) }) ``` #### `ses.setPermissionCheckHandler(handler)` * `handler` Function\<boolean> | null * `webContents` ([WebContents](web-contents.md) | null) - WebContents checking the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin. All cross origin sub frames making permission checks will pass a `null` webContents to this handler, while certain other permission checks such as `notifications` checks will always pass `null`. You should use `embeddingOrigin` and `requestingOrigin` to determine what origin the owning frame and the requesting frame are on respectively. * `permission` string - Type of permission check. Valid values are `midiSysex`, `notifications`, `geolocation`, `media`,`mediaKeySystem`,`midi`, `pointerLock`, `fullscreen`, `openExternal`, `hid`, or `serial`. * `requestingOrigin` string - The origin URL of the permission check * `details` Object - Some properties are only available on certain permission types. * `embeddingOrigin` string (optional) - The origin of the frame embedding the frame that made the permission check. Only set for cross-origin sub frames making permission checks. * `securityOrigin` string (optional) - The security origin of the `media` check. * `mediaType` string (optional) - The type of media access being requested, can be `video`, `audio` or `unknown` * `requestingUrl` string (optional) - The last URL the requesting frame loaded. This is not provided for cross-origin sub frames making permission checks. * `isMainFrame` boolean - Whether the frame making the request is the main frame Sets the handler which can be used to respond to permission checks for the `session`. Returning `true` will allow the permission and `false` will reject it. Please note that you must also implement `setPermissionRequestHandler` to get complete permission handling. Most web APIs do a permission check and then make a permission request if the check is denied. To clear the handler, call `setPermissionCheckHandler(null)`. ```javascript const { session } = require('electron') const url = require('url') session.fromPartition('some-partition').setPermissionCheckHandler((webContents, permission, requestingOrigin) => { if (new URL(requestingOrigin).hostname === 'some-host' && permission === 'notifications') { return true // granted } return false // denied }) ``` #### `ses.setDevicePermissionHandler(handler)` * `handler` Function\<boolean> | null * `details` Object * `deviceType` string - The type of device that permission is being requested on, can be `hid` or `serial`. * `origin` string - The origin URL of the device permission check. * `device` [HIDDevice](structures/hid-device.md) | [SerialPort](structures/serial-port.md)- the device that permission is being requested for. Sets the handler which can be used to respond to device permission checks for the `session`. Returning `true` will allow the device to be permitted and `false` will reject it. To clear the handler, call `setDevicePermissionHandler(null)`. This handler can be used to provide default permissioning to devices without first calling for permission to devices (eg via `navigator.hid.requestDevice`). If this handler is not defined, the default device permissions as granted through device selection (eg via `navigator.hid.requestDevice`) will be used. Additionally, the default behavior of Electron is to store granted device permision in memory. If longer term storage is needed, a developer can store granted device permissions (eg when handling the `select-hid-device` event) and then read from that storage with `setDevicePermissionHandler`. ```javascript const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow() win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'hid') { // Add logic here to determine if permission should be given to allow HID selection return true } else if (permission === 'serial') { // Add logic here to determine if permission should be given to allow serial port selection } return false }) // Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } else if (details.deviceType === 'serial') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first) return true } } return false }) win.webContents.session.on('select-hid-device', (event, details, callback) => { event.preventDefault() const selectedDevice = details.deviceList.find((device) => { return device.vendorId === '9025' && device.productId === '67' }) callback(selectedPort?.deviceId) }) }) ``` #### `ses.clearHostResolverCache()` Returns `Promise<void>` - Resolves when the operation is complete. Clears the host resolver cache. #### `ses.allowNTLMCredentialsForDomains(domains)` * `domains` string - A comma-separated list of servers for which integrated authentication is enabled. Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate authentication. ```javascript const { session } = require('electron') // consider any url ending with `example.com`, `foobar.com`, `baz` // for integrated authentication. session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz') // consider all urls for integrated authentication. session.defaultSession.allowNTLMCredentialsForDomains('*') ``` #### `ses.setUserAgent(userAgent[, acceptLanguages])` * `userAgent` string * `acceptLanguages` string (optional) Overrides the `userAgent` and `acceptLanguages` for this session. The `acceptLanguages` must a comma separated ordered list of language codes, for example `"en-US,fr,de,ko,zh-CN,ja"`. This doesn't affect existing `WebContents`, and each `WebContents` can use `webContents.setUserAgent` to override the session-wide user agent. #### `ses.isPersistent()` Returns `boolean` - Whether or not this session is a persistent one. The default `webContents` session of a `BrowserWindow` is persistent. When creating a session from a partition, session prefixed with `persist:` will be persistent, while others will be temporary. #### `ses.getUserAgent()` Returns `string` - The user agent for this session. #### `ses.setSSLConfig(config)` * `config` Object * `minVersion` string (optional) - Can be `tls1`, `tls1.1`, `tls1.2` or `tls1.3`. The minimum SSL version to allow when connecting to remote servers. Defaults to `tls1`. * `maxVersion` string (optional) - Can be `tls1.2` or `tls1.3`. The maximum SSL version to allow when connecting to remote servers. Defaults to `tls1.3`. * `disabledCipherSuites` Integer[] (optional) - List of cipher suites which should be explicitly prevented from being used in addition to those disabled by the net built-in policy. Supported literal forms: 0xAABB, where AA is `cipher_suite[0]` and BB is `cipher_suite[1]`, as defined in RFC 2246, Section 7.4.1.2. Unrecognized but parsable cipher suites in this form will not return an error. Ex: To disable TLS_RSA_WITH_RC4_128_MD5, specify 0x0004, while to disable TLS_ECDH_ECDSA_WITH_RC4_128_SHA, specify 0xC002. Note that TLSv1.3 ciphers cannot be disabled using this mechanism. Sets the SSL configuration for the session. All subsequent network requests will use the new configuration. Existing network connections (such as WebSocket connections) will not be terminated, but old sockets in the pool will not be reused for new connections. #### `ses.getBlobData(identifier)` * `identifier` string - Valid UUID. Returns `Promise<Buffer>` - resolves with blob data. #### `ses.downloadURL(url)` * `url` string Initiates a download of the resource at `url`. The API will generate a [DownloadItem](download-item.md) that can be accessed with the [will-download](#event-will-download) event. **Note:** This does not perform any security checks that relate to a page's origin, unlike [`webContents.downloadURL`](web-contents.md#contentsdownloadurlurl). #### `ses.createInterruptedDownload(options)` * `options` Object * `path` string - Absolute path of the download. * `urlChain` string[] - Complete URL chain for the download. * `mimeType` string (optional) * `offset` Integer - Start range for the download. * `length` Integer - Total length of the download. * `lastModified` string (optional) - Last-Modified header value. * `eTag` string (optional) - ETag header value. * `startTime` Double (optional) - Time when download was started in number of seconds since UNIX epoch. Allows resuming `cancelled` or `interrupted` downloads from previous `Session`. The API will generate a [DownloadItem](download-item.md) that can be accessed with the [will-download](#event-will-download) event. The [DownloadItem](download-item.md) will not have any `WebContents` associated with it and the initial state will be `interrupted`. The download will start only when the `resume` API is called on the [DownloadItem](download-item.md). #### `ses.clearAuthCache()` Returns `Promise<void>` - resolves when the session’s HTTP authentication cache has been cleared. #### `ses.setPreloads(preloads)` * `preloads` string[] - An array of absolute path to preload scripts Adds scripts that will be executed on ALL web contents that are associated with this session just before normal `preload` scripts run. #### `ses.getPreloads()` Returns `string[]` an array of paths to preload scripts that have been registered. #### `ses.setCodeCachePath(path)` * `path` String - Absolute path to store the v8 generated JS code cache from the renderer. Sets the directory to store the generated JS [code cache](https://v8.dev/blog/code-caching-for-devs) for this session. The directory is not required to be created by the user before this call, the runtime will create if it does not exist otherwise will use the existing directory. If directory cannot be created, then code cache will not be used and all operations related to code cache will fail silently inside the runtime. By default, the directory will be `Code Cache` under the respective user data folder. #### `ses.clearCodeCaches(options)` * `options` Object * `urls` String[] (optional) - An array of url corresponding to the resource whose generated code cache needs to be removed. If the list is empty then all entries in the cache directory will be removed. Returns `Promise<void>` - resolves when the code cache clear operation is complete. #### `ses.setSpellCheckerEnabled(enable)` * `enable` boolean Sets whether to enable the builtin spell checker. #### `ses.isSpellCheckerEnabled()` Returns `boolean` - Whether the builtin spell checker is enabled. #### `ses.setSpellCheckerLanguages(languages)` * `languages` string[] - An array of language codes to enable the spellchecker for. The built in spellchecker does not automatically detect what language a user is typing in. In order for the spell checker to correctly check their words you must call this API with an array of language codes. You can get the list of supported language codes with the `ses.availableSpellCheckerLanguages` property. **Note:** On macOS the OS spellchecker is used and will detect your language automatically. This API is a no-op on macOS. #### `ses.getSpellCheckerLanguages()` Returns `string[]` - An array of language codes the spellchecker is enabled for. If this list is empty the spellchecker will fallback to using `en-US`. By default on launch if this setting is an empty list Electron will try to populate this setting with the current OS locale. This setting is persisted across restarts. **Note:** On macOS the OS spellchecker is used and has its own list of languages. This API is a no-op on macOS. #### `ses.setSpellCheckerDictionaryDownloadURL(url)` * `url` string - A base URL for Electron to download hunspell dictionaries from. By default Electron will download hunspell dictionaries from the Chromium CDN. If you want to override this behavior you can use this API to point the dictionary downloader at your own hosted version of the hunspell dictionaries. We publish a `hunspell_dictionaries.zip` file with each release which contains the files you need to host here. The file server must be **case insensitive**. If you cannot do this, you must upload each file twice: once with the case it has in the ZIP file and once with the filename as all lowercase. If the files present in `hunspell_dictionaries.zip` are available at `https://example.com/dictionaries/language-code.bdic` then you should call this api with `ses.setSpellCheckerDictionaryDownloadURL('https://example.com/dictionaries/')`. Please note the trailing slash. The URL to the dictionaries is formed as `${url}${filename}`. **Note:** On macOS the OS spellchecker is used and therefore we do not download any dictionary files. This API is a no-op on macOS. #### `ses.listWordsInSpellCheckerDictionary()` Returns `Promise<string[]>` - An array of all words in app's custom dictionary. Resolves when the full dictionary is loaded from disk. #### `ses.addWordToSpellCheckerDictionary(word)` * `word` string - The word you want to add to the dictionary Returns `boolean` - Whether the word was successfully written to the custom dictionary. This API will not work on non-persistent (in-memory) sessions. **Note:** On macOS and Windows 10 this word will be written to the OS custom dictionary as well #### `ses.removeWordFromSpellCheckerDictionary(word)` * `word` string - The word you want to remove from the dictionary Returns `boolean` - Whether the word was successfully removed from the custom dictionary. This API will not work on non-persistent (in-memory) sessions. **Note:** On macOS and Windows 10 this word will be removed from the OS custom dictionary as well #### `ses.loadExtension(path[, options])` * `path` string - Path to a directory containing an unpacked Chrome extension * `options` Object (optional) * `allowFileAccess` boolean - Whether to allow the extension to read local files over `file://` protocol and inject content scripts into `file://` pages. This is required e.g. for loading devtools extensions on `file://` URLs. Defaults to false. Returns `Promise<Extension>` - resolves when the extension is loaded. This method will raise an exception if the extension could not be loaded. If there are warnings when installing the extension (e.g. if the extension requests an API that Electron does not support) then they will be logged to the console. Note that Electron does not support the full range of Chrome extensions APIs. See [Supported Extensions APIs](extensions.md#supported-extensions-apis) for more details on what is supported. Note that in previous versions of Electron, extensions that were loaded would be remembered for future runs of the application. This is no longer the case: `loadExtension` must be called on every boot of your app if you want the extension to be loaded. ```js const { app, session } = require('electron') const path = require('path') app.on('ready', async () => { await session.defaultSession.loadExtension( path.join(__dirname, 'react-devtools'), // allowFileAccess is required to load the devtools extension on file:// URLs. { allowFileAccess: true } ) // Note that in order to use the React DevTools extension, you'll need to // download and unzip a copy of the extension. }) ``` This API does not support loading packed (.crx) extensions. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. **Note:** Loading extensions into in-memory (non-persistent) sessions is not supported and will throw an error. #### `ses.removeExtension(extensionId)` * `extensionId` string - ID of extension to remove Unloads an extension. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. #### `ses.getExtension(extensionId)` * `extensionId` string - ID of extension to query Returns `Extension` | `null` - The loaded extension with the given ID. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. #### `ses.getAllExtensions()` Returns `Extension[]` - A list of all loaded extensions. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. #### `ses.getStoragePath()` A `string | null` indicating the absolute file system path where data for this session is persisted on disk. For in memory sessions this returns `null`. ### Instance Properties The following properties are available on instances of `Session`: #### `ses.availableSpellCheckerLanguages` _Readonly_ A `string[]` array which consists of all the known available spell checker languages. Providing a language code to the `setSpellCheckerLanguages` API that isn't in this array will result in an error. #### `ses.spellCheckerEnabled` A `boolean` indicating whether builtin spell checker is enabled. #### `ses.storagePath` _Readonly_ A `string | null` indicating the absolute file system path where data for this session is persisted on disk. For in memory sessions this returns `null`. #### `ses.cookies` _Readonly_ A [`Cookies`](cookies.md) object for this session. #### `ses.serviceWorkers` _Readonly_ A [`ServiceWorkers`](service-workers.md) object for this session. #### `ses.webRequest` _Readonly_ A [`WebRequest`](web-request.md) object for this session. #### `ses.protocol` _Readonly_ A [`Protocol`](protocol.md) object for this session. ```javascript const { app, session } = require('electron') const path = require('path') app.whenReady().then(() => { const protocol = session.fromPartition('some-partition').protocol if (!protocol.registerFileProtocol('atom', (request, callback) => { const url = request.url.substr(7) callback({ path: path.normalize(`${__dirname}/${url}`) }) })) { console.error('Failed to register protocol') } }) ``` #### `ses.netLog` _Readonly_ A [`NetLog`](net-log.md) object for this session. ```javascript const { app, session } = require('electron') app.whenReady().then(async () => { const netLog = session.fromPartition('some-partition').netLog netLog.startLogging('/path/to/net-log') // After some network events const path = await netLog.stopLogging() console.log('Net-logs written to', path) }) ```
closed
electron/electron
https://github.com/electron/electron
35,255
[Bug]: Wrong TypeScript type of ses.getStoragePath
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.1 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.5 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior The return type of `ses.getStoragePath()` should be `string | null`. This is returned when actually calling the function and is also described in https://github.com/electron/electron/blob/91f9436ad8e6028bf2909008e5814867289b9310/docs/api/session.md#sesgetstoragepath. ### Actual Behavior The generated TypeScript type definition says `ses.getStoragePath()` returns `void`, as can also be seen in https://unpkg.com/browse/[email protected]/electron.d.ts#L7763. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/35255
https://github.com/electron/electron/pull/35288
8646bf8d304d8dc97988227cdf76007c6fa4bfdf
1d95b98cc86a4b4ed757931fd38105b06e3e2556
2022-08-08T09:07:38Z
c++
2022-08-10T05:39:36Z
docs/api/session.md
# session > Manage browser sessions, cookies, cache, proxy settings, etc. Process: [Main](../glossary.md#main-process) The `session` module can be used to create new `Session` objects. You can also access the `session` of existing pages by using the `session` property of [`WebContents`](web-contents.md), or from the `session` module. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('http://github.com') const ses = win.webContents.session console.log(ses.getUserAgent()) ``` ## Methods The `session` module has the following methods: ### `session.fromPartition(partition[, options])` * `partition` string * `options` Object (optional) * `cache` boolean - Whether to enable cache. Returns `Session` - A session instance from `partition` string. When there is an existing `Session` with the same `partition`, it will be returned; otherwise a new `Session` instance will be created with `options`. If `partition` starts with `persist:`, the page will use a persistent session available to all pages in the app with the same `partition`. if there is no `persist:` prefix, the page will use an in-memory session. If the `partition` is empty then default session of the app will be returned. To create a `Session` with `options`, you have to ensure the `Session` with the `partition` has never been used before. There is no way to change the `options` of an existing `Session` object. ## Properties The `session` module has the following properties: ### `session.defaultSession` A `Session` object, the default session object of the app. ## Class: Session > Get and set properties of a session. Process: [Main](../glossary.md#main-process)<br /> _This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ You can create a `Session` object in the `session` module: ```javascript const { session } = require('electron') const ses = session.fromPartition('persist:name') console.log(ses.getUserAgent()) ``` ### Instance Events The following events are available on instances of `Session`: #### Event: 'will-download' Returns: * `event` Event * `item` [DownloadItem](download-item.md) * `webContents` [WebContents](web-contents.md) Emitted when Electron is about to download `item` in `webContents`. Calling `event.preventDefault()` will cancel the download and `item` will not be available from next tick of the process. ```javascript const { session } = require('electron') session.defaultSession.on('will-download', (event, item, webContents) => { event.preventDefault() require('got')(item.getURL()).then((response) => { require('fs').writeFileSync('/somewhere', response.body) }) }) ``` #### Event: 'extension-loaded' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is loaded. This occurs whenever an extension is added to the "enabled" set of extensions. This includes: * Extensions being loaded from `Session.loadExtension`. * Extensions being reloaded: * from a crash. * if the extension requested it ([`chrome.runtime.reload()`](https://developer.chrome.com/extensions/runtime#method-reload)). #### Event: 'extension-unloaded' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is unloaded. This occurs when `Session.removeExtension` is called. #### Event: 'extension-ready' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is loaded and all necessary browser state is initialized to support the start of the extension's background page. #### Event: 'preconnect' Returns: * `event` Event * `preconnectUrl` string - The URL being requested for preconnection by the renderer. * `allowCredentials` boolean - True if the renderer is requesting that the connection include credentials (see the [spec](https://w3c.github.io/resource-hints/#preconnect) for more details.) Emitted when a render process requests preconnection to a URL, generally due to a [resource hint](https://w3c.github.io/resource-hints/). #### Event: 'spellcheck-dictionary-initialized' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file has been successfully initialized. This occurs after the file has been downloaded. #### Event: 'spellcheck-dictionary-download-begin' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file starts downloading #### Event: 'spellcheck-dictionary-download-success' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file has been successfully downloaded #### Event: 'spellcheck-dictionary-download-failure' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file download fails. For details on the failure you should collect a netlog and inspect the download request. #### Event: 'select-hid-device' Returns: * `event` Event * `details` Object * `deviceList` [HIDDevice[]](structures/hid-device.md) * `frame` [WebFrameMain](web-frame-main.md) * `callback` Function * `deviceId` string | null (optional) Emitted when a HID device needs to be selected when a call to `navigator.hid.requestDevice` is made. `callback` should be called with `deviceId` to be selected; passing no arguments to `callback` will cancel the request. Additionally, permissioning on `navigator.hid` can be further managed by using [ses.setPermissionCheckHandler(handler)](#sessetpermissioncheckhandlerhandler) and [ses.setDevicePermissionHandler(handler)`](#sessetdevicepermissionhandlerhandler). ```javascript const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow() win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'hid') { // Add logic here to determine if permission should be given to allow HID selection return true } return false }) // Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } return false }) win.webContents.session.on('select-hid-device', (event, details, callback) => { event.preventDefault() const selectedDevice = details.deviceList.find((device) => { return device.vendorId === '9025' && device.productId === '67' }) callback(selectedPort?.deviceId) }) }) ``` #### Event: 'hid-device-added' Returns: * `event` Event * `details` Object * `device` [HIDDevice[]](structures/hid-device.md) * `frame` [WebFrameMain](web-frame-main.md) Emitted after `navigator.hid.requestDevice` has been called and `select-hid-device` has fired if a new device becomes available before the callback from `select-hid-device` is called. This event is intended for use when using a UI to ask users to pick a device so that the UI can be updated with the newly added device. #### Event: 'hid-device-removed' Returns: * `event` Event * `details` Object * `device` [HIDDevice[]](structures/hid-device.md) * `frame` [WebFrameMain](web-frame-main.md) Emitted after `navigator.hid.requestDevice` has been called and `select-hid-device` has fired if a device has been removed before the callback from `select-hid-device` is called. This event is intended for use when using a UI to ask users to pick a device so that the UI can be updated to remove the specified device. #### Event: 'hid-device-revoked' Returns: * `event` Event * `details` Object * `device` [HIDDevice[]](structures/hid-device.md) * `origin` string (optional) - The origin that the device has been revoked from. Emitted after `HIDDevice.forget()` has been called. This event can be used to help maintain persistent storage of permissions when `setDevicePermissionHandler` is used. #### Event: 'select-serial-port' Returns: * `event` Event * `portList` [SerialPort[]](structures/serial-port.md) * `webContents` [WebContents](web-contents.md) * `callback` Function * `portId` string Emitted when a serial port needs to be selected when a call to `navigator.serial.requestPort` is made. `callback` should be called with `portId` to be selected, passing an empty string to `callback` will cancel the request. Additionally, permissioning on `navigator.serial` can be managed by using [ses.setPermissionCheckHandler(handler)](#sessetpermissioncheckhandlerhandler) with the `serial` permission. ```javascript const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'serial') { // Add logic here to determine if permission should be given to allow serial selection return true } return false }) // Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'serial') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.serial.requestPort` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } return false }) win.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { event.preventDefault() const selectedPort = portList.find((device) => { return device.vendorId === '9025' && device.productId === '67' }) if (!selectedPort) { callback('') } else { callback(selectedPort.portId) } }) }) ``` #### Event: 'serial-port-added' Returns: * `event` Event * `port` [SerialPort](structures/serial-port.md) * `webContents` [WebContents](web-contents.md) Emitted after `navigator.serial.requestPort` has been called and `select-serial-port` has fired if a new serial port becomes available before the callback from `select-serial-port` is called. This event is intended for use when using a UI to ask users to pick a port so that the UI can be updated with the newly added port. #### Event: 'serial-port-removed' Returns: * `event` Event * `port` [SerialPort](structures/serial-port.md) * `webContents` [WebContents](web-contents.md) Emitted after `navigator.serial.requestPort` has been called and `select-serial-port` has fired if a serial port has been removed before the callback from `select-serial-port` is called. This event is intended for use when using a UI to ask users to pick a port so that the UI can be updated to remove the specified port. ### Instance Methods The following methods are available on instances of `Session`: #### `ses.getCacheSize()` Returns `Promise<Integer>` - the session's current cache size, in bytes. #### `ses.clearCache()` Returns `Promise<void>` - resolves when the cache clear operation is complete. Clears the session’s HTTP cache. #### `ses.clearStorageData([options])` * `options` Object (optional) * `origin` string (optional) - Should follow `window.location.origin`’s representation `scheme://host:port`. * `storages` string[] (optional) - The types of storages to clear, can contain: `appcache`, `cookies`, `filesystem`, `indexdb`, `localstorage`, `shadercache`, `websql`, `serviceworkers`, `cachestorage`. If not specified, clear all storage types. * `quotas` string[] (optional) - The types of quotas to clear, can contain: `temporary`, `persistent`, `syncable`. If not specified, clear all quotas. Returns `Promise<void>` - resolves when the storage data has been cleared. #### `ses.flushStorageData()` Writes any unwritten DOMStorage data to disk. #### `ses.setProxy(config)` * `config` Object * `mode` string (optional) - The proxy mode. Should be one of `direct`, `auto_detect`, `pac_script`, `fixed_servers` or `system`. If it's unspecified, it will be automatically determined based on other specified options. * `direct` In direct mode all connections are created directly, without any proxy involved. * `auto_detect` In auto_detect mode the proxy configuration is determined by a PAC script that can be downloaded at http://wpad/wpad.dat. * `pac_script` In pac_script mode the proxy configuration is determined by a PAC script that is retrieved from the URL specified in the `pacScript`. This is the default mode if `pacScript` is specified. * `fixed_servers` In fixed_servers mode the proxy configuration is specified in `proxyRules`. This is the default mode if `proxyRules` is specified. * `system` In system mode the proxy configuration is taken from the operating system. Note that the system mode is different from setting no proxy configuration. In the latter case, Electron falls back to the system settings only if no command-line options influence the proxy configuration. * `pacScript` string (optional) - The URL associated with the PAC file. * `proxyRules` string (optional) - Rules indicating which proxies to use. * `proxyBypassRules` string (optional) - Rules indicating which URLs should bypass the proxy settings. Returns `Promise<void>` - Resolves when the proxy setting process is complete. Sets the proxy settings. When `mode` is unspecified, `pacScript` and `proxyRules` are provided together, the `proxyRules` option is ignored and `pacScript` configuration is applied. You may need `ses.closeAllConnections` to close currently in flight connections to prevent pooled sockets using previous proxy from being reused by future requests. The `proxyRules` has to follow the rules below: ```sh proxyRules = schemeProxies[";"<schemeProxies>] schemeProxies = [<urlScheme>"="]<proxyURIList> urlScheme = "http" | "https" | "ftp" | "socks" proxyURIList = <proxyURL>[","<proxyURIList>] proxyURL = [<proxyScheme>"://"]<proxyHost>[":"<proxyPort>] ``` For example: * `http=foopy:80;ftp=foopy2` - Use HTTP proxy `foopy:80` for `http://` URLs, and HTTP proxy `foopy2:80` for `ftp://` URLs. * `foopy:80` - Use HTTP proxy `foopy:80` for all URLs. * `foopy:80,bar,direct://` - Use HTTP proxy `foopy:80` for all URLs, failing over to `bar` if `foopy:80` is unavailable, and after that using no proxy. * `socks4://foopy` - Use SOCKS v4 proxy `foopy:1080` for all URLs. * `http=foopy,socks5://bar.com` - Use HTTP proxy `foopy` for http URLs, and fail over to the SOCKS5 proxy `bar.com` if `foopy` is unavailable. * `http=foopy,direct://` - Use HTTP proxy `foopy` for http URLs, and use no proxy if `foopy` is unavailable. * `http=foopy;socks=foopy2` - Use HTTP proxy `foopy` for http URLs, and use `socks4://foopy2` for all other URLs. The `proxyBypassRules` is a comma separated list of rules described below: * `[ URL_SCHEME "://" ] HOSTNAME_PATTERN [ ":" <port> ]` Match all hostnames that match the pattern HOSTNAME_PATTERN. Examples: "foobar.com", "*foobar.com", "*.foobar.com", "*foobar.com:99", "https://x.*.y.com:99" * `"." HOSTNAME_SUFFIX_PATTERN [ ":" PORT ]` Match a particular domain suffix. Examples: ".google.com", ".com", "http://.google.com" * `[ SCHEME "://" ] IP_LITERAL [ ":" PORT ]` Match URLs which are IP address literals. Examples: "127.0.1", "[0:0::1]", "[::1]", "http://[::1]:99" * `IP_LITERAL "/" PREFIX_LENGTH_IN_BITS` Match any URL that is to an IP literal that falls between the given range. IP range is specified using CIDR notation. Examples: "192.168.1.1/16", "fefe:13::abc/33". * `<local>` Match local addresses. The meaning of `<local>` is whether the host matches one of: "127.0.0.1", "::1", "localhost". #### `ses.resolveProxy(url)` * `url` URL Returns `Promise<string>` - Resolves with the proxy information for `url`. #### `ses.forceReloadProxyConfig()` Returns `Promise<void>` - Resolves when the all internal states of proxy service is reset and the latest proxy configuration is reapplied if it's already available. The pac script will be fetched from `pacScript` again if the proxy mode is `pac_script`. #### `ses.setDownloadPath(path)` * `path` string - The download location. Sets download saving directory. By default, the download directory will be the `Downloads` under the respective app folder. #### `ses.enableNetworkEmulation(options)` * `options` Object * `offline` boolean (optional) - Whether to emulate network outage. Defaults to false. * `latency` Double (optional) - RTT in ms. Defaults to 0 which will disable latency throttling. * `downloadThroughput` Double (optional) - Download rate in Bps. Defaults to 0 which will disable download throttling. * `uploadThroughput` Double (optional) - Upload rate in Bps. Defaults to 0 which will disable upload throttling. Emulates network with the given configuration for the `session`. ```javascript // To emulate a GPRS connection with 50kbps throughput and 500 ms latency. window.webContents.session.enableNetworkEmulation({ latency: 500, downloadThroughput: 6400, uploadThroughput: 6400 }) // To emulate a network outage. window.webContents.session.enableNetworkEmulation({ offline: true }) ``` #### `ses.preconnect(options)` * `options` Object * `url` string - URL for preconnect. Only the origin is relevant for opening the socket. * `numSockets` number (optional) - number of sockets to preconnect. Must be between 1 and 6. Defaults to 1. Preconnects the given number of sockets to an origin. #### `ses.closeAllConnections()` Returns `Promise<void>` - Resolves when all connections are closed. **Note:** It will terminate / fail all requests currently in flight. #### `ses.disableNetworkEmulation()` Disables any network emulation already active for the `session`. Resets to the original network configuration. #### `ses.setCertificateVerifyProc(proc)` * `proc` Function | null * `request` Object * `hostname` string * `certificate` [Certificate](structures/certificate.md) * `validatedCertificate` [Certificate](structures/certificate.md) * `isIssuedByKnownRoot` boolean - `true` if Chromium recognises the root CA as a standard root. If it isn't then it's probably the case that this certificate was generated by a MITM proxy whose root has been installed locally (for example, by a corporate proxy). This should not be trusted if the `verificationResult` is not `OK`. * `verificationResult` string - `OK` if the certificate is trusted, otherwise an error like `CERT_REVOKED`. * `errorCode` Integer - Error code. * `callback` Function * `verificationResult` Integer - Value can be one of certificate error codes from [here](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h). Apart from the certificate error codes, the following special codes can be used. * `0` - Indicates success and disables Certificate Transparency verification. * `-2` - Indicates failure. * `-3` - Uses the verification result from chromium. Sets the certificate verify proc for `session`, the `proc` will be called with `proc(request, callback)` whenever a server certificate verification is requested. Calling `callback(0)` accepts the certificate, calling `callback(-2)` rejects it. Calling `setCertificateVerifyProc(null)` will revert back to default certificate verify proc. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.webContents.session.setCertificateVerifyProc((request, callback) => { const { hostname } = request if (hostname === 'github.com') { callback(0) } else { callback(-2) } }) ``` > **NOTE:** The result of this procedure is cached by the network service. #### `ses.setPermissionRequestHandler(handler)` * `handler` Function | null * `webContents` [WebContents](web-contents.md) - WebContents requesting the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin. * `permission` string - The type of requested permission. * `clipboard-read` - Request access to read from the clipboard. * `media` - Request access to media devices such as camera, microphone and speakers. * `display-capture` - Request access to capture the screen. * `mediaKeySystem` - Request access to DRM protected content. * `geolocation` - Request access to user's current location. * `notifications` - Request notification creation and the ability to display them in the user's system tray. * `midi` - Request MIDI access in the `webmidi` API. * `midiSysex` - Request the use of system exclusive messages in the `webmidi` API. * `pointerLock` - Request to directly interpret mouse movements as an input method. Click [here](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API) to know more. * `fullscreen` - Request for the app to enter fullscreen mode. * `openExternal` - Request to open links in external applications. * `unknown` - An unrecognized permission request * `callback` Function * `permissionGranted` boolean - Allow or deny the permission. * `details` Object - Some properties are only available on certain permission types. * `externalURL` string (optional) - The url of the `openExternal` request. * `securityOrigin` string (optional) - The security origin of the `media` request. * `mediaTypes` string[] (optional) - The types of media access being requested, elements can be `video` or `audio` * `requestingUrl` string - The last URL the requesting frame loaded * `isMainFrame` boolean - Whether the frame making the request is the main frame Sets the handler which can be used to respond to permission requests for the `session`. Calling `callback(true)` will allow the permission and `callback(false)` will reject it. To clear the handler, call `setPermissionRequestHandler(null)`. Please note that you must also implement `setPermissionCheckHandler` to get complete permission handling. Most web APIs do a permission check and then make a permission request if the check is denied. ```javascript const { session } = require('electron') session.fromPartition('some-partition').setPermissionRequestHandler((webContents, permission, callback) => { if (webContents.getURL() === 'some-host' && permission === 'notifications') { return callback(false) // denied. } callback(true) }) ``` #### `ses.setPermissionCheckHandler(handler)` * `handler` Function\<boolean> | null * `webContents` ([WebContents](web-contents.md) | null) - WebContents checking the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin. All cross origin sub frames making permission checks will pass a `null` webContents to this handler, while certain other permission checks such as `notifications` checks will always pass `null`. You should use `embeddingOrigin` and `requestingOrigin` to determine what origin the owning frame and the requesting frame are on respectively. * `permission` string - Type of permission check. Valid values are `midiSysex`, `notifications`, `geolocation`, `media`,`mediaKeySystem`,`midi`, `pointerLock`, `fullscreen`, `openExternal`, `hid`, or `serial`. * `requestingOrigin` string - The origin URL of the permission check * `details` Object - Some properties are only available on certain permission types. * `embeddingOrigin` string (optional) - The origin of the frame embedding the frame that made the permission check. Only set for cross-origin sub frames making permission checks. * `securityOrigin` string (optional) - The security origin of the `media` check. * `mediaType` string (optional) - The type of media access being requested, can be `video`, `audio` or `unknown` * `requestingUrl` string (optional) - The last URL the requesting frame loaded. This is not provided for cross-origin sub frames making permission checks. * `isMainFrame` boolean - Whether the frame making the request is the main frame Sets the handler which can be used to respond to permission checks for the `session`. Returning `true` will allow the permission and `false` will reject it. Please note that you must also implement `setPermissionRequestHandler` to get complete permission handling. Most web APIs do a permission check and then make a permission request if the check is denied. To clear the handler, call `setPermissionCheckHandler(null)`. ```javascript const { session } = require('electron') const url = require('url') session.fromPartition('some-partition').setPermissionCheckHandler((webContents, permission, requestingOrigin) => { if (new URL(requestingOrigin).hostname === 'some-host' && permission === 'notifications') { return true // granted } return false // denied }) ``` #### `ses.setDevicePermissionHandler(handler)` * `handler` Function\<boolean> | null * `details` Object * `deviceType` string - The type of device that permission is being requested on, can be `hid` or `serial`. * `origin` string - The origin URL of the device permission check. * `device` [HIDDevice](structures/hid-device.md) | [SerialPort](structures/serial-port.md)- the device that permission is being requested for. Sets the handler which can be used to respond to device permission checks for the `session`. Returning `true` will allow the device to be permitted and `false` will reject it. To clear the handler, call `setDevicePermissionHandler(null)`. This handler can be used to provide default permissioning to devices without first calling for permission to devices (eg via `navigator.hid.requestDevice`). If this handler is not defined, the default device permissions as granted through device selection (eg via `navigator.hid.requestDevice`) will be used. Additionally, the default behavior of Electron is to store granted device permision in memory. If longer term storage is needed, a developer can store granted device permissions (eg when handling the `select-hid-device` event) and then read from that storage with `setDevicePermissionHandler`. ```javascript const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow() win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'hid') { // Add logic here to determine if permission should be given to allow HID selection return true } else if (permission === 'serial') { // Add logic here to determine if permission should be given to allow serial port selection } return false }) // Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } else if (details.deviceType === 'serial') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first) return true } } return false }) win.webContents.session.on('select-hid-device', (event, details, callback) => { event.preventDefault() const selectedDevice = details.deviceList.find((device) => { return device.vendorId === '9025' && device.productId === '67' }) callback(selectedPort?.deviceId) }) }) ``` #### `ses.clearHostResolverCache()` Returns `Promise<void>` - Resolves when the operation is complete. Clears the host resolver cache. #### `ses.allowNTLMCredentialsForDomains(domains)` * `domains` string - A comma-separated list of servers for which integrated authentication is enabled. Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate authentication. ```javascript const { session } = require('electron') // consider any url ending with `example.com`, `foobar.com`, `baz` // for integrated authentication. session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz') // consider all urls for integrated authentication. session.defaultSession.allowNTLMCredentialsForDomains('*') ``` #### `ses.setUserAgent(userAgent[, acceptLanguages])` * `userAgent` string * `acceptLanguages` string (optional) Overrides the `userAgent` and `acceptLanguages` for this session. The `acceptLanguages` must a comma separated ordered list of language codes, for example `"en-US,fr,de,ko,zh-CN,ja"`. This doesn't affect existing `WebContents`, and each `WebContents` can use `webContents.setUserAgent` to override the session-wide user agent. #### `ses.isPersistent()` Returns `boolean` - Whether or not this session is a persistent one. The default `webContents` session of a `BrowserWindow` is persistent. When creating a session from a partition, session prefixed with `persist:` will be persistent, while others will be temporary. #### `ses.getUserAgent()` Returns `string` - The user agent for this session. #### `ses.setSSLConfig(config)` * `config` Object * `minVersion` string (optional) - Can be `tls1`, `tls1.1`, `tls1.2` or `tls1.3`. The minimum SSL version to allow when connecting to remote servers. Defaults to `tls1`. * `maxVersion` string (optional) - Can be `tls1.2` or `tls1.3`. The maximum SSL version to allow when connecting to remote servers. Defaults to `tls1.3`. * `disabledCipherSuites` Integer[] (optional) - List of cipher suites which should be explicitly prevented from being used in addition to those disabled by the net built-in policy. Supported literal forms: 0xAABB, where AA is `cipher_suite[0]` and BB is `cipher_suite[1]`, as defined in RFC 2246, Section 7.4.1.2. Unrecognized but parsable cipher suites in this form will not return an error. Ex: To disable TLS_RSA_WITH_RC4_128_MD5, specify 0x0004, while to disable TLS_ECDH_ECDSA_WITH_RC4_128_SHA, specify 0xC002. Note that TLSv1.3 ciphers cannot be disabled using this mechanism. Sets the SSL configuration for the session. All subsequent network requests will use the new configuration. Existing network connections (such as WebSocket connections) will not be terminated, but old sockets in the pool will not be reused for new connections. #### `ses.getBlobData(identifier)` * `identifier` string - Valid UUID. Returns `Promise<Buffer>` - resolves with blob data. #### `ses.downloadURL(url)` * `url` string Initiates a download of the resource at `url`. The API will generate a [DownloadItem](download-item.md) that can be accessed with the [will-download](#event-will-download) event. **Note:** This does not perform any security checks that relate to a page's origin, unlike [`webContents.downloadURL`](web-contents.md#contentsdownloadurlurl). #### `ses.createInterruptedDownload(options)` * `options` Object * `path` string - Absolute path of the download. * `urlChain` string[] - Complete URL chain for the download. * `mimeType` string (optional) * `offset` Integer - Start range for the download. * `length` Integer - Total length of the download. * `lastModified` string (optional) - Last-Modified header value. * `eTag` string (optional) - ETag header value. * `startTime` Double (optional) - Time when download was started in number of seconds since UNIX epoch. Allows resuming `cancelled` or `interrupted` downloads from previous `Session`. The API will generate a [DownloadItem](download-item.md) that can be accessed with the [will-download](#event-will-download) event. The [DownloadItem](download-item.md) will not have any `WebContents` associated with it and the initial state will be `interrupted`. The download will start only when the `resume` API is called on the [DownloadItem](download-item.md). #### `ses.clearAuthCache()` Returns `Promise<void>` - resolves when the session’s HTTP authentication cache has been cleared. #### `ses.setPreloads(preloads)` * `preloads` string[] - An array of absolute path to preload scripts Adds scripts that will be executed on ALL web contents that are associated with this session just before normal `preload` scripts run. #### `ses.getPreloads()` Returns `string[]` an array of paths to preload scripts that have been registered. #### `ses.setCodeCachePath(path)` * `path` String - Absolute path to store the v8 generated JS code cache from the renderer. Sets the directory to store the generated JS [code cache](https://v8.dev/blog/code-caching-for-devs) for this session. The directory is not required to be created by the user before this call, the runtime will create if it does not exist otherwise will use the existing directory. If directory cannot be created, then code cache will not be used and all operations related to code cache will fail silently inside the runtime. By default, the directory will be `Code Cache` under the respective user data folder. #### `ses.clearCodeCaches(options)` * `options` Object * `urls` String[] (optional) - An array of url corresponding to the resource whose generated code cache needs to be removed. If the list is empty then all entries in the cache directory will be removed. Returns `Promise<void>` - resolves when the code cache clear operation is complete. #### `ses.setSpellCheckerEnabled(enable)` * `enable` boolean Sets whether to enable the builtin spell checker. #### `ses.isSpellCheckerEnabled()` Returns `boolean` - Whether the builtin spell checker is enabled. #### `ses.setSpellCheckerLanguages(languages)` * `languages` string[] - An array of language codes to enable the spellchecker for. The built in spellchecker does not automatically detect what language a user is typing in. In order for the spell checker to correctly check their words you must call this API with an array of language codes. You can get the list of supported language codes with the `ses.availableSpellCheckerLanguages` property. **Note:** On macOS the OS spellchecker is used and will detect your language automatically. This API is a no-op on macOS. #### `ses.getSpellCheckerLanguages()` Returns `string[]` - An array of language codes the spellchecker is enabled for. If this list is empty the spellchecker will fallback to using `en-US`. By default on launch if this setting is an empty list Electron will try to populate this setting with the current OS locale. This setting is persisted across restarts. **Note:** On macOS the OS spellchecker is used and has its own list of languages. This API is a no-op on macOS. #### `ses.setSpellCheckerDictionaryDownloadURL(url)` * `url` string - A base URL for Electron to download hunspell dictionaries from. By default Electron will download hunspell dictionaries from the Chromium CDN. If you want to override this behavior you can use this API to point the dictionary downloader at your own hosted version of the hunspell dictionaries. We publish a `hunspell_dictionaries.zip` file with each release which contains the files you need to host here. The file server must be **case insensitive**. If you cannot do this, you must upload each file twice: once with the case it has in the ZIP file and once with the filename as all lowercase. If the files present in `hunspell_dictionaries.zip` are available at `https://example.com/dictionaries/language-code.bdic` then you should call this api with `ses.setSpellCheckerDictionaryDownloadURL('https://example.com/dictionaries/')`. Please note the trailing slash. The URL to the dictionaries is formed as `${url}${filename}`. **Note:** On macOS the OS spellchecker is used and therefore we do not download any dictionary files. This API is a no-op on macOS. #### `ses.listWordsInSpellCheckerDictionary()` Returns `Promise<string[]>` - An array of all words in app's custom dictionary. Resolves when the full dictionary is loaded from disk. #### `ses.addWordToSpellCheckerDictionary(word)` * `word` string - The word you want to add to the dictionary Returns `boolean` - Whether the word was successfully written to the custom dictionary. This API will not work on non-persistent (in-memory) sessions. **Note:** On macOS and Windows 10 this word will be written to the OS custom dictionary as well #### `ses.removeWordFromSpellCheckerDictionary(word)` * `word` string - The word you want to remove from the dictionary Returns `boolean` - Whether the word was successfully removed from the custom dictionary. This API will not work on non-persistent (in-memory) sessions. **Note:** On macOS and Windows 10 this word will be removed from the OS custom dictionary as well #### `ses.loadExtension(path[, options])` * `path` string - Path to a directory containing an unpacked Chrome extension * `options` Object (optional) * `allowFileAccess` boolean - Whether to allow the extension to read local files over `file://` protocol and inject content scripts into `file://` pages. This is required e.g. for loading devtools extensions on `file://` URLs. Defaults to false. Returns `Promise<Extension>` - resolves when the extension is loaded. This method will raise an exception if the extension could not be loaded. If there are warnings when installing the extension (e.g. if the extension requests an API that Electron does not support) then they will be logged to the console. Note that Electron does not support the full range of Chrome extensions APIs. See [Supported Extensions APIs](extensions.md#supported-extensions-apis) for more details on what is supported. Note that in previous versions of Electron, extensions that were loaded would be remembered for future runs of the application. This is no longer the case: `loadExtension` must be called on every boot of your app if you want the extension to be loaded. ```js const { app, session } = require('electron') const path = require('path') app.on('ready', async () => { await session.defaultSession.loadExtension( path.join(__dirname, 'react-devtools'), // allowFileAccess is required to load the devtools extension on file:// URLs. { allowFileAccess: true } ) // Note that in order to use the React DevTools extension, you'll need to // download and unzip a copy of the extension. }) ``` This API does not support loading packed (.crx) extensions. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. **Note:** Loading extensions into in-memory (non-persistent) sessions is not supported and will throw an error. #### `ses.removeExtension(extensionId)` * `extensionId` string - ID of extension to remove Unloads an extension. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. #### `ses.getExtension(extensionId)` * `extensionId` string - ID of extension to query Returns `Extension` | `null` - The loaded extension with the given ID. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. #### `ses.getAllExtensions()` Returns `Extension[]` - A list of all loaded extensions. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. #### `ses.getStoragePath()` A `string | null` indicating the absolute file system path where data for this session is persisted on disk. For in memory sessions this returns `null`. ### Instance Properties The following properties are available on instances of `Session`: #### `ses.availableSpellCheckerLanguages` _Readonly_ A `string[]` array which consists of all the known available spell checker languages. Providing a language code to the `setSpellCheckerLanguages` API that isn't in this array will result in an error. #### `ses.spellCheckerEnabled` A `boolean` indicating whether builtin spell checker is enabled. #### `ses.storagePath` _Readonly_ A `string | null` indicating the absolute file system path where data for this session is persisted on disk. For in memory sessions this returns `null`. #### `ses.cookies` _Readonly_ A [`Cookies`](cookies.md) object for this session. #### `ses.serviceWorkers` _Readonly_ A [`ServiceWorkers`](service-workers.md) object for this session. #### `ses.webRequest` _Readonly_ A [`WebRequest`](web-request.md) object for this session. #### `ses.protocol` _Readonly_ A [`Protocol`](protocol.md) object for this session. ```javascript const { app, session } = require('electron') const path = require('path') app.whenReady().then(() => { const protocol = session.fromPartition('some-partition').protocol if (!protocol.registerFileProtocol('atom', (request, callback) => { const url = request.url.substr(7) callback({ path: path.normalize(`${__dirname}/${url}`) }) })) { console.error('Failed to register protocol') } }) ``` #### `ses.netLog` _Readonly_ A [`NetLog`](net-log.md) object for this session. ```javascript const { app, session } = require('electron') app.whenReady().then(async () => { const netLog = session.fromPartition('some-partition').netLog netLog.startLogging('/path/to/net-log') // After some network events const path = await netLog.stopLogging() console.log('Net-logs written to', path) }) ```
closed
electron/electron
https://github.com/electron/electron
34,129
[Bug]: WCO on Windows occludes dev tools
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4.1 ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Using WCO and frameless windows on Windows, the WCO does not occlude the top right corner of the dev tools when they are placed on the right side. ### Actual Behavior Using WCO and frameless windows on Windows, the WCO occludes the top right corner of the dev tools when they are placed on the right side. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34129
https://github.com/electron/electron/pull/35209
eab7ab2c47c0750359a247450d9c7a41642b3dd1
4d54cadb281cceb9cf8de91773047ea2cc41da5f
2022-05-06T21:42:03Z
c++
2022-08-11T13:16:12Z
docs/api/web-contents.md
# webContents > Render and control web pages. Process: [Main](../glossary.md#main-process) `webContents` is an [EventEmitter][event-emitter]. It is responsible for rendering and controlling a web page and is a property of the [`BrowserWindow`](browser-window.md) object. An example of accessing the `webContents` object: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 1500 }) win.loadURL('http://github.com') const contents = win.webContents console.log(contents) ``` ## Methods These methods can be accessed from the `webContents` module: ```javascript const { webContents } = require('electron') console.log(webContents) ``` ### `webContents.getAllWebContents()` Returns `WebContents[]` - An array of all `WebContents` instances. This will contain web contents for all windows, webviews, opened devtools, and devtools extension background pages. ### `webContents.getFocusedWebContents()` Returns `WebContents` | null - The web contents that is focused in this application, otherwise returns `null`. ### `webContents.fromId(id)` * `id` Integer Returns `WebContents` | undefined - A WebContents instance with the given ID, or `undefined` if there is no WebContents associated with the given ID. ### `webContents.fromDevToolsTargetId(targetId)` * `targetId` string - The Chrome DevTools Protocol [TargetID](https://chromedevtools.github.io/devtools-protocol/tot/Target/#type-TargetID) associated with the WebContents instance. Returns `WebContents` | undefined - A WebContents instance with the given TargetID, or `undefined` if there is no WebContents associated with the given TargetID. When communicating with the [Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/), it can be useful to lookup a WebContents instance based on its assigned TargetID. ```js async function lookupTargetId (browserWindow) { const wc = browserWindow.webContents await wc.debugger.attach('1.3') const { targetInfo } = await wc.debugger.sendCommand('Target.getTargetInfo') const { targetId } = targetInfo const targetWebContents = await webContents.fromDevToolsTargetId(targetId) } ``` ## Class: WebContents > Render and control the contents of a BrowserWindow instance. Process: [Main](../glossary.md#main-process)<br /> _This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ ### Instance Events #### Event: 'did-finish-load' Emitted when the navigation is done, i.e. the spinner of the tab has stopped spinning, and the `onload` event was dispatched. #### Event: 'did-fail-load' Returns: * `event` Event * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer This event is like `did-finish-load` but emitted when the load failed. The full list of error codes and their meaning is available [here](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h). #### Event: 'did-fail-provisional-load' Returns: * `event` Event * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer This event is like `did-fail-load` but emitted when the load was cancelled (e.g. `window.stop()` was invoked). #### Event: 'did-frame-finish-load' Returns: * `event` Event * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when a frame has done navigation. #### Event: 'did-start-loading' Corresponds to the points in time when the spinner of the tab started spinning. #### Event: 'did-stop-loading' Corresponds to the points in time when the spinner of the tab stopped spinning. #### Event: 'dom-ready' Returns: * `event` Event Emitted when the document in the top-level frame is loaded. #### Event: 'page-title-updated' Returns: * `event` Event * `title` string * `explicitSet` boolean Fired when page title is set during navigation. `explicitSet` is false when title is synthesized from file url. #### Event: 'page-favicon-updated' Returns: * `event` Event * `favicons` string[] - Array of URLs. Emitted when page receives favicon urls. #### Event: 'did-create-window' Returns: * `window` BrowserWindow * `details` Object * `url` string - URL for the created window. * `frameName` string - Name given to the created window in the `window.open()` call. * `options` BrowserWindowConstructorOptions - The options used to create the BrowserWindow. They are merged in increasing precedence: parsed options from the `features` string from `window.open()`, security-related webPreferences inherited from the parent, and options given by [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). Unrecognized options are not filtered out. * `referrer` [Referrer](structures/referrer.md) - The referrer that will be passed to the new window. May or may not result in the `Referer` header being sent, depending on the referrer policy. * `postBody` [PostBody](structures/post-body.md) (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be `null`. Only defined when the window is being created by a form that set `target=_blank`. * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window`, `save-to-disk` and `other`. Emitted _after_ successful creation of a window via `window.open` in the renderer. Not emitted if the creation of the window is canceled from [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). See [`window.open()`](window-open.md) for more details and how to use this in conjunction with `webContents.setWindowOpenHandler`. #### Event: 'will-navigate' Returns: * `event` Event * `url` string Emitted when a user or the page wants to start navigation. It can happen when the `window.location` object is changed or a user clicks a link in the page. This event will not emit when the navigation is started programmatically with APIs like `webContents.loadURL` and `webContents.back`. It is also not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. Calling `event.preventDefault()` will prevent the navigation. #### Event: 'did-start-navigation' Returns: * `event` Event * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame (including main) starts navigating. `isInPlace` will be `true` for in-page navigations. #### Event: 'will-redirect' Returns: * `event` Event * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when a server side redirect occurs during navigation. For example a 302 redirect. This event will be emitted after `did-start-navigation` and always before the `did-redirect-navigation` event for the same navigation. Calling `event.preventDefault()` will prevent the navigation (not just the redirect). #### Event: 'did-redirect-navigation' Returns: * `event` Event * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted after a server side redirect occurs during navigation. For example a 302 redirect. This event cannot be prevented, if you want to prevent redirects you should checkout out the `will-redirect` event above. #### Event: 'did-navigate' Returns: * `event` Event * `url` string * `httpResponseCode` Integer - -1 for non HTTP navigations * `httpStatusText` string - empty for non HTTP navigations Emitted when a main frame navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. #### Event: 'did-frame-navigate' Returns: * `event` Event * `url` string * `httpResponseCode` Integer - -1 for non HTTP navigations * `httpStatusText` string - empty for non HTTP navigations, * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. #### Event: 'did-navigate-in-page' Returns: * `event` Event * `url` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when an in-page navigation happened in any frame. When in-page navigation happens, the page URL changes but does not cause navigation outside of the page. Examples of this occurring are when anchor links are clicked or when the DOM `hashchange` event is triggered. #### Event: 'will-prevent-unload' Returns: * `event` Event Emitted when a `beforeunload` event handler is attempting to cancel a page unload. Calling `event.preventDefault()` will ignore the `beforeunload` event handler and allow the page to be unloaded. ```javascript const { BrowserWindow, dialog } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('will-prevent-unload', (event) => { const choice = dialog.showMessageBoxSync(win, { type: 'question', buttons: ['Leave', 'Stay'], title: 'Do you want to leave this site?', message: 'Changes you made may not be saved.', defaultId: 0, cancelId: 1 }) const leave = (choice === 0) if (leave) { event.preventDefault() } }) ``` **Note:** This will be emitted for `BrowserViews` but will _not_ be respected - this is because we have chosen not to tie the `BrowserView` lifecycle to its owning BrowserWindow should one exist per the [specification](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event). #### Event: 'crashed' _Deprecated_ Returns: * `event` Event * `killed` boolean Emitted when the renderer process crashes or is killed. **Deprecated:** This event is superceded by the `render-process-gone` event which contains more information about why the render process disappeared. It isn't always because it crashed. The `killed` boolean can be replaced by checking `reason === 'killed'` when you switch to that event. #### Event: 'render-process-gone' Returns: * `event` Event * `details` Object * `reason` string - The reason the render process is gone. Possible values: * `clean-exit` - Process exited with an exit code of zero * `abnormal-exit` - Process exited with a non-zero exit code * `killed` - Process was sent a SIGTERM or otherwise killed externally * `crashed` - Process crashed * `oom` - Process ran out of memory * `launch-failed` - Process never successfully launched * `integrity-failure` - Windows code integrity checks failed * `exitCode` Integer - The exit code of the process, unless `reason` is `launch-failed`, in which case `exitCode` will be a platform-specific launch failure error code. Emitted when the renderer process unexpectedly disappears. This is normally because it was crashed or killed. #### Event: 'unresponsive' Emitted when the web page becomes unresponsive. #### Event: 'responsive' Emitted when the unresponsive web page becomes responsive again. #### Event: 'plugin-crashed' Returns: * `event` Event * `name` string * `version` string Emitted when a plugin process has crashed. #### Event: 'destroyed' Emitted when `webContents` is destroyed. #### Event: 'before-input-event' Returns: * `event` Event * `input` Object - Input properties. * `type` string - Either `keyUp` or `keyDown`. * `key` string - Equivalent to [KeyboardEvent.key][keyboardevent]. * `code` string - Equivalent to [KeyboardEvent.code][keyboardevent]. * `isAutoRepeat` boolean - Equivalent to [KeyboardEvent.repeat][keyboardevent]. * `isComposing` boolean - Equivalent to [KeyboardEvent.isComposing][keyboardevent]. * `shift` boolean - Equivalent to [KeyboardEvent.shiftKey][keyboardevent]. * `control` boolean - Equivalent to [KeyboardEvent.controlKey][keyboardevent]. * `alt` boolean - Equivalent to [KeyboardEvent.altKey][keyboardevent]. * `meta` boolean - Equivalent to [KeyboardEvent.metaKey][keyboardevent]. * `location` number - Equivalent to [KeyboardEvent.location][keyboardevent]. * `modifiers` string[] - See [InputEvent.modifiers](structures/input-event.md). Emitted before dispatching the `keydown` and `keyup` events in the page. Calling `event.preventDefault` will prevent the page `keydown`/`keyup` events and the menu shortcuts. To only prevent the menu shortcuts, use [`setIgnoreMenuShortcuts`](#contentssetignoremenushortcutsignore): ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('before-input-event', (event, input) => { // For example, only enable application menu keyboard shortcuts when // Ctrl/Cmd are down. win.webContents.setIgnoreMenuShortcuts(!input.control && !input.meta) }) ``` #### Event: 'enter-html-full-screen' Emitted when the window enters a full-screen state triggered by HTML API. #### Event: 'leave-html-full-screen' Emitted when the window leaves a full-screen state triggered by HTML API. #### Event: 'zoom-changed' Returns: * `event` Event * `zoomDirection` string - Can be `in` or `out`. Emitted when the user is requesting to change the zoom level using the mouse wheel. #### Event: 'blur' Emitted when the `WebContents` loses focus. #### Event: 'focus' Emitted when the `WebContents` gains focus. Note that on macOS, having focus means the `WebContents` is the first responder of window, so switching focus between windows would not trigger the `focus` and `blur` events of `WebContents`, as the first responder of each window is not changed. The `focus` and `blur` events of `WebContents` should only be used to detect focus change between different `WebContents` and `BrowserView` in the same window. #### Event: 'devtools-opened' Emitted when DevTools is opened. #### Event: 'devtools-closed' Emitted when DevTools is closed. #### Event: 'devtools-focused' Emitted when DevTools is focused / opened. #### Event: 'certificate-error' Returns: * `event` Event * `url` string * `error` string - The error code. * `certificate` [Certificate](structures/certificate.md) * `callback` Function * `isTrusted` boolean - Indicates whether the certificate can be considered trusted. * `isMainFrame` boolean Emitted when failed to verify the `certificate` for `url`. The usage is the same with [the `certificate-error` event of `app`](app.md#event-certificate-error). #### Event: 'select-client-certificate' Returns: * `event` Event * `url` URL * `certificateList` [Certificate[]](structures/certificate.md) * `callback` Function * `certificate` [Certificate](structures/certificate.md) - Must be a certificate from the given list. Emitted when a client certificate is requested. The usage is the same with [the `select-client-certificate` event of `app`](app.md#event-select-client-certificate). #### Event: 'login' Returns: * `event` Event * `authenticationResponseDetails` Object * `url` URL * `authInfo` Object * `isProxy` boolean * `scheme` string * `host` string * `port` Integer * `realm` string * `callback` Function * `username` string (optional) * `password` string (optional) Emitted when `webContents` wants to do basic auth. The usage is the same with [the `login` event of `app`](app.md#event-login). #### Event: 'found-in-page' Returns: * `event` Event * `result` Object * `requestId` Integer * `activeMatchOrdinal` Integer - Position of the active match. * `matches` Integer - Number of Matches. * `selectionArea` Rectangle - Coordinates of first match region. * `finalUpdate` boolean Emitted when a result is available for [`webContents.findInPage`] request. #### Event: 'media-started-playing' Emitted when media starts playing. #### Event: 'media-paused' Emitted when media is paused or done playing. #### Event: 'did-change-theme-color' Returns: * `event` Event * `color` (string | null) - Theme color is in format of '#rrggbb'. It is `null` when no theme color is set. Emitted when a page's theme color changes. This is usually due to encountering a meta tag: ```html <meta name='theme-color' content='#ff0000'> ``` #### Event: 'update-target-url' Returns: * `event` Event * `url` string Emitted when mouse moves over a link or the keyboard moves the focus to a link. #### Event: 'cursor-changed' Returns: * `event` Event * `type` string * `image` [NativeImage](native-image.md) (optional) * `scale` Float (optional) - scaling factor for the custom cursor. * `size` [Size](structures/size.md) (optional) - the size of the `image`. * `hotspot` [Point](structures/point.md) (optional) - coordinates of the custom cursor's hotspot. Emitted when the cursor's type changes. The `type` parameter can be `default`, `crosshair`, `pointer`, `text`, `wait`, `help`, `e-resize`, `n-resize`, `ne-resize`, `nw-resize`, `s-resize`, `se-resize`, `sw-resize`, `w-resize`, `ns-resize`, `ew-resize`, `nesw-resize`, `nwse-resize`, `col-resize`, `row-resize`, `m-panning`, `e-panning`, `n-panning`, `ne-panning`, `nw-panning`, `s-panning`, `se-panning`, `sw-panning`, `w-panning`, `move`, `vertical-text`, `cell`, `context-menu`, `alias`, `progress`, `nodrop`, `copy`, `none`, `not-allowed`, `zoom-in`, `zoom-out`, `grab`, `grabbing` or `custom`. If the `type` parameter is `custom`, the `image` parameter will hold the custom cursor image in a [`NativeImage`](native-image.md), and `scale`, `size` and `hotspot` will hold additional information about the custom cursor. #### Event: 'context-menu' Returns: * `event` Event * `params` Object * `x` Integer - x coordinate. * `y` Integer - y coordinate. * `frame` WebFrameMain - Frame from which the context menu was invoked. * `linkURL` string - URL of the link that encloses the node the context menu was invoked on. * `linkText` string - Text associated with the link. May be an empty string if the contents of the link are an image. * `pageURL` string - URL of the top level page that the context menu was invoked on. * `frameURL` string - URL of the subframe that the context menu was invoked on. * `srcURL` string - Source URL for the element that the context menu was invoked on. Elements with source URLs are images, audio and video. * `mediaType` string - Type of the node the context menu was invoked on. Can be `none`, `image`, `audio`, `video`, `canvas`, `file` or `plugin`. * `hasImageContents` boolean - Whether the context menu was invoked on an image which has non-empty contents. * `isEditable` boolean - Whether the context is editable. * `selectionText` string - Text of the selection that the context menu was invoked on. * `titleText` string - Title text of the selection that the context menu was invoked on. * `altText` string - Alt text of the selection that the context menu was invoked on. * `suggestedFilename` string - Suggested filename to be used when saving file through 'Save Link As' option of context menu. * `selectionRect` [Rectangle](structures/rectangle.md) - Rect representing the coordinates in the document space of the selection. * `selectionStartOffset` number - Start position of the selection text. * `referrerPolicy` [Referrer](structures/referrer.md) - The referrer policy of the frame on which the menu is invoked. * `misspelledWord` string - The misspelled word under the cursor, if any. * `dictionarySuggestions` string[] - An array of suggested words to show the user to replace the `misspelledWord`. Only available if there is a misspelled word and spellchecker is enabled. * `frameCharset` string - The character encoding of the frame on which the menu was invoked. * `inputFieldType` string - If the context menu was invoked on an input field, the type of that field. Possible values are `none`, `plainText`, `password`, `other`. * `spellcheckEnabled` boolean - If the context is editable, whether or not spellchecking is enabled. * `menuSourceType` string - Input source that invoked the context menu. Can be `none`, `mouse`, `keyboard`, `touch`, `touchMenu`, `longPress`, `longTap`, `touchHandle`, `stylus`, `adjustSelection`, or `adjustSelectionReset`. * `mediaFlags` Object - The flags for the media element the context menu was invoked on. * `inError` boolean - Whether the media element has crashed. * `isPaused` boolean - Whether the media element is paused. * `isMuted` boolean - Whether the media element is muted. * `hasAudio` boolean - Whether the media element has audio. * `isLooping` boolean - Whether the media element is looping. * `isControlsVisible` boolean - Whether the media element's controls are visible. * `canToggleControls` boolean - Whether the media element's controls are toggleable. * `canPrint` boolean - Whether the media element can be printed. * `canSave` boolean - Whether or not the media element can be downloaded. * `canShowPictureInPicture` boolean - Whether the media element can show picture-in-picture. * `isShowingPictureInPicture` boolean - Whether the media element is currently showing picture-in-picture. * `canRotate` boolean - Whether the media element can be rotated. * `canLoop` boolean - Whether the media element can be looped. * `editFlags` Object - These flags indicate whether the renderer believes it is able to perform the corresponding action. * `canUndo` boolean - Whether the renderer believes it can undo. * `canRedo` boolean - Whether the renderer believes it can redo. * `canCut` boolean - Whether the renderer believes it can cut. * `canCopy` boolean - Whether the renderer believes it can copy. * `canPaste` boolean - Whether the renderer believes it can paste. * `canDelete` boolean - Whether the renderer believes it can delete. * `canSelectAll` boolean - Whether the renderer believes it can select all. * `canEditRichly` boolean - Whether the renderer believes it can edit text richly. Emitted when there is a new context menu that needs to be handled. #### Event: 'select-bluetooth-device' Returns: * `event` Event * `devices` [BluetoothDevice[]](structures/bluetooth-device.md) * `callback` Function * `deviceId` string Emitted when bluetooth device needs to be selected on call to `navigator.bluetooth.requestDevice`. To use `navigator.bluetooth` api `webBluetooth` should be enabled. If `event.preventDefault` is not called, first available device will be selected. `callback` should be called with `deviceId` to be selected, passing empty string to `callback` will cancel the request. If no event listener is added for this event, all bluetooth requests will be cancelled. ```javascript const { app, BrowserWindow } = require('electron') let win = null app.commandLine.appendSwitch('enable-experimental-web-platform-features') app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('select-bluetooth-device', (event, deviceList, callback) => { event.preventDefault() const result = deviceList.find((device) => { return device.deviceName === 'test' }) if (!result) { callback('') } else { callback(result.deviceId) } }) }) ``` #### Event: 'paint' Returns: * `event` Event * `dirtyRect` [Rectangle](structures/rectangle.md) * `image` [NativeImage](native-image.md) - The image data of the whole frame. Emitted when a new frame is generated. Only the dirty area is passed in the buffer. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ webPreferences: { offscreen: true } }) win.webContents.on('paint', (event, dirty, image) => { // updateBitmap(dirty, image.getBitmap()) }) win.loadURL('http://github.com') ``` #### Event: 'devtools-reload-page' Emitted when the devtools window instructs the webContents to reload #### Event: 'will-attach-webview' Returns: * `event` Event * `webPreferences` WebPreferences - The web preferences that will be used by the guest page. This object can be modified to adjust the preferences for the guest page. * `params` Record<string, string> - The other `<webview>` parameters such as the `src` URL. This object can be modified to adjust the parameters of the guest page. Emitted when a `<webview>`'s web contents is being attached to this web contents. Calling `event.preventDefault()` will destroy the guest page. This event can be used to configure `webPreferences` for the `webContents` of a `<webview>` before it's loaded, and provides the ability to set settings that can't be set via `<webview>` attributes. #### Event: 'did-attach-webview' Returns: * `event` Event * `webContents` WebContents - The guest web contents that is used by the `<webview>`. Emitted when a `<webview>` has been attached to this web contents. #### Event: 'console-message' Returns: * `event` Event * `level` Integer - The log level, from 0 to 3. In order it matches `verbose`, `info`, `warning` and `error`. * `message` string - The actual console message * `line` Integer - The line number of the source that triggered this console message * `sourceId` string Emitted when the associated window logs a console message. #### Event: 'preload-error' Returns: * `event` Event * `preloadPath` string * `error` Error Emitted when the preload script `preloadPath` throws an unhandled exception `error`. #### Event: 'ipc-message' Returns: * `event` Event * `channel` string * `...args` any[] Emitted when the renderer process sends an asynchronous message via `ipcRenderer.send()`. See also [`webContents.ipc`](#contentsipc-readonly), which provides an [`IpcMain`](ipc-main.md)-like interface for responding to IPC messages specifically from this WebContents. #### Event: 'ipc-message-sync' Returns: * `event` Event * `channel` string * `...args` any[] Emitted when the renderer process sends a synchronous message via `ipcRenderer.sendSync()`. See also [`webContents.ipc`](#contentsipc-readonly), which provides an [`IpcMain`](ipc-main.md)-like interface for responding to IPC messages specifically from this WebContents. #### Event: 'preferred-size-changed' Returns: * `event` Event * `preferredSize` [Size](structures/size.md) - The minimum size needed to contain the layout of the document—without requiring scrolling. Emitted when the `WebContents` preferred size has changed. This event will only be emitted when `enablePreferredSizeMode` is set to `true` in `webPreferences`. #### Event: 'frame-created' Returns: * `event` Event * `details` Object * `frame` WebFrameMain Emitted when the [mainFrame](web-contents.md#contentsmainframe-readonly), an `<iframe>`, or a nested `<iframe>` is loaded within the page. ### Instance Methods #### `contents.loadURL(url[, options])` * `url` string * `options` Object (optional) * `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer url. * `userAgent` string (optional) - A user agent originating the request. * `extraHeaders` string (optional) - Extra headers separated by "\n". * `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional) * `baseURLForDataURL` string (optional) - Base url (with trailing path separator) for files to be loaded by the data url. This is needed only if the specified `url` is a data url and needs to load other files. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). A noop rejection handler is already attached, which avoids unhandled rejection errors. Loads the `url` in the window. The `url` must contain the protocol prefix, e.g. the `http://` or `file://`. If the load should bypass http cache then use the `pragma` header to achieve it. ```javascript const { webContents } = require('electron') const options = { extraHeaders: 'pragma: no-cache\n' } webContents.loadURL('https://github.com', options) ``` #### `contents.loadFile(filePath[, options])` * `filePath` string * `options` Object (optional) * `query` Record<string, string> (optional) - Passed to `url.format()`. * `search` string (optional) - Passed to `url.format()`. * `hash` string (optional) - Passed to `url.format()`. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). Loads the given file in the window, `filePath` should be a path to an HTML file relative to the root of your application. For instance an app structure like this: ```sh | root | - package.json | - src | - main.js | - index.html ``` Would require code like this ```js win.loadFile('src/index.html') ``` #### `contents.downloadURL(url)` * `url` string Initiates a download of the resource at `url` without navigating. The `will-download` event of `session` will be triggered. #### `contents.getURL()` Returns `string` - The URL of the current web page. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('http://github.com').then(() => { const currentURL = win.webContents.getURL() console.log(currentURL) }) ``` #### `contents.getTitle()` Returns `string` - The title of the current web page. #### `contents.isDestroyed()` Returns `boolean` - Whether the web page is destroyed. #### `contents.focus()` Focuses the web page. #### `contents.isFocused()` Returns `boolean` - Whether the web page is focused. #### `contents.isLoading()` Returns `boolean` - Whether web page is still loading resources. #### `contents.isLoadingMainFrame()` Returns `boolean` - Whether the main frame (and not just iframes or frames within it) is still loading. #### `contents.isWaitingForResponse()` Returns `boolean` - Whether the web page is waiting for a first-response from the main resource of the page. #### `contents.stop()` Stops any pending navigation. #### `contents.reload()` Reloads the current web page. #### `contents.reloadIgnoringCache()` Reloads current page and ignores cache. #### `contents.canGoBack()` Returns `boolean` - Whether the browser can go back to previous web page. #### `contents.canGoForward()` Returns `boolean` - Whether the browser can go forward to next web page. #### `contents.canGoToOffset(offset)` * `offset` Integer Returns `boolean` - Whether the web page can go to `offset`. #### `contents.clearHistory()` Clears the navigation history. #### `contents.goBack()` Makes the browser go back a web page. #### `contents.goForward()` Makes the browser go forward a web page. #### `contents.goToIndex(index)` * `index` Integer Navigates browser to the specified absolute web page index. #### `contents.goToOffset(offset)` * `offset` Integer Navigates to the specified offset from the "current entry". #### `contents.isCrashed()` Returns `boolean` - Whether the renderer process has crashed. #### `contents.forcefullyCrashRenderer()` Forcefully terminates the renderer process that is currently hosting this `webContents`. This will cause the `render-process-gone` event to be emitted with the `reason=killed || reason=crashed`. Please note that some webContents share renderer processes and therefore calling this method may also crash the host process for other webContents as well. Calling `reload()` immediately after calling this method will force the reload to occur in a new process. This should be used when this process is unstable or unusable, for instance in order to recover from the `unresponsive` event. ```js contents.on('unresponsive', async () => { const { response } = await dialog.showMessageBox({ message: 'App X has become unresponsive', title: 'Do you want to try forcefully reloading the app?', buttons: ['OK', 'Cancel'], cancelId: 1 }) if (response === 0) { contents.forcefullyCrashRenderer() contents.reload() } }) ``` #### `contents.setUserAgent(userAgent)` * `userAgent` string Overrides the user agent for this web page. #### `contents.getUserAgent()` Returns `string` - The user agent for this web page. #### `contents.insertCSS(css[, options])` * `css` string * `options` Object (optional) * `cssOrigin` string (optional) - Can be either 'user' or 'author'. Sets the [cascade origin](https://www.w3.org/TR/css3-cascade/#cascade-origin) of the inserted stylesheet. Default is 'author'. Returns `Promise<string>` - A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via `contents.removeInsertedCSS(key)`. Injects CSS into the current web page and returns a unique key for the inserted stylesheet. ```js contents.on('did-finish-load', () => { contents.insertCSS('html, body { background-color: #f00; }') }) ``` #### `contents.removeInsertedCSS(key)` * `key` string Returns `Promise<void>` - Resolves if the removal was successful. Removes the inserted CSS from the current web page. The stylesheet is identified by its key, which is returned from `contents.insertCSS(css)`. ```js contents.on('did-finish-load', async () => { const key = await contents.insertCSS('html, body { background-color: #f00; }') contents.removeInsertedCSS(key) }) ``` #### `contents.executeJavaScript(code[, userGesture])` * `code` string * `userGesture` boolean (optional) - Default is `false`. Returns `Promise<any>` - A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise. Evaluates `code` in page. In the browser window some HTML APIs like `requestFullScreen` can only be invoked by a gesture from the user. Setting `userGesture` to `true` will remove this limitation. Code execution will be suspended until web page stop loading. ```js contents.executeJavaScript('fetch("https://jsonplaceholder.typicode.com/users/1").then(resp => resp.json())', true) .then((result) => { console.log(result) // Will be the JSON object from the fetch call }) ``` #### `contents.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture])` * `worldId` Integer - The ID of the world to run the javascript in, `0` is the default world, `999` is the world used by Electron's `contextIsolation` feature. You can provide any integer here. * `scripts` [WebSource[]](structures/web-source.md) * `userGesture` boolean (optional) - Default is `false`. Returns `Promise<any>` - A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise. Works like `executeJavaScript` but evaluates `scripts` in an isolated context. #### `contents.setIgnoreMenuShortcuts(ignore)` * `ignore` boolean Ignore application menu shortcuts while this web contents is focused. #### `contents.setWindowOpenHandler(handler)` * `handler` Function<{action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}> * `details` Object * `url` string - The _resolved_ version of the URL passed to `window.open()`. e.g. opening a window with `window.open('foo')` will yield something like `https://the-origin/the/current/path/foo`. * `frameName` string - Name of the window provided in `window.open()` * `features` string - Comma separated list of window features provided to `window.open()`. * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window`, `save-to-disk` or `other`. * `referrer` [Referrer](structures/referrer.md) - The referrer that will be passed to the new window. May or may not result in the `Referer` header being sent, depending on the referrer policy. * `postBody` [PostBody](structures/post-body.md) (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be `null`. Only defined when the window is being created by a form that set `target=_blank`. Returns `{action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}` - `deny` cancels the creation of the new window. `allow` will allow the new window to be created. Specifying `overrideBrowserWindowOptions` allows customization of the created window. Returning an unrecognized value such as a null, undefined, or an object without a recognized 'action' value will result in a console error and have the same effect as returning `{action: 'deny'}`. Called before creating a window a new window is requested by the renderer, e.g. by `window.open()`, a link with `target="_blank"`, shift+clicking on a link, or submitting a form with `<form target="_blank">`. See [`window.open()`](window-open.md) for more details and how to use this in conjunction with `did-create-window`. #### `contents.setAudioMuted(muted)` * `muted` boolean Mute the audio on the current web page. #### `contents.isAudioMuted()` Returns `boolean` - Whether this page has been muted. #### `contents.isCurrentlyAudible()` Returns `boolean` - Whether audio is currently playing. #### `contents.setZoomFactor(factor)` * `factor` Double - Zoom factor; default is 1.0. Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0. The factor must be greater than 0.0. #### `contents.getZoomFactor()` Returns `number` - the current zoom factor. #### `contents.setZoomLevel(level)` * `level` number - Zoom level. Changes the zoom level to the specified level. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`. > **NOTE**: The zoom policy at the Chromium level is same-origin, meaning that the > zoom level for a specific domain propagates across all instances of windows with > the same domain. Differentiating the window URLs will make zoom work per-window. #### `contents.getZoomLevel()` Returns `number` - the current zoom level. #### `contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)` * `minimumLevel` number * `maximumLevel` number Returns `Promise<void>` Sets the maximum and minimum pinch-to-zoom level. > **NOTE**: Visual zoom is disabled by default in Electron. To re-enable it, call: > > ```js > contents.setVisualZoomLevelLimits(1, 3) > ``` #### `contents.undo()` Executes the editing command `undo` in web page. #### `contents.redo()` Executes the editing command `redo` in web page. #### `contents.cut()` Executes the editing command `cut` in web page. #### `contents.copy()` Executes the editing command `copy` in web page. #### `contents.copyImageAt(x, y)` * `x` Integer * `y` Integer Copy the image at the given position to the clipboard. #### `contents.paste()` Executes the editing command `paste` in web page. #### `contents.pasteAndMatchStyle()` Executes the editing command `pasteAndMatchStyle` in web page. #### `contents.delete()` Executes the editing command `delete` in web page. #### `contents.selectAll()` Executes the editing command `selectAll` in web page. #### `contents.unselect()` Executes the editing command `unselect` in web page. #### `contents.replace(text)` * `text` string Executes the editing command `replace` in web page. #### `contents.replaceMisspelling(text)` * `text` string Executes the editing command `replaceMisspelling` in web page. #### `contents.insertText(text)` * `text` string Returns `Promise<void>` Inserts `text` to the focused element. #### `contents.findInPage(text[, options])` * `text` string - Content to be searched, must not be empty. * `options` Object (optional) * `forward` boolean (optional) - Whether to search forward or backward, defaults to `true`. * `findNext` boolean (optional) - Whether to begin a new text finding session with this request. Should be `true` for initial requests, and `false` for follow-up requests. Defaults to `false`. * `matchCase` boolean (optional) - Whether search should be case-sensitive, defaults to `false`. Returns `Integer` - The request id used for the request. Starts a request to find all matches for the `text` in the web page. The result of the request can be obtained by subscribing to [`found-in-page`](web-contents.md#event-found-in-page) event. #### `contents.stopFindInPage(action)` * `action` string - Specifies the action to take place when ending [`webContents.findInPage`] request. * `clearSelection` - Clear the selection. * `keepSelection` - Translate the selection into a normal selection. * `activateSelection` - Focus and click the selection node. Stops any `findInPage` request for the `webContents` with the provided `action`. ```javascript const { webContents } = require('electron') webContents.on('found-in-page', (event, result) => { if (result.finalUpdate) webContents.stopFindInPage('clearSelection') }) const requestId = webContents.findInPage('api') console.log(requestId) ``` #### `contents.capturePage([rect])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured. Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md) Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. #### `contents.isBeingCaptured()` Returns `boolean` - Whether this page is being captured. It returns true when the capturer count is large then 0. #### `contents.incrementCapturerCount([size, stayHidden, stayAwake])` * `size` [Size](structures/size.md) (optional) - The preferred size for the capturer. * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Increase the capturer count by one. The page is considered visible when its browser window is hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true. This also affects the Page Visibility API. #### `contents.decrementCapturerCount([stayHidden, stayAwake])` * `stayHidden` boolean (optional) - Keep the page in hidden state instead of visible. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Decrease the capturer count by one. The page will be set to hidden or occluded state when its browser window is hidden or occluded and the capturer count reaches zero. If you want to decrease the hidden capturer count instead you should set `stayHidden` to true. #### `contents.getPrinters()` _Deprecated_ Get the system printer list. Returns [`PrinterInfo[]`](structures/printer-info.md) **Deprecated:** Should use the new [`contents.getPrintersAsync`](web-contents.md#contentsgetprintersasync) API. #### `contents.getPrintersAsync()` Get the system printer list. Returns `Promise<PrinterInfo[]>` - Resolves with a [`PrinterInfo[]`](structures/printer-info.md) #### `contents.print([options], [callback])` * `options` Object (optional) * `silent` boolean (optional) - Don't ask user for print settings. Default is `false`. * `printBackground` boolean (optional) - Prints the background color and image of the web page. Default is `false`. * `deviceName` string (optional) - Set the printer device name to use. Must be the system-defined name and not the 'friendly' name, e.g 'Brother_QL_820NWB' and not 'Brother QL-820NWB'. * `color` boolean (optional) - Set whether the printed web page will be in color or grayscale. Default is `true`. * `margins` Object (optional) * `marginType` string (optional) - Can be `default`, `none`, `printableArea`, or `custom`. If `custom` is chosen, you will also need to specify `top`, `bottom`, `left`, and `right`. * `top` number (optional) - The top margin of the printed web page, in pixels. * `bottom` number (optional) - The bottom margin of the printed web page, in pixels. * `left` number (optional) - The left margin of the printed web page, in pixels. * `right` number (optional) - The right margin of the printed web page, in pixels. * `landscape` boolean (optional) - Whether the web page should be printed in landscape mode. Default is `false`. * `scaleFactor` number (optional) - The scale factor of the web page. * `pagesPerSheet` number (optional) - The number of pages to print per page sheet. * `collate` boolean (optional) - Whether the web page should be collated. * `copies` number (optional) - The number of copies of the web page to print. * `pageRanges` Object[] (optional) - The page range to print. On macOS, only one range is honored. * `from` number - Index of the first page to print (0-based). * `to` number - Index of the last page to print (inclusive) (0-based). * `duplexMode` string (optional) - Set the duplex mode of the printed web page. Can be `simplex`, `shortEdge`, or `longEdge`. * `dpi` Record<string, number> (optional) * `horizontal` number (optional) - The horizontal dpi. * `vertical` number (optional) - The vertical dpi. * `header` string (optional) - string to be printed as page header. * `footer` string (optional) - string to be printed as page footer. * `pageSize` string | Size (optional) - Specify page size of the printed document. Can be `A3`, `A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` and `width`. * `callback` Function (optional) * `success` boolean - Indicates success of the print call. * `failureReason` string - Error description called back if the print fails. When a custom `pageSize` is passed, Chromium attempts to validate platform specific minimum values for `width_microns` and `height_microns`. Width and height must both be minimum 353 microns but may be higher on some operating systems. Prints window's web page. When `silent` is set to `true`, Electron will pick the system's default printer if `deviceName` is empty and the default settings for printing. Use `page-break-before: always;` CSS style to force to print to a new page. Example usage: ```js const options = { silent: true, deviceName: 'My-Printer', pageRanges: [{ from: 0, to: 1 }] } win.webContents.print(options, (success, errorType) => { if (!success) console.log(errorType) }) ``` #### `contents.printToPDF(options)` * `options` Object * `landscape` boolean (optional) - Paper orientation.`true` for landscape, `false` for portrait. Defaults to false. * `displayHeaderFooter` boolean (optional) - Whether to display header and footer. Defaults to false. * `printBackground` boolean (optional) - Whether to print background graphics. Defaults to false. * `scale` number(optional) - Scale of the webpage rendering. Defaults to 1. * `pageSize` string | Size (optional) - Specify page size of the generated PDF. Can be `A0`, `A1`, `A2`, `A3`, `A4`, `A5`, `A6`, `Legal`, `Letter`, `Tabloid`, `Ledger`, or an Object containing `height` and `width` in inches. Defaults to `Letter`. * `margins` Object (optional) * `top` number (optional) - Top margin in inches. Defaults to 1cm (~0.4 inches). * `bottom` number (optional) - Bottom margin in inches. Defaults to 1cm (~0.4 inches). * `left` number (optional) - Left margin in inches. Defaults to 1cm (~0.4 inches). * `right` number (optional) - Right margin in inches. Defaults to 1cm (~0.4 inches). * `pageRanges` string (optional) - Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages. * `headerTemplate` string (optional) - HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: `date` (formatted print date), `title` (document title), `url` (document location), `pageNumber` (current page number) and `totalPages` (total pages in the document). For example, `<span class=title></span>` would generate span containing the title. * `footerTemplate` string (optional) - HTML template for the print footer. Should use the same format as the `headerTemplate`. * `preferCSSPageSize` boolean (optional) - Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size. Returns `Promise<Buffer>` - Resolves with the generated PDF data. Prints the window's web page as PDF. The `landscape` will be ignored if `@page` CSS at-rule is used in the web page. An example of `webContents.printToPDF`: ```javascript const { BrowserWindow } = require('electron') const fs = require('fs') const path = require('path') const os = require('os') const win = new BrowserWindow() win.loadURL('http://github.com') win.webContents.on('did-finish-load', () => { // Use default printing options const pdfPath = path.join(os.homedir(), 'Desktop', 'temp.pdf') win.webContents.printToPDF({}).then(data => { fs.writeFile(pdfPath, data, (error) => { if (error) throw error console.log(`Wrote PDF successfully to ${pdfPath}`) }) }).catch(error => { console.log(`Failed to write PDF to ${pdfPath}: `, error) }) }) ``` See [Page.printToPdf](https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF) for more information. #### `contents.addWorkSpace(path)` * `path` string Adds the specified path to DevTools workspace. Must be used after DevTools creation: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.webContents.on('devtools-opened', () => { win.webContents.addWorkSpace(__dirname) }) ``` #### `contents.removeWorkSpace(path)` * `path` string Removes the specified path from DevTools workspace. #### `contents.setDevToolsWebContents(devToolsWebContents)` * `devToolsWebContents` WebContents Uses the `devToolsWebContents` as the target `WebContents` to show devtools. The `devToolsWebContents` must not have done any navigation, and it should not be used for other purposes after the call. By default Electron manages the devtools by creating an internal `WebContents` with native view, which developers have very limited control of. With the `setDevToolsWebContents` method, developers can use any `WebContents` to show the devtools in it, including `BrowserWindow`, `BrowserView` and `<webview>` tag. Note that closing the devtools does not destroy the `devToolsWebContents`, it is caller's responsibility to destroy `devToolsWebContents`. An example of showing devtools in a `<webview>` tag: ```html <html> <head> <style type="text/css"> * { margin: 0; } #browser { height: 70%; } #devtools { height: 30%; } </style> </head> <body> <webview id="browser" src="https://github.com"></webview> <webview id="devtools" src="about:blank"></webview> <script> const { ipcRenderer } = require('electron') const emittedOnce = (element, eventName) => new Promise(resolve => { element.addEventListener(eventName, event => resolve(event), { once: true }) }) const browserView = document.getElementById('browser') const devtoolsView = document.getElementById('devtools') const browserReady = emittedOnce(browserView, 'dom-ready') const devtoolsReady = emittedOnce(devtoolsView, 'dom-ready') Promise.all([browserReady, devtoolsReady]).then(() => { const targetId = browserView.getWebContentsId() const devtoolsId = devtoolsView.getWebContentsId() ipcRenderer.send('open-devtools', targetId, devtoolsId) }) </script> </body> </html> ``` ```js // Main process const { ipcMain, webContents } = require('electron') ipcMain.on('open-devtools', (event, targetContentsId, devtoolsContentsId) => { const target = webContents.fromId(targetContentsId) const devtools = webContents.fromId(devtoolsContentsId) target.setDevToolsWebContents(devtools) target.openDevTools() }) ``` An example of showing devtools in a `BrowserWindow`: ```js const { app, BrowserWindow } = require('electron') let win = null let devtools = null app.whenReady().then(() => { win = new BrowserWindow() devtools = new BrowserWindow() win.loadURL('https://github.com') win.webContents.setDevToolsWebContents(devtools.webContents) win.webContents.openDevTools({ mode: 'detach' }) }) ``` #### `contents.openDevTools([options])` * `options` Object (optional) * `mode` string - Opens the devtools with specified dock state, can be `left`, `right`, `bottom`, `undocked`, `detach`. Defaults to last used dock state. In `undocked` mode it's possible to dock back. In `detach` mode it's not. * `activate` boolean (optional) - Whether to bring the opened devtools window to the foreground. The default is `true`. Opens the devtools. When `contents` is a `<webview>` tag, the `mode` would be `detach` by default, explicitly passing an empty `mode` can force using last used dock state. #### `contents.closeDevTools()` Closes the devtools. #### `contents.isDevToolsOpened()` Returns `boolean` - Whether the devtools is opened. #### `contents.isDevToolsFocused()` Returns `boolean` - Whether the devtools view is focused . #### `contents.toggleDevTools()` Toggles the developer tools. #### `contents.inspectElement(x, y)` * `x` Integer * `y` Integer Starts inspecting element at position (`x`, `y`). #### `contents.inspectSharedWorker()` Opens the developer tools for the shared worker context. #### `contents.inspectSharedWorkerById(workerId)` * `workerId` string Inspects the shared worker based on its ID. #### `contents.getAllSharedWorkers()` Returns [`SharedWorkerInfo[]`](structures/shared-worker-info.md) - Information about all Shared Workers. #### `contents.inspectServiceWorker()` Opens the developer tools for the service worker context. #### `contents.send(channel, ...args)` * `channel` string * `...args` any[] Send an asynchronous message to the renderer process via `channel`, along with arguments. Arguments will be serialized with the [Structured Clone Algorithm][SCA], just like [`postMessage`][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. > **NOTE**: Sending non-standard JavaScript types such as DOM objects or > special Electron objects will throw an exception. The renderer process can handle the message by listening to `channel` with the [`ipcRenderer`](ipc-renderer.md) module. An example of sending messages from the main process to the renderer process: ```javascript // In the main process. const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL(`file://${__dirname}/index.html`) win.webContents.on('did-finish-load', () => { win.webContents.send('ping', 'whoooooooh!') }) }) ``` ```html <!-- index.html --> <html> <body> <script> require('electron').ipcRenderer.on('ping', (event, message) => { console.log(message) // Prints 'whoooooooh!' }) </script> </body> </html> ``` #### `contents.sendToFrame(frameId, channel, ...args)` * `frameId` Integer | [number, number] - the ID of the frame to send to, or a pair of `[processId, frameId]` if the frame is in a different process to the main frame. * `channel` string * `...args` any[] Send an asynchronous message to a specific frame in a renderer process via `channel`, along with arguments. Arguments will be serialized with the [Structured Clone Algorithm][SCA], just like [`postMessage`][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. > **NOTE:** Sending non-standard JavaScript types such as DOM objects or > special Electron objects will throw an exception. The renderer process can handle the message by listening to `channel` with the [`ipcRenderer`](ipc-renderer.md) module. If you want to get the `frameId` of a given renderer context you should use the `webFrame.routingId` value. E.g. ```js // In a renderer process console.log('My frameId is:', require('electron').webFrame.routingId) ``` You can also read `frameId` from all incoming IPC messages in the main process. ```js // In the main process ipcMain.on('ping', (event) => { console.info('Message came from frameId:', event.frameId) }) ``` #### `contents.postMessage(channel, message, [transfer])` * `channel` string * `message` any * `transfer` MessagePortMain[] (optional) Send a message to the renderer process, optionally transferring ownership of zero or more [`MessagePortMain`][] objects. The transferred `MessagePortMain` objects will be available in the renderer process by accessing the `ports` property of the emitted event. When they arrive in the renderer, they will be native DOM `MessagePort` objects. For example: ```js // Main process const { port1, port2 } = new MessageChannelMain() webContents.postMessage('port', { message: 'hello' }, [port1]) // Renderer process ipcRenderer.on('port', (e, msg) => { const [port] = e.ports // ... }) ``` #### `contents.enableDeviceEmulation(parameters)` * `parameters` Object * `screenPosition` string - Specify the screen type to emulate (default: `desktop`): * `desktop` - Desktop screen type. * `mobile` - Mobile screen type. * `screenSize` [Size](structures/size.md) - Set the emulated screen size (screenPosition == mobile). * `viewPosition` [Point](structures/point.md) - Position the view on the screen (screenPosition == mobile) (default: `{ x: 0, y: 0 }`). * `deviceScaleFactor` Integer - Set the device scale factor (if zero defaults to original device scale factor) (default: `0`). * `viewSize` [Size](structures/size.md) - Set the emulated view size (empty means no override) * `scale` Float - Scale of emulated view inside available space (not in fit to view mode) (default: `1`). Enable device emulation with the given parameters. #### `contents.disableDeviceEmulation()` Disable device emulation enabled by `webContents.enableDeviceEmulation`. #### `contents.sendInputEvent(inputEvent)` * `inputEvent` [MouseInputEvent](structures/mouse-input-event.md) | [MouseWheelInputEvent](structures/mouse-wheel-input-event.md) | [KeyboardInputEvent](structures/keyboard-input-event.md) Sends an input `event` to the page. **Note:** The [`BrowserWindow`](browser-window.md) containing the contents needs to be focused for `sendInputEvent()` to work. #### `contents.beginFrameSubscription([onlyDirty ,]callback)` * `onlyDirty` boolean (optional) - Defaults to `false`. * `callback` Function * `image` [NativeImage](native-image.md) * `dirtyRect` [Rectangle](structures/rectangle.md) Begin subscribing for presentation events and captured frames, the `callback` will be called with `callback(image, dirtyRect)` when there is a presentation event. The `image` is an instance of [NativeImage](native-image.md) that stores the captured frame. The `dirtyRect` is an object with `x, y, width, height` properties that describes which part of the page was repainted. If `onlyDirty` is set to `true`, `image` will only contain the repainted area. `onlyDirty` defaults to `false`. #### `contents.endFrameSubscription()` End subscribing for frame presentation events. #### `contents.startDrag(item)` * `item` Object * `file` string - The path to the file being dragged. * `files` string[] (optional) - The paths to the files being dragged. (`files` will override `file` field) * `icon` [NativeImage](native-image.md) | string - The image must be non-empty on macOS. Sets the `item` as dragging item for current drag-drop operation, `file` is the absolute path of the file to be dragged, and `icon` is the image showing under the cursor when dragging. #### `contents.savePage(fullPath, saveType)` * `fullPath` string - The absolute file path. * `saveType` string - Specify the save type. * `HTMLOnly` - Save only the HTML of the page. * `HTMLComplete` - Save complete-html page. * `MHTML` - Save complete-html page as MHTML. Returns `Promise<void>` - resolves if the page is saved. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.loadURL('https://github.com') win.webContents.on('did-finish-load', async () => { win.webContents.savePage('/tmp/test.html', 'HTMLComplete').then(() => { console.log('Page was saved successfully.') }).catch(err => { console.log(err) }) }) ``` #### `contents.showDefinitionForSelection()` _macOS_ Shows pop-up dictionary that searches the selected word on the page. #### `contents.isOffscreen()` Returns `boolean` - Indicates whether *offscreen rendering* is enabled. #### `contents.startPainting()` If *offscreen rendering* is enabled and not painting, start painting. #### `contents.stopPainting()` If *offscreen rendering* is enabled and painting, stop painting. #### `contents.isPainting()` Returns `boolean` - If *offscreen rendering* is enabled returns whether it is currently painting. #### `contents.setFrameRate(fps)` * `fps` Integer If *offscreen rendering* is enabled sets the frame rate to the specified number. Only values between 1 and 240 are accepted. #### `contents.getFrameRate()` Returns `Integer` - If *offscreen rendering* is enabled returns the current frame rate. #### `contents.invalidate()` Schedules a full repaint of the window this web contents is in. If *offscreen rendering* is enabled invalidates the frame and generates a new one through the `'paint'` event. #### `contents.getWebRTCIPHandlingPolicy()` Returns `string` - Returns the WebRTC IP Handling Policy. #### `contents.setWebRTCIPHandlingPolicy(policy)` * `policy` string - Specify the WebRTC IP Handling Policy. * `default` - Exposes user's public and local IPs. This is the default behavior. When this policy is used, WebRTC has the right to enumerate all interfaces and bind them to discover public interfaces. * `default_public_interface_only` - Exposes user's public IP, but does not expose user's local IP. When this policy is used, WebRTC should only use the default route used by http. This doesn't expose any local addresses. * `default_public_and_private_interfaces` - Exposes user's public and local IPs. When this policy is used, WebRTC should only use the default route used by http. This also exposes the associated default private address. Default route is the route chosen by the OS on a multi-homed endpoint. * `disable_non_proxied_udp` - Does not expose public or local IPs. When this policy is used, WebRTC should only use TCP to contact peers or servers unless the proxy server supports UDP. Setting the WebRTC IP handling policy allows you to control which IPs are exposed via WebRTC. See [BrowserLeaks](https://browserleaks.com/webrtc) for more details. #### `contents.getMediaSourceId(requestWebContents)` * `requestWebContents` WebContents - Web contents that the id will be registered to. Returns `string` - The identifier of a WebContents stream. This identifier can be used with `navigator.mediaDevices.getUserMedia` using a `chromeMediaSource` of `tab`. The identifier is restricted to the web contents that it is registered to and is only valid for 10 seconds. #### `contents.getOSProcessId()` Returns `Integer` - The operating system `pid` of the associated renderer process. #### `contents.getProcessId()` Returns `Integer` - The Chromium internal `pid` of the associated renderer. Can be compared to the `frameProcessId` passed by frame specific navigation events (e.g. `did-frame-navigate`) #### `contents.takeHeapSnapshot(filePath)` * `filePath` string - Path to the output file. Returns `Promise<void>` - Indicates whether the snapshot has been created successfully. Takes a V8 heap snapshot and saves it to `filePath`. #### `contents.getBackgroundThrottling()` Returns `boolean` - whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.setBackgroundThrottling(allowed)` * `allowed` boolean Controls whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.getType()` Returns `string` - the type of the webContent. Can be `backgroundPage`, `window`, `browserView`, `remote`, `webview` or `offscreen`. #### `contents.setImageAnimationPolicy(policy)` * `policy` string - Can be `animate`, `animateOnce` or `noAnimation`. Sets the image animation policy for this webContents. The policy only affects _new_ images, existing images that are currently being animated are unaffected. This is a known limitation in Chromium, you can force image animation to be recalculated with `img.src = img.src` which will result in no network traffic but will update the animation policy. This corresponds to the [animationPolicy][] accessibility feature in Chromium. [animationPolicy]: https://developer.chrome.com/docs/extensions/reference/accessibilityFeatures/#property-animationPolicy ### Instance Properties #### `contents.ipc` _Readonly_ An [`IpcMain`](ipc-main.md) scoped to just IPC messages sent from this WebContents. IPC messages sent with `ipcRenderer.send`, `ipcRenderer.sendSync` or `ipcRenderer.postMessage` will be delivered in the following order: 1. `contents.on('ipc-message')` 2. `contents.mainFrame.on(channel)` 3. `contents.ipc.on(channel)` 4. `ipcMain.on(channel)` Handlers registered with `invoke` will be checked in the following order. The first one that is defined will be called, the rest will be ignored. 1. `contents.mainFrame.handle(channel)` 2. `contents.handle(channel)` 3. `ipcMain.handle(channel)` A handler or event listener registered on the WebContents will receive IPC messages sent from any frame, including child frames. In most cases, only the main frame can send IPC messages. However, if the `nodeIntegrationInSubFrames` option is enabled, it is possible for child frames to send IPC messages also. In that case, handlers should check the `senderFrame` property of the IPC event to ensure that the message is coming from the expected frame. Alternatively, register handlers on the appropriate frame directly using the [`WebFrameMain.ipc`](web-frame-main.md#frameipc-readonly) interface. #### `contents.audioMuted` A `boolean` property that determines whether this page is muted. #### `contents.userAgent` A `string` property that determines the user agent for this web page. #### `contents.zoomLevel` A `number` property that determines the zoom level for this web contents. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`. #### `contents.zoomFactor` A `number` property that determines the zoom factor for this web contents. The zoom factor is the zoom percent divided by 100, so 300% = 3.0. #### `contents.frameRate` An `Integer` property that sets the frame rate of the web contents to the specified number. Only values between 1 and 240 are accepted. Only applicable if *offscreen rendering* is enabled. #### `contents.id` _Readonly_ A `Integer` representing the unique ID of this WebContents. Each ID is unique among all `WebContents` instances of the entire Electron application. #### `contents.session` _Readonly_ A [`Session`](session.md) used by this webContents. #### `contents.hostWebContents` _Readonly_ A [`WebContents`](web-contents.md) instance that might own this `WebContents`. #### `contents.devToolsWebContents` _Readonly_ A `WebContents | null` property that represents the of DevTools `WebContents` associated with a given `WebContents`. **Note:** Users should never store this object because it may become `null` when the DevTools has been closed. #### `contents.debugger` _Readonly_ A [`Debugger`](debugger.md) instance for this webContents. #### `contents.backgroundThrottling` A `boolean` property that determines whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.mainFrame` _Readonly_ A [`WebFrameMain`](web-frame-main.md) property that represents the top frame of the page's frame hierarchy. [keyboardevent]: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter [SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm [`postMessage`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
closed
electron/electron
https://github.com/electron/electron
34,129
[Bug]: WCO on Windows occludes dev tools
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4.1 ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Using WCO and frameless windows on Windows, the WCO does not occlude the top right corner of the dev tools when they are placed on the right side. ### Actual Behavior Using WCO and frameless windows on Windows, the WCO occludes the top right corner of the dev tools when they are placed on the right side. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34129
https://github.com/electron/electron/pull/35209
eab7ab2c47c0750359a247450d9c7a41642b3dd1
4d54cadb281cceb9cf8de91773047ea2cc41da5f
2022-05-06T21:42:03Z
c++
2022-08-11T13:16:12Z
shell/browser/api/electron_api_web_contents.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_web_contents.h" #include <limits> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/containers/id_map.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/no_destructor.h" #include "base/strings/utf_string_conversions.h" #include "base/task/current_thread.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/views/eye_dropper/eye_dropper.h" #include "chrome/common/pref_names.h" #include "components/embedder_support/user_agent_utils.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/security_state/content/content_utils.h" #include "components/security_state/core/security_state.h" #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck #include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/context_menu_params.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/desktop_streams_registry.h" #include "content/public/browser/download_request_utils.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/service_worker_context.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/referrer_type_converters.h" #include "content/public/common/webplugininfo.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/arguments.h" #include "gin/data_object_builder.h" #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/system/platform_handle.h" #include "ppapi/buildflags/buildflags.h" #include "printing/buildflags/buildflags.h" #include "printing/print_job_constants.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "shell/browser/api/electron_api_browser_window.h" #include "shell/browser/api/electron_api_debugger.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/api/electron_api_web_frame_main.h" #include "shell/browser/api/message_port.h" #include "shell/browser/browser.h" #include "shell/browser/child_web_contents_tracker.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_javascript_dialog_manager.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/file_select_helper.h" #include "shell/browser/native_window.h" #include "shell/browser/session_preferences.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_contents_zoom_controller.h" #include "shell/browser/web_view_guest_delegate.h" #include "shell/browser/web_view_manager.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/color_util.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/base_converter.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/content_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/net_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/language_util.h" #include "shell/common/mouse_util.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "shell/common/v8_value_serializer.h" #include "storage/browser/file_system/isolated_context.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "third_party/blink/public/mojom/frame/find_in_page.mojom.h" #include "third_party/blink/public/mojom/frame/fullscreen.mojom.h" #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" #include "third_party/blink/public/mojom/renderer_preferences.mojom.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/display/screen.h" #include "ui/events/base_event_utils.h" #if BUILDFLAG(ENABLE_OSR) #include "shell/browser/osr/osr_render_widget_host_view.h" #include "shell/browser/osr/osr_web_contents_view.h" #endif #if !BUILDFLAG(IS_MAC) #include "ui/aura/window.h" #else #include "ui/base/cocoa/defaults_utils.h" #endif #if BUILDFLAG(IS_LINUX) #include "ui/linux/linux_ui.h" #endif #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) #include "ui/gfx/font_render_params.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/script_executor.h" #include "extensions/browser/view_type_utils.h" #include "extensions/common/mojom/view_type.mojom.h" #include "shell/browser/extensions/electron_extension_web_contents_observer.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "chrome/browser/printing/print_view_manager_base.h" #include "components/printing/browser/print_manager_utils.h" #include "components/printing/browser/print_to_pdf/pdf_print_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" // nogncheck #include "printing/page_range.h" #include "shell/browser/printing/print_view_manager_electron.h" #if BUILDFLAG(IS_WIN) #include "printing/backend/win_helper.h" #endif #endif #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h" #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck #include "shell/browser/electron_pdf_web_contents_helper_client.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #endif #ifndef MAS_BUILD #include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck #endif namespace gin { #if BUILDFLAG(ENABLE_PRINTING) template <> struct Converter<printing::mojom::MarginType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::MarginType* out) { std::string type; if (ConvertFromV8(isolate, val, &type)) { if (type == "default") { *out = printing::mojom::MarginType::kDefaultMargins; return true; } if (type == "none") { *out = printing::mojom::MarginType::kNoMargins; return true; } if (type == "printableArea") { *out = printing::mojom::MarginType::kPrintableAreaMargins; return true; } if (type == "custom") { *out = printing::mojom::MarginType::kCustomMargins; return true; } } return false; } }; template <> struct Converter<printing::mojom::DuplexMode> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::DuplexMode* out) { std::string mode; if (ConvertFromV8(isolate, val, &mode)) { if (mode == "simplex") { *out = printing::mojom::DuplexMode::kSimplex; return true; } if (mode == "longEdge") { *out = printing::mojom::DuplexMode::kLongEdge; return true; } if (mode == "shortEdge") { *out = printing::mojom::DuplexMode::kShortEdge; return true; } } return false; } }; #endif template <> struct Converter<WindowOpenDisposition> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, WindowOpenDisposition val) { std::string disposition = "other"; switch (val) { case WindowOpenDisposition::CURRENT_TAB: disposition = "default"; break; case WindowOpenDisposition::NEW_FOREGROUND_TAB: disposition = "foreground-tab"; break; case WindowOpenDisposition::NEW_BACKGROUND_TAB: disposition = "background-tab"; break; case WindowOpenDisposition::NEW_POPUP: case WindowOpenDisposition::NEW_WINDOW: disposition = "new-window"; break; case WindowOpenDisposition::SAVE_TO_DISK: disposition = "save-to-disk"; break; default: break; } return gin::ConvertToV8(isolate, disposition); } }; template <> struct Converter<content::SavePageType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, content::SavePageType* out) { std::string save_type; if (!ConvertFromV8(isolate, val, &save_type)) return false; save_type = base::ToLowerASCII(save_type); if (save_type == "htmlonly") { *out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML; } else if (save_type == "htmlcomplete") { *out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML; } else if (save_type == "mhtml") { *out = content::SAVE_PAGE_TYPE_AS_MHTML; } else { return false; } return true; } }; template <> struct Converter<electron::api::WebContents::Type> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, electron::api::WebContents::Type val) { using Type = electron::api::WebContents::Type; std::string type; switch (val) { case Type::kBackgroundPage: type = "backgroundPage"; break; case Type::kBrowserWindow: type = "window"; break; case Type::kBrowserView: type = "browserView"; break; case Type::kRemote: type = "remote"; break; case Type::kWebView: type = "webview"; break; case Type::kOffScreen: type = "offscreen"; break; default: break; } return gin::ConvertToV8(isolate, type); } static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, electron::api::WebContents::Type* out) { using Type = electron::api::WebContents::Type; std::string type; if (!ConvertFromV8(isolate, val, &type)) return false; if (type == "backgroundPage") { *out = Type::kBackgroundPage; } else if (type == "browserView") { *out = Type::kBrowserView; } else if (type == "webview") { *out = Type::kWebView; #if BUILDFLAG(ENABLE_OSR) } else if (type == "offscreen") { *out = Type::kOffScreen; #endif } else { return false; } return true; } }; template <> struct Converter<scoped_refptr<content::DevToolsAgentHost>> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const scoped_refptr<content::DevToolsAgentHost>& val) { gin_helper::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("id", val->GetId()); dict.Set("url", val->GetURL().spec()); return dict.GetHandle(); } }; } // namespace gin namespace electron::api { namespace { base::IDMap<WebContents*>& GetAllWebContents() { static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents; return *s_all_web_contents; } // Called when CapturePage is done. void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); } absl::optional<base::TimeDelta> GetCursorBlinkInterval() { #if BUILDFLAG(IS_MAC) absl::optional<base::TimeDelta> system_value( ui::TextInsertionCaretBlinkPeriodFromDefaults()); if (system_value) return *system_value; #elif BUILDFLAG(IS_LINUX) if (auto* linux_ui = ui::LinuxUi::instance()) return linux_ui->GetCursorBlinkInterval(); #elif BUILDFLAG(IS_WIN) const auto system_msec = ::GetCaretBlinkTime(); if (system_msec != 0) { return (system_msec == INFINITE) ? base::TimeDelta() : base::Milliseconds(system_msec); } #endif return absl::nullopt; } #if BUILDFLAG(ENABLE_PRINTING) // This will return false if no printer with the provided device_name can be // found on the network. We need to check this because Chromium does not do // sanity checking of device_name validity and so will crash on invalid names. bool IsDeviceNameValid(const std::u16string& device_name) { #if BUILDFLAG(IS_MAC) base::ScopedCFTypeRef<CFStringRef> new_printer_id( base::SysUTF16ToCFStringRef(device_name)); PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get()); bool printer_exists = new_printer != nullptr; PMRelease(new_printer); return printer_exists; #else scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name)); #endif } // This function returns a validated device name. // If the user passed one to webContents.print(), we check that it's valid and // return it or fail if the network doesn't recognize it. If the user didn't // pass a device name, we first try to return the system default printer. If one // isn't set, then pull all the printers and use the first one or fail if none // exist. std::pair<std::string, std::u16string> GetDeviceNameToUse( const std::u16string& device_name) { #if BUILDFLAG(IS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ThreadRestrictions::ScopedAllowIO allow_io; #endif if (!device_name.empty()) { if (!IsDeviceNameValid(device_name)) return std::make_pair("Invalid deviceName provided", std::u16string()); return std::make_pair(std::string(), device_name); } scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); std::string printer_name; printing::mojom::ResultCode code = print_backend->GetDefaultPrinterName(printer_name); // We don't want to return if this fails since some devices won't have a // default printer. if (code != printing::mojom::ResultCode::kSuccess) LOG(ERROR) << "Failed to get default printer name"; if (printer_name.empty()) { printing::PrinterList printers; if (print_backend->EnumeratePrinters(printers) != printing::mojom::ResultCode::kSuccess) return std::make_pair("Failed to enumerate printers", std::u16string()); if (printers.empty()) return std::make_pair("No printers available on the network", std::u16string()); printer_name = printers.front().printer_name; } return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name)); } // Copied from // chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54 scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() { // USER_VISIBLE because the result is displayed in the print preview dialog. #if !BUILDFLAG(IS_WIN) static constexpr base::TaskTraits kTraits = { base::MayBlock(), base::TaskPriority::USER_VISIBLE}; #endif #if defined(USE_CUPS) // CUPS is thread safe. return base::ThreadPool::CreateTaskRunner(kTraits); #elif BUILDFLAG(IS_WIN) // Windows drivers are likely not thread-safe and need to be accessed on the // UI thread. return content::GetUIThreadTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); #else // Be conservative on unsupported platforms. return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits); #endif } #endif struct UserDataLink : public base::SupportsUserData::Data { explicit UserDataLink(base::WeakPtr<WebContents> contents) : web_contents(contents) {} base::WeakPtr<WebContents> web_contents; }; const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey; const char kRootName[] = "<root>"; struct FileSystem { FileSystem() = default; FileSystem(const std::string& type, const std::string& file_system_name, const std::string& root_url, const std::string& file_system_path) : type(type), file_system_name(file_system_name), root_url(root_url), file_system_path(file_system_path) {} std::string type; std::string file_system_name; std::string root_url; std::string file_system_path; }; std::string RegisterFileSystem(content::WebContents* web_contents, const base::FilePath& path) { auto* isolated_context = storage::IsolatedContext::GetInstance(); std::string root_name(kRootName); storage::IsolatedContext::ScopedFSHandle file_system = isolated_context->RegisterFileSystemForPath( storage::kFileSystemTypeLocal, std::string(), path, &root_name); content::ChildProcessSecurityPolicy* policy = content::ChildProcessSecurityPolicy::GetInstance(); content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost(); int renderer_id = render_view_host->GetProcess()->GetID(); policy->GrantReadFileSystem(renderer_id, file_system.id()); policy->GrantWriteFileSystem(renderer_id, file_system.id()); policy->GrantCreateFileForFileSystem(renderer_id, file_system.id()); policy->GrantDeleteFromFileSystem(renderer_id, file_system.id()); if (!policy->CanReadFile(renderer_id, path)) policy->GrantReadFile(renderer_id, path); return file_system.id(); } FileSystem CreateFileSystemStruct(content::WebContents* web_contents, const std::string& file_system_id, const std::string& file_system_path, const std::string& type) { const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL(); std::string file_system_name = storage::GetIsolatedFileSystemName(origin, file_system_id); std::string root_url = storage::GetIsolatedFileSystemRootURIString( origin, file_system_id, kRootName); return FileSystem(type, file_system_name, root_url, file_system_path); } base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) { base::Value::Dict value; value.Set("type", file_system.type); value.Set("fileSystemName", file_system.file_system_name); value.Set("rootURL", file_system.root_url); value.Set("fileSystemPath", file_system.file_system_path); return value; } void WriteToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::WriteFile(path, content.data(), content.size()); } void AppendToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::AppendToFile(path, content); } PrefService* GetPrefService(content::WebContents* web_contents) { auto* context = web_contents->GetBrowserContext(); return static_cast<electron::ElectronBrowserContext*>(context)->prefs(); } std::map<std::string, std::string> GetAddedFileSystemPaths( content::WebContents* web_contents) { auto* pref_service = GetPrefService(web_contents); const base::Value* file_system_paths_value = pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; if (file_system_paths_value) { const base::DictionaryValue* file_system_paths_dict; file_system_paths_value->GetAsDictionary(&file_system_paths_dict); for (auto it : file_system_paths_dict->DictItems()) { std::string type = it.second.is_string() ? it.second.GetString() : std::string(); result[it.first] = type; } } return result; } bool IsDevToolsFileSystemAdded(content::WebContents* web_contents, const std::string& file_system_path) { auto file_system_paths = GetAddedFileSystemPaths(web_contents); return file_system_paths.find(file_system_path) != file_system_paths.end(); } void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } } // namespace #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) { switch (view_type) { case extensions::mojom::ViewType::kExtensionBackgroundPage: return WebContents::Type::kBackgroundPage; case extensions::mojom::ViewType::kAppWindow: case extensions::mojom::ViewType::kComponent: case extensions::mojom::ViewType::kExtensionDialog: case extensions::mojom::ViewType::kExtensionPopup: case extensions::mojom::ViewType::kBackgroundContents: case extensions::mojom::ViewType::kExtensionGuest: case extensions::mojom::ViewType::kTabContents: case extensions::mojom::ViewType::kOffscreenDocument: case extensions::mojom::ViewType::kInvalid: return WebContents::Type::kRemote; } } #endif WebContents::WebContents(v8::Isolate* isolate, content::WebContents* web_contents) : content::WebContentsObserver(web_contents), type_(Type::kRemote), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // WebContents created by extension host will have valid ViewType set. extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents); if (view_type != extensions::mojom::ViewType::kInvalid) { InitWithExtensionView(isolate, web_contents, view_type); } extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents); #endif auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); SetUserAgent(GetBrowserContext()->GetUserAgent()); web_contents->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) : content::WebContentsObserver(web_contents.get()), type_(type), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { DCHECK(type != Type::kRemote) << "Can't take ownership of a remote WebContents"; auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); InitWithSessionAndOptions(isolate, std::move(web_contents), session, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options) : id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { // Read options. options.Get("backgroundThrottling", &background_throttling_); // Get type options.Get("type", &type_); #if BUILDFLAG(ENABLE_OSR) bool b = false; if (options.Get(options::kOffscreen, &b) && b) type_ = Type::kOffScreen; #endif // Init embedder earlier options.Get("embedder", &embedder_); // Whether to enable DevTools. options.Get("devTools", &enable_devtools_); // BrowserViews are not attached to a window initially so they should start // off as hidden. This is also important for compositor recycling. See: // https://github.com/electron/electron/pull/21372 bool initially_shown = type_ != Type::kBrowserView; options.Get(options::kShow, &initially_shown); // Obtain the session. std::string partition; gin::Handle<api::Session> session; if (options.Get("session", &session) && !session.IsEmpty()) { } else if (options.Get("partition", &partition)) { session = Session::FromPartition(isolate, partition); } else { // Use the default session if not specified. session = Session::FromPartition(isolate, ""); } session_.Reset(isolate, session.ToV8()); std::unique_ptr<content::WebContents> web_contents; if (IsGuest()) { scoped_refptr<content::SiteInstance> site_instance = content::SiteInstance::CreateForURL(session->browser_context(), GURL("chrome-guest://fake-host")); content::WebContents::CreateParams params(session->browser_context(), site_instance); guest_delegate_ = std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this); params.guest_delegate = guest_delegate_.get(); #if BUILDFLAG(ENABLE_OSR) if (embedder_ && embedder_->IsOffScreen()) { auto* view = new OffScreenWebContentsView( false, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); } else { #endif web_contents = content::WebContents::Create(params); #if BUILDFLAG(ENABLE_OSR) } } else if (IsOffScreen()) { // webPreferences does not have a transparent option, so if the window needs // to be transparent, that will be set at electron_api_browser_window.cc#L57 // and we then need to pull it back out and check it here. std::string background_color; options.GetHidden(options::kBackgroundColor, &background_color); bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT; content::WebContents::CreateParams params(session->browser_context()); auto* view = new OffScreenWebContentsView( transparent, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); #endif } else { content::WebContents::CreateParams params(session->browser_context()); params.initially_hidden = !initially_shown; web_contents = content::WebContents::Create(params); } InitWithSessionAndOptions(isolate, std::move(web_contents), session, options); } void WebContents::InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options) { WebContentsZoomController::CreateForWebContents(web_contents); zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents); double zoom_factor; if (options.Get(options::kZoomFactor, &zoom_factor)) zoom_controller_->SetDefaultZoomFactor(zoom_factor); } void WebContents::InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> owned_web_contents, gin::Handle<api::Session> session, const gin_helper::Dictionary& options) { Observe(owned_web_contents.get()); InitWithWebContents(std::move(owned_web_contents), session->browser_context(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); auto* prefs = web_contents()->GetMutableRendererPrefs(); // Collect preferred languages from OS and browser process. accept_languages // effects HTTP header, navigator.languages, and CJK fallback font selection. // // Note that an application locale set to the browser process might be // different with the one set to the preference list. // (e.g. overridden with --lang) std::string accept_languages = g_browser_process->GetApplicationLocale() + ","; for (auto const& language : electron::GetPreferredLanguages()) { if (language == g_browser_process->GetApplicationLocale()) continue; accept_languages += language + ","; } accept_languages.pop_back(); prefs->accept_languages = accept_languages; #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) // Update font settings. static const gfx::FontRenderParams params( gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr)); prefs->should_antialias_text = params.antialiasing; prefs->use_subpixel_positioning = params.subpixel_positioning; prefs->hinting = params.hinting; prefs->use_autohinter = params.autohinter; prefs->use_bitmaps = params.use_bitmaps; prefs->subpixel_rendering = params.subpixel_rendering; #endif // Honor the system's cursor blink rate settings if (auto interval = GetCursorBlinkInterval()) prefs->caret_blink_interval = *interval; // Save the preferences in C++. // If there's already a WebContentsPreferences object, we created it as part // of the webContents.setWindowOpenHandler path, so don't overwrite it. if (!WebContentsPreferences::From(web_contents())) { new WebContentsPreferences(web_contents(), options); } // Trigger re-calculation of webkit prefs. web_contents()->NotifyPreferencesChanged(); WebContentsPermissionHelper::CreateForWebContents(web_contents()); InitZoomController(web_contents(), options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents()); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents()); #endif AutofillDriverFactory::CreateForWebContents(web_contents()); SetUserAgent(GetBrowserContext()->GetUserAgent()); if (IsGuest()) { NativeWindow* owner_window = nullptr; if (embedder_) { // New WebContents's owner_window is the embedder's owner_window. auto* relay = NativeWindowRelay::FromWebContents(embedder_->web_contents()); if (relay) owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); } web_contents()->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void WebContents::InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::mojom::ViewType view_type) { // Must reassign type prior to calling `Init`. type_ = GetTypeFromViewType(view_type); if (type_ == Type::kRemote) return; if (type_ == Type::kBackgroundPage) // non-background-page WebContents are retained by other classes. We need // to pin here to prevent background-page WebContents from being GC'd. // The background page api::WebContents will live until the underlying // content::WebContents is destroyed. Pin(isolate); // Allow toggling DevTools for background pages Observe(web_contents); InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents), GetBrowserContext(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); } #endif void WebContents::InitWithWebContents( std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest) { browser_context_ = browser_context; web_contents->SetDelegate(this); #if BUILDFLAG(ENABLE_PRINTING) PrintViewManagerElectron::CreateForWebContents(web_contents.get()); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) pdf::PDFWebContentsHelper::CreateForWebContentsWithClient( web_contents.get(), std::make_unique<ElectronPDFWebContentsHelperClient>()); #endif // Determine whether the WebContents is offscreen. auto* web_preferences = WebContentsPreferences::From(web_contents.get()); offscreen_ = web_preferences && web_preferences->IsOffscreen(); // Create InspectableWebContents. inspectable_web_contents_ = std::make_unique<InspectableWebContents>( std::move(web_contents), browser_context->prefs(), is_guest); inspectable_web_contents_->SetDelegate(this); } WebContents::~WebContents() { if (!inspectable_web_contents_) { WebContentsDestroyed(); return; } inspectable_web_contents_->GetView()->SetDelegate(nullptr); // This event is only for internal use, which is emitted when WebContents is // being destroyed. Emit("will-destroy"); // For guest view based on OOPIF, the WebContents is released by the embedder // frame, and we need to clear the reference to the memory. bool not_owned_by_this = IsGuest() && attached_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // And background pages are owned by extensions::ExtensionHost. if (type_ == Type::kBackgroundPage) not_owned_by_this = true; #endif if (not_owned_by_this) { inspectable_web_contents_->ReleaseWebContents(); WebContentsDestroyed(); } // InspectableWebContents will be automatically destroyed. } void WebContents::DeleteThisIfAlive() { // It is possible that the FirstWeakCallback has been called but the // SecondWeakCallback has not, in this case the garbage collection of // WebContents has already started and we should not |delete this|. // Calling |GetWrapper| can detect this corner case. auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; delete this; } void WebContents::Destroy() { // The content::WebContents should be destroyed asynchronously when possible // as user may choose to destroy WebContents during an event of it. if (Browser::Get()->is_shutting_down() || IsGuest()) { DeleteThisIfAlive(); } else { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce( [](base::WeakPtr<WebContents> contents) { if (contents) contents->DeleteThisIfAlive(); }, GetWeakPtr())); } } bool WebContents::DidAddMessageToConsole( content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) { return Emit("console-message", static_cast<int32_t>(level), message, line_no, source_id); } void WebContents::OnCreateWindow( const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const std::string& features, const scoped_refptr<network::ResourceRequestBody>& body) { Emit("-new-window", target_url, frame_name, disposition, features, referrer, body); } void WebContents::WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) { ChildWebContentsTracker::CreateForWebContents(new_contents); auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents); tracker->url = params.target_url; tracker->frame_name = params.frame_name; tracker->referrer = params.referrer.To<content::Referrer>(); tracker->raw_features = params.raw_features; tracker->body = params.body; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary dict; gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate), &dict); pending_child_web_preferences_.Reset(); // Associate the preferences passed in via `setWindowOpenHandler` with the // content::WebContents that was just created for the child window. These // preferences will be picked up by the RenderWidgetHost via its call to the // delegate's OverrideWebkitPrefs. new WebContentsPreferences(new_contents, dict); } bool WebContents::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) { bool default_prevented = Emit( "-will-add-new-contents", params.target_url, params.frame_name, params.raw_features, params.disposition, *params.referrer, params.body); // If the app prevented the default, redirect to CreateCustomWebContents, // which always returns nullptr, which will result in the window open being // prevented (window.open() will return null in the renderer). return default_prevented; } void WebContents::SetNextChildWebPreferences( const gin_helper::Dictionary preferences) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); // Store these prefs for when Chrome calls WebContentsCreatedWithFullParams // with the new child contents. pending_child_web_preferences_.Reset(isolate, preferences.GetHandle()); } content::WebContents* WebContents::CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionConfig& partition_config, content::SessionStorageNamespace* session_storage_namespace) { return nullptr; } void WebContents::AddNewContents( content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, 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, initial_rect.x(), initial_rect.y(), initial_rect.width(), initial_rect.height(), tracker->url, tracker->frame_name, tracker->referrer, tracker->raw_features, tracker->body)) { api_web_contents->Destroy(); } } content::WebContents* WebContents::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { auto weak_this = GetWeakPtr(); if (params.disposition != WindowOpenDisposition::CURRENT_TAB) { Emit("-new-window", params.url, "", params.disposition, "", params.referrer, params.post_data); return nullptr; } if (!weak_this || !web_contents()) return nullptr; content::NavigationController::LoadURLParams load_url_params(params.url); load_url_params.referrer = params.referrer; load_url_params.transition_type = params.transition; load_url_params.extra_headers = params.extra_headers; load_url_params.should_replace_current_entry = params.should_replace_current_entry; load_url_params.is_renderer_initiated = params.is_renderer_initiated; load_url_params.started_from_context_menu = params.started_from_context_menu; load_url_params.initiator_origin = params.initiator_origin; load_url_params.source_site_instance = params.source_site_instance; load_url_params.frame_tree_node_id = params.frame_tree_node_id; load_url_params.redirect_chain = params.redirect_chain; load_url_params.has_user_gesture = params.user_gesture; load_url_params.blob_url_loader_factory = params.blob_url_loader_factory; load_url_params.href_translate = params.href_translate; load_url_params.reload_type = params.reload_type; if (params.post_data) { load_url_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; load_url_params.post_data = params.post_data; } source->GetController().LoadURLWithParams(load_url_params); return source; } void WebContents::BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen || type_ == Type::kBrowserView) *proceed_to_fire_unload = proceed; else *proceed_to_fire_unload = true; // Note that Chromium does not emit this for navigations. Emit("before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnSetContentBounds(rect); } void WebContents::CloseContents(content::WebContents* source) { Emit("close"); auto* autofill_driver_factory = AutofillDriverFactory::FromWebContents(web_contents()); if (autofill_driver_factory) { autofill_driver_factory->CloseAllPopups(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); } void WebContents::ActivateContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnActivateContents(); } void WebContents::UpdateTargetURL(content::WebContents* source, const GURL& url) { Emit("update-target-url", url); } bool WebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (type_ == Type::kWebView && embedder_) { // Send the unhandled keyboard events back to the embedder. return embedder_->HandleKeyboardEvent(source, event); } else { return PlatformHandleKeyboardEvent(source, event); } } #if !BUILDFLAG(IS_MAC) // NOTE: The macOS version of this function is found in // electron_api_web_contents_mac.mm, as it requires calling into objective-C // code. bool WebContents::PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { // Escape exits tabbed fullscreen mode. if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { ExitFullscreenModeForTab(source); return true; } // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts()) return false; // Let the NativeWindow handle other parts. if (owner_window()) { owner_window()->HandleKeyboardEvent(source, event); return true; } return false; } #endif content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (exclusive_access_manager_->HandleUserKeyEvent(event)) return content::KeyboardEventProcessingResult::HANDLED; if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kKeyUp) { bool prevent_default = Emit("before-input-event", event); if (prevent_default) { return content::KeyboardEventProcessingResult::HANDLED; } } return content::KeyboardEventProcessingResult::NOT_HANDLED; } void WebContents::ContentsZoomChange(bool zoom_in) { Emit("zoom-changed", zoom_in ? "in" : "out"); } Profile* WebContents::GetProfile() { return nullptr; } bool WebContents::IsFullscreen() const { return owner_window_ && owner_window_->IsFullscreen(); } void WebContents::EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) {} void WebContents::ExitFullscreen() {} void WebContents::UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool 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(callback); } void WebContents::OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed) { if (!allowed || !owner_window_) return; auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); if (IsFullscreenForTabOrPending(source)) { DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame()); return; } owner_window()->set_fullscreen_transition_type( NativeWindow::FullScreenTransitionType::HTML); exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); SetHtmlApiFullscreen(true); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { if (!owner_window_) return; // This needs to be called before we exit fullscreen on the native window, // or the controller will incorrectly think we weren't fullscreen and bail. exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab( source); SetHtmlApiFullscreen(false); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. Chrome does this indirectly from // `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) { Emit("unresponsive"); } void WebContents::RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) { Emit("responsive"); } bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) { Emit("context-menu", std::make_pair(params, &render_frame_host)); return true; } bool WebContents::OnGoToEntryOffset(int offset) { GoToOffset(offset); return false; } void WebContents::FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { if (!final_update) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate); result.Set("requestId", request_id); result.Set("matches", number_of_matches); result.Set("selectionArea", selection_rect); result.Set("activeMatchOrdinal", active_match_ordinal); result.Set("finalUpdate", final_update); // Deprecate after 2.0 Emit("found-in-page", result.GetHandle()); } void WebContents::RequestExclusivePointerAccess( content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed) { if (allowed) { exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse( web_contents, user_gesture, last_unlocked_by_target); } else { web_contents->GotResponseToLockMouseRequest( blink::mojom::PointerLockResult::kPermissionDenied); } } void WebContents::RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestPointerLockPermission( user_gesture, last_unlocked_by_target, base::BindOnce(&WebContents::RequestExclusivePointerAccess, base::Unretained(this))); } void WebContents::LostMouseLock() { exclusive_access_manager_->mouse_lock_controller()->LostMouseLock(); } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } void WebContents::CancelKeyboardLockRequest( content::WebContents* web_contents) { exclusive_access_manager_->keyboard_lock_controller() ->CancelKeyboardLockRequest(web_contents); } bool WebContents::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckMediaAccessPermission(security_origin, type); } void WebContents::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestMediaAccessPermission(request, std::move(callback)); } content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { if (!dialog_manager_) dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>(); return dialog_manager_.get(); } void WebContents::OnAudioStateChanged(bool audible) { Emit("-audio-state-changed", audible); } void WebContents::BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) { // Do nothing, we override this method just to avoid compilation error since // there are two virtual functions named BeforeUnloadFired. } void WebContents::HandleNewRenderFrame( content::RenderFrameHost* render_frame_host) { auto* rwhv = render_frame_host->GetView(); if (!rwhv) return; // Set the background color of RenderWidgetHostView. auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences) { absl::optional<SkColor> maybe_color = web_preferences->GetBackgroundColor(); web_contents()->SetPageBaseBackgroundColor(maybe_color); bool guest = IsGuest() || type_ == Type::kBrowserView; SkColor color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); SetBackgroundColor(rwhv, color); } if (!background_throttling_) render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false); auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (rwh_impl) rwh_impl->disable_hidden_ = !background_throttling_; auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->MaybeSetupMojoConnection(); } void WebContents::OnBackgroundColorChanged() { absl::optional<SkColor> color = web_contents()->GetBackgroundColor(); if (color.has_value()) { auto* const view = web_contents()->GetRenderWidgetHostView(); static_cast<content::RenderWidgetHostViewBase*>(view) ->SetContentBackgroundColor(color.value()); } } void WebContents::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { HandleNewRenderFrame(render_frame_host); // RenderFrameCreated is called for speculative frames which may not be // used in certain cross-origin navigations. Invoking // RenderFrameHost::GetLifecycleState currently crashes when called for // speculative frames so we need to filter it out for now. Check // https://crbug.com/1183639 for details on when this can be removed. auto* rfh_impl = static_cast<content::RenderFrameHostImpl*>(render_frame_host); if (rfh_impl->lifecycle_state() == content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) { return; } content::RenderFrameHost::LifecycleState lifecycle_state = render_frame_host->GetLifecycleState(); if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.SetGetter("frame", render_frame_host); Emit("frame-created", details); } } void WebContents::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { // A RenderFrameHost can be deleted when: // - A WebContents is removed and its containing frames are disposed. // - An <iframe> is removed from the DOM. // - Cross-origin navigation creates a new RFH in a separate process which // is swapped by content::RenderFrameHostManager. // // WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID // to find an existing instance of WebFrameMain. During a cross-origin // navigation, the deleted RFH will be the old host which was swapped out. In // this special case, we need to also ensure that WebFrameMain's internal RFH // matches before marking it as disposed. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame && web_frame->render_frame_host() == render_frame_host) web_frame->MarkRenderFrameDisposed(); } void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { // During cross-origin navigation, a FrameTreeNode will swap out its RFH. // If an instance of WebFrameMain exists, it will need to have its RFH // swapped as well. // // |old_host| can be a nullptr so we use |new_host| for looking up the // WebFrameMain instance. auto* web_frame = WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId()); if (web_frame) { web_frame->UpdateRenderFrameHost(new_host); } } void WebContents::FrameDeleted(int frame_tree_node_id) { auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id); if (web_frame) web_frame->Destroyed(); } void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) { // This event is necessary for tracking any states with respect to // intermediate render view hosts aka speculative render view hosts. Currently // used by object-registry.js to ref count remote objects. Emit("render-view-deleted", render_view_host->GetProcess()->GetID()); if (web_contents()->GetRenderViewHost() == render_view_host) { // When the RVH that has been deleted is the current RVH it means that the // the web contents are being closed. This is communicated by this event. // Currently tracked by guest-window-manager.ts to destroy the // BrowserWindow. Emit("current-render-view-deleted", render_view_host->GetProcess()->GetID()); } } void WebContents::PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) { auto weak_this = GetWeakPtr(); Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED); // User might destroy WebContents in the crashed event. if (!weak_this || !web_contents()) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.Set("reason", status); details.Set("exitCode", web_contents()->GetCrashedErrorCode()); Emit("render-process-gone", details); } void WebContents::PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) { #if BUILDFLAG(ENABLE_PLUGINS) content::WebPluginInfo info; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->GetPluginInfoByPath(plugin_path, &info); Emit("plugin-crashed", info.name, info.version); #endif // BUILDFLAG(ENABLE_PLUGINS) } void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) { Emit("media-started-playing"); } void WebContents::MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) { Emit("media-paused"); } void WebContents::DidChangeThemeColor() { auto theme_color = web_contents()->GetThemeColor(); if (theme_color) { Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value())); } else { Emit("did-change-theme-color", nullptr); } } void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) { set_fullscreen_frame(rfh); } void WebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { Emit("focus"); } void WebContents::OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) { Emit("blur"); } void WebContents::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->DOMContentLoaded(); if (!render_frame_host->GetParent()) Emit("dom-ready"); } void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); auto weak_this = GetWeakPtr(); Emit("did-frame-finish-load", is_main_frame, frame_process_id, frame_routing_id); // ⚠️WARNING!⚠️ // Emit() triggers JS which can call destroy() on |this|. It's not safe to // assume that |this| points to valid memory at this point. if (is_main_frame && weak_this && web_contents()) Emit("did-finish-load"); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& url, int error_code) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::DidStartLoading() { Emit("did-start-loading"); } void WebContents::DidStopLoading() { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences && web_preferences->ShouldUsePreferredSizeMode()) web_contents()->GetRenderViewHost()->EnablePreferredSizeMode(); Emit("did-stop-loading"); } bool WebContents::EmitNavigationEvent( const std::string& event, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId(); content::FrameTreeNode* frame_tree_node = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id); content::RenderFrameHostManager* render_manager = frame_tree_node->render_manager(); content::RenderFrameHost* frame_host = nullptr; if (render_manager) { frame_host = render_manager->speculative_frame_host(); if (!frame_host) frame_host = render_manager->current_frame_host(); } int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } bool is_same_document = navigation_handle->IsSameDocument(); auto url = navigation_handle->GetURL(); return Emit(event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Message", "channel", channel); // webContents.emit('-ipc-message', new Event(), internal, channel, // arguments); EmitWithSender("-ipc-message", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), internal, channel, std::move(arguments)); } void WebContents::Invoke( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::InvokeCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel); // webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments); EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::OnFirstNonEmptyLayout( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents()->GetPrimaryMainFrame()) { Emit("ready-to-show"); } } void WebContents::ReceivePostMessage( const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto wrapped_ports = MessagePort::EntanglePorts(isolate, std::move(message.ports)); v8::Local<v8::Value> message_value = electron::DeserializeV8Value(isolate, message); EmitWithSender("-ipc-ports", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), false, channel, message_value, std::move(wrapped_ports)); } void WebContents::MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel); // webContents.emit('-ipc-message-sync', new Event(sender, message), internal, // channel, arguments); EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments) { TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel); auto* target_web_contents = FromID(web_contents_id); if (target_web_contents) { content::RenderFrameHost* frame = target_web_contents->MainFrame(); DCHECK(frame); v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate()); gin::Handle<WebFrameMain> web_frame_main = WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame); if (!web_frame_main->CheckRenderFrame()) return; int32_t sender_id = ID(); web_frame_main->GetRendererApi()->Message(false /* internal */, channel, std::move(arguments), sender_id); } } void WebContents::MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel); // webContents.emit('ipc-message-host', new Event(), channel, args); EmitWithSender("ipc-message-host", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), channel, std::move(arguments)); } void WebContents::UpdateDraggableRegions( std::vector<mojom::DraggableRegionPtr> regions) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDraggableRegionsUpdated(regions); } void WebContents::DidStartNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-start-navigation", navigation_handle); } void WebContents::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-redirect-navigation", navigation_handle); } void WebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { // Don't focus content in an inactive window. if (!owner_window()) return; #if BUILDFLAG(IS_MAC) if (!owner_window()->IsActive()) return; #else if (!owner_window()->widget()->IsActive()) return; #endif // Don't focus content after subframe navigations. if (!navigation_handle->IsInMainFrame()) return; // Only focus for top-level contents. if (type_ != Type::kBrowserWindow) return; web_contents()->SetInitialFocus(); } void WebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (owner_window_) { owner_window_->NotifyLayoutWindowControlsOverlay(); } if (!navigation_handle->HasCommitted()) return; bool is_main_frame = navigation_handle->IsInMainFrame(); content::RenderFrameHost* frame_host = navigation_handle->GetRenderFrameHost(); int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } if (!navigation_handle->IsErrorPage()) { // FIXME: All the Emit() calls below could potentially result in |this| // being destroyed (by JS listening for the event and calling // webContents.destroy()). auto url = navigation_handle->GetURL(); bool is_same_document = navigation_handle->IsSameDocument(); if (is_same_document) { Emit("did-navigate-in-page", url, is_main_frame, frame_process_id, frame_routing_id); } else { const net::HttpResponseHeaders* http_response = navigation_handle->GetResponseHeaders(); std::string http_status_text; int http_response_code = -1; if (http_response) { http_status_text = http_response->GetStatusText(); http_response_code = http_response->response_code(); } Emit("did-frame-navigate", url, http_response_code, http_status_text, is_main_frame, frame_process_id, frame_routing_id); if (is_main_frame) { Emit("did-navigate", url, http_response_code, http_status_text); } } if (IsGuest()) Emit("load-commit", url, is_main_frame); } else { auto url = navigation_handle->GetURL(); int code = navigation_handle->GetNetErrorCode(); auto description = net::ErrorToShortString(code); Emit("did-fail-provisional-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); // Do not emit "did-fail-load" for canceled requests. if (code != net::ERR_ABORTED) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "Failed to load URL: " + url.possibly_invalid_spec() + " with error: " + description, "electron"); Emit("did-fail-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); } } content::NavigationEntry* entry = navigation_handle->GetNavigationEntry(); // This check is needed due to an issue in Chromium // Check the Chromium issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=1178663 // If a history entry has been made and the forward/back call has been made, // proceed with setting the new title if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK)) WebContents::TitleWasSet(entry); } void WebContents::TitleWasSet(content::NavigationEntry* entry) { std::u16string final_title; bool explicit_set = true; if (entry) { auto title = entry->GetTitle(); auto url = entry->GetURL(); if (url.SchemeIsFile() && title.empty()) { final_title = base::UTF8ToUTF16(url.ExtractFileName()); explicit_set = false; } else { final_title = title; } } else { final_title = web_contents()->GetTitle(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnPageTitleUpdated(final_title, explicit_set); Emit("page-title-updated", final_title, explicit_set); } void WebContents::DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) { std::set<GURL> unique_urls; for (const auto& iter : urls) { if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon) continue; const GURL& url = iter->icon_url; if (url.is_valid()) unique_urls.insert(url); } Emit("page-favicon-updated", unique_urls); } void WebContents::DevToolsReloadPage() { Emit("devtools-reload-page"); } void WebContents::DevToolsFocused() { Emit("devtools-focused"); } void WebContents::DevToolsOpened() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); DCHECK(inspectable_web_contents_); DCHECK(inspectable_web_contents_->GetDevToolsWebContents()); auto handle = FromOrCreate( isolate, inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_contents_.Reset(isolate, handle.ToV8()); // Set inspected tabID. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "setInspectedTabId", base::Value(ID())); // Inherit owner window in devtools when it doesn't have one. auto* devtools = inspectable_web_contents_->GetDevToolsWebContents(); bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey()); if (owner_window() && !has_window) handle->SetOwnerWindow(devtools, owner_window()); Emit("devtools-opened"); } void WebContents::DevToolsClosed() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); devtools_web_contents_.Reset(); Emit("devtools-closed"); } void WebContents::DevToolsResized() { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDevToolsResized(); } void WebContents::SetOwnerWindow(NativeWindow* owner_window) { SetOwnerWindow(GetWebContents(), owner_window); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } #if BUILDFLAG(ENABLE_OSR) auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); #endif } content::WebContents* WebContents::GetWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetWebContents(); } content::WebContents* WebContents::GetDevToolsWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetDevToolsWebContents(); } void WebContents::WebContentsDestroyed() { // Clear the pointer stored in wrapper. if (GetAllWebContents().Lookup(id_)) GetAllWebContents().Remove(id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; wrapper->SetAlignedPointerInInternalField(0, nullptr); // Tell WebViewGuestDelegate that the WebContents has been destroyed. if (guest_delegate_) guest_delegate_->WillDestroy(); Observe(nullptr); Emit("destroyed"); } void WebContents::NavigationEntryCommitted( const content::LoadCommittedDetails& details) { Emit("navigation-entry-committed", details.entry->GetURL(), details.is_same_document, details.did_replace_entry); } bool WebContents::GetBackgroundThrottling() const { return background_throttling_; } void WebContents::SetBackgroundThrottling(bool allowed) { background_throttling_ = allowed; auto* rfh = web_contents()->GetPrimaryMainFrame(); if (!rfh) return; auto* rwhv = rfh->GetView(); if (!rwhv) return; auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (!rwh_impl) return; rwh_impl->disable_hidden_ = !background_throttling_; web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed); if (rwh_impl->is_hidden()) { rwh_impl->WasShown({}); } } int WebContents::GetProcessID() const { return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents() ->GetPrimaryMainFrame() ->GetProcess() ->GetProcess() .Handle(); return base::GetProcId(process_handle); } WebContents::Type WebContents::GetType() const { return type_; } bool WebContents::Equal(const WebContents* web_contents) const { return ID() == web_contents->ID(); } GURL WebContents::GetURL() const { return web_contents()->GetLastCommittedURL(); } void WebContents::LoadURL(const GURL& url, const gin_helper::Dictionary& options) { if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) { Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL), net::ErrorToShortString(net::ERR_INVALID_URL), url.possibly_invalid_spec(), true); return; } content::NavigationController::LoadURLParams params(url); if (!options.Get("httpReferrer", &params.referrer)) { GURL http_referrer; if (options.Get("httpReferrer", &http_referrer)) params.referrer = content::Referrer(http_referrer.GetAsReferrer(), network::mojom::ReferrerPolicy::kDefault); } std::string user_agent; if (options.Get("userAgent", &user_agent)) SetUserAgent(user_agent); std::string extra_headers; if (options.Get("extraHeaders", &extra_headers)) params.extra_headers = extra_headers; scoped_refptr<network::ResourceRequestBody> body; if (options.Get("postData", &body)) { params.post_data = body; params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; } GURL base_url_for_data_url; if (options.Get("baseURLForDataURL", &base_url_for_data_url)) { params.base_url_for_data_url = base_url_for_data_url; params.load_type = content::NavigationController::LOAD_TYPE_DATA; } bool reload_ignoring_cache = false; if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) && reload_ignoring_cache) { params.reload_type = content::ReloadType::BYPASSING_CACHE; } // Calling LoadURLWithParams() can trigger JS which destroys |this|. auto weak_this = GetWeakPtr(); params.transition_type = ui::PageTransitionFromInt( ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; // Discard non-committed entries to ensure that we don't re-use a pending // entry web_contents()->GetController().DiscardNonCommittedEntries(); web_contents()->GetController().LoadURLWithParams(params); // ⚠️WARNING!⚠️ // LoadURLWithParams() triggers JS events which can call destroy() on |this|. // It's not safe to assume that |this| points to valid memory at this point. if (!weak_this || !web_contents()) return; // Required to make beforeunload handler work. NotifyUserActivation(); } // TODO(MarshallOfSound): Figure out what we need to do with post data here, I // believe the default behavior when we pass "true" is to phone out to the // delegate and then the controller expects this method to be called again with // "false" if the user approves the reload. For now this would result in // ".reload()" calls on POST data domains failing silently. Passing false would // result in them succeeding, but reposting which although more correct could be // considering a breaking change. void WebContents::Reload() { web_contents()->GetController().Reload(content::ReloadType::NORMAL, /* check_for_repost */ true); } void WebContents::ReloadIgnoringCache() { web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE, /* check_for_repost */ true); } void WebContents::DownloadURL(const GURL& url) { auto* browser_context = web_contents()->GetBrowserContext(); auto* download_manager = browser_context->GetDownloadManager(); std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); download_manager->DownloadUrl(std::move(download_params)); } std::u16string WebContents::GetTitle() const { return web_contents()->GetTitle(); } bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } bool WebContents::IsLoadingMainFrame() const { return web_contents()->ShouldShowLoadingUI(); } bool WebContents::IsWaitingForResponse() const { return web_contents()->IsWaitingForResponse(); } void WebContents::Stop() { web_contents()->Stop(); } bool WebContents::CanGoBack() const { return web_contents()->GetController().CanGoBack(); } void WebContents::GoBack() { if (CanGoBack()) web_contents()->GetController().GoBack(); } bool WebContents::CanGoForward() const { return web_contents()->GetController().CanGoForward(); } void WebContents::GoForward() { if (CanGoForward()) web_contents()->GetController().GoForward(); } bool WebContents::CanGoToOffset(int offset) const { return web_contents()->GetController().CanGoToOffset(offset); } void WebContents::GoToOffset(int offset) { if (CanGoToOffset(offset)) web_contents()->GetController().GoToOffset(offset); } bool WebContents::CanGoToIndex(int index) const { return index >= 0 && index < GetHistoryLength(); } void WebContents::GoToIndex(int index) { if (CanGoToIndex(index)) web_contents()->GetController().GoToIndex(index); } int WebContents::GetActiveIndex() const { return web_contents()->GetController().GetCurrentEntryIndex(); } void WebContents::ClearHistory() { // In some rare cases (normally while there is no real history) we are in a // state where we can't prune navigation entries if (web_contents()->GetController().CanPruneAllButLastCommitted()) { web_contents()->GetController().PruneAllButLastCommitted(); } } int WebContents::GetHistoryLength() const { return web_contents()->GetController().GetEntryCount(); } const std::string WebContents::GetWebRTCIPHandlingPolicy() const { return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy; } void WebContents::SetWebRTCIPHandlingPolicy( const std::string& webrtc_ip_handling_policy) { if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy) return; web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy = webrtc_ip_handling_policy; web_contents()->SyncRendererPrefs(); } std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) return std::string(); content::DesktopMediaID media_id( content::DesktopMediaID::TYPE_WEB_CONTENTS, content::DesktopMediaID::kNullId, content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(), frame_host->GetRoutingID())); auto* request_frame_host = request_web_contents->GetPrimaryMainFrame(); if (!request_frame_host) return std::string(); std::string id = content::DesktopStreamsRegistry::GetInstance()->RegisterStream( request_frame_host->GetProcess()->GetID(), request_frame_host->GetRoutingID(), url::Origin::Create(request_frame_host->GetLastCommittedURL() .DeprecatedGetOriginAsURL()), media_id, "", content::kRegistryStreamTypeTab); return id; } bool WebContents::IsCrashed() const { return web_contents()->IsCrashed(); } void WebContents::ForcefullyCrashRenderer() { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); if (!rwh) return; content::RenderProcessHost* rph = rwh->GetProcess(); if (rph) { #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // A generic |CrashDumpHungChildProcess()| is not implemented for Linux. // Instead we send an explicit IPC to crash on the renderer's IO thread. rph->ForceCrash(); #else // Try to generate a crash report for the hung process. #ifndef MAS_BUILD CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { blink::UserAgentOverride ua_override; ua_override.ua_string_override = user_agent; if (!user_agent.empty()) ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata(); web_contents()->SetUserAgentOverride(ua_override, false); } std::string WebContents::GetUserAgent() { return web_contents()->GetUserAgentOverride().ua_string_override; } v8::Local<v8::Promise> WebContents::SavePage( const base::FilePath& full_file_path, const content::SavePageType& save_type) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (!full_file_path.IsAbsolute()) { promise.RejectWithErrorMessage("Path must be absolute"); return handle; } auto* handler = new SavePageHandler(web_contents(), std::move(promise)); handler->Handle(full_file_path, save_type); return handle; } void WebContents::OpenDevTools(gin::Arguments* args) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; std::string state; if (type_ == Type::kWebView || type_ == Type::kBackgroundPage || !owner_window()) { state = "detach"; } bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->ShowDevTools(activate); } void WebContents::CloseDevTools() { if (type_ == Type::kRemote) return; DCHECK(inspectable_web_contents_); inspectable_web_contents_->CloseDevTools(); } bool WebContents::IsDevToolsOpened() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->IsDevToolsViewShowing(); } bool WebContents::IsDevToolsFocused() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetView()->IsDevToolsViewFocused(); } void WebContents::EnableDeviceEmulation( const blink::DeviceEmulationParams& params) { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->EnableDeviceEmulation(params); } } } void WebContents::DisableDeviceEmulation() { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->DisableDeviceEmulation(); } } } void WebContents::ToggleDevTools() { if (IsDevToolsOpened()) CloseDevTools(); else OpenDevTools(nullptr); } void WebContents::InspectElement(int x, int y) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; DCHECK(inspectable_web_contents_); if (!inspectable_web_contents_->GetDevToolsWebContents()) OpenDevTools(nullptr); inspectable_web_contents_->InspectElement(x, y); } void WebContents::InspectSharedWorkerById(const std::string& workerId) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { if (agent_host->GetId() == workerId) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } } std::vector<scoped_refptr<content::DevToolsAgentHost>> WebContents::GetAllSharedWorkers() { std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers; if (type_ == Type::kRemote) return shared_workers; if (!enable_devtools_) return shared_workers; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { shared_workers.push_back(agent_host); } } return shared_workers; } void WebContents::InspectSharedWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::InspectServiceWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeServiceWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::SetIgnoreMenuShortcuts(bool ignore) { auto* web_preferences = WebContentsPreferences::From(web_contents()); DCHECK(web_preferences); web_preferences->SetIgnoreMenuShortcuts(ignore); } void WebContents::SetAudioMuted(bool muted) { web_contents()->SetAudioMuted(muted); } bool WebContents::IsAudioMuted() { return web_contents()->IsAudioMuted(); } bool WebContents::IsCurrentlyAudible() { return web_contents()->IsCurrentlyAudible(); } #if BUILDFLAG(ENABLE_PRINTING) void WebContents::OnGetDeviceNameToUse( base::Value::Dict print_settings, printing::CompletionCallback print_callback, bool silent, // <error, device_name> std::pair<std::string, std::u16string> info) { // The content::WebContents might be already deleted at this point, and the // PrintViewManagerElectron class does not do null check. if (!web_contents()) { if (print_callback) std::move(print_callback).Run(false, "failed"); return; } if (!info.first.empty()) { if (print_callback) std::move(print_callback).Run(false, info.first); return; } // If the user has passed a deviceName use it, otherwise use default printer. print_settings.Set(printing::kSettingDeviceName, info.second); auto* print_view_manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!print_view_manager) return; auto* focused_frame = web_contents()->GetFocusedFrame(); auto* rfh = focused_frame && focused_frame->HasSelection() ? focused_frame : web_contents()->GetPrimaryMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); base::Value::Dict settings; if (args->Length() >= 1 && !args->GetNext(&options)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid print settings specified."); return; } printing::CompletionCallback callback; if (args->Length() == 2 && !args->GetNext(&callback)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid optional callback provided."); return; } // Set optional silent printing bool silent = false; options.Get("silent", &silent); bool print_background = false; options.Get("printBackground", &print_background); settings.Set(printing::kSettingShouldPrintBackgrounds, print_background); // Set custom margin settings gin_helper::Dictionary margins = gin::Dictionary::CreateEmpty(args->isolate()); if (options.Get("margins", &margins)) { printing::mojom::MarginType margin_type = printing::mojom::MarginType::kDefaultMargins; margins.Get("marginType", &margin_type); settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type)); if (margin_type == printing::mojom::MarginType::kCustomMargins) { base::Value::Dict custom_margins; int top = 0; margins.Get("top", &top); custom_margins.Set(printing::kSettingMarginTop, top); int bottom = 0; margins.Get("bottom", &bottom); custom_margins.Set(printing::kSettingMarginBottom, bottom); int left = 0; margins.Get("left", &left); custom_margins.Set(printing::kSettingMarginLeft, left); int right = 0; margins.Get("right", &right); custom_margins.Set(printing::kSettingMarginRight, right); settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins)); } } else { settings.Set( printing::kSettingMarginsType, static_cast<int>(printing::mojom::MarginType::kDefaultMargins)); } // Set whether to print color or greyscale bool print_color = true; options.Get("color", &print_color); auto const color_model = print_color ? printing::mojom::ColorModel::kColor : printing::mojom::ColorModel::kGray; settings.Set(printing::kSettingColor, static_cast<int>(color_model)); // Is the orientation landscape or portrait. bool landscape = false; options.Get("landscape", &landscape); settings.Set(printing::kSettingLandscape, landscape); // We set the default to the system's default printer and only update // if at the Chromium level if the user overrides. // Printer device name as opened by the OS. std::u16string device_name; options.Get("deviceName", &device_name); int scale_factor = 100; options.Get("scaleFactor", &scale_factor); settings.Set(printing::kSettingScaleFactor, scale_factor); int pages_per_sheet = 1; options.Get("pagesPerSheet", &pages_per_sheet); settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet); // True if the user wants to print with collate. bool collate = true; options.Get("collate", &collate); settings.Set(printing::kSettingCollate, collate); // The number of individual copies to print int copies = 1; options.Get("copies", &copies); settings.Set(printing::kSettingCopies, copies); // Strings to be printed as headers and footers if requested by the user. std::string header; options.Get("header", &header); std::string footer; options.Get("footer", &footer); if (!(header.empty() && footer.empty())) { settings.Set(printing::kSettingHeaderFooterEnabled, true); settings.Set(printing::kSettingHeaderFooterTitle, header); settings.Set(printing::kSettingHeaderFooterURL, footer); } else { settings.Set(printing::kSettingHeaderFooterEnabled, false); } // We don't want to allow the user to enable these settings // but we need to set them or a CHECK is hit. settings.Set(printing::kSettingPrinterType, static_cast<int>(printing::mojom::PrinterType::kLocal)); settings.Set(printing::kSettingShouldPrintSelectionOnly, false); settings.Set(printing::kSettingRasterizePdf, false); // Set custom page ranges to print std::vector<gin_helper::Dictionary> page_ranges; if (options.Get("pageRanges", &page_ranges)) { base::Value::List page_range_list; for (auto& range : page_ranges) { int from, to; if (range.Get("from", &from) && range.Get("to", &to)) { base::Value::Dict range; // Chromium uses 1-based page ranges, so increment each by 1. range.Set(printing::kSettingPageRangeFrom, from + 1); range.Set(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range)); } else { continue; } } if (!page_range_list.empty()) settings.Set(printing::kSettingPageRange, std::move(page_range_list)); } // Duplex type user wants to use. printing::mojom::DuplexMode duplex_mode = printing::mojom::DuplexMode::kSimplex; options.Get("duplexMode", &duplex_mode); settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode)); // We've already done necessary parameter sanitization at the // JS level, so we can simply pass this through. base::Value media_size(base::Value::Type::DICTIONARY); if (options.Get("mediaSize", &media_size)) settings.Set(printing::kSettingMediaSize, std::move(media_size)); // Set custom dots per inch (dpi) gin_helper::Dictionary dpi_settings; int dpi = 72; if (options.Get("dpi", &dpi_settings)) { int horizontal = 72; dpi_settings.Get("horizontal", &horizontal); settings.Set(printing::kSettingDpiHorizontal, horizontal); int vertical = 72; dpi_settings.Get("vertical", &vertical); settings.Set(printing::kSettingDpiVertical, vertical); } else { settings.Set(printing::kSettingDpiHorizontal, dpi); settings.Set(printing::kSettingDpiVertical, dpi); } print_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name), base::BindOnce(&WebContents::OnGetDeviceNameToUse, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), silent)); } // Partially duplicated and modified from // headless/lib/browser/protocol/page_handler.cc;l=41 v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); // This allows us to track headless printing calls. auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID); auto landscape = settings.GetDict().FindBool("landscape"); auto display_header_footer = settings.GetDict().FindBool("displayHeaderFooter"); auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds"); auto scale = settings.GetDict().FindDouble("scale"); auto paper_width = settings.GetDict().FindInt("paperWidth"); auto paper_height = settings.GetDict().FindInt("paperHeight"); auto margin_top = settings.GetDict().FindIntByDottedPath("margins.top"); auto margin_bottom = settings.GetDict().FindIntByDottedPath("margins.bottom"); auto margin_left = settings.GetDict().FindIntByDottedPath("margins.left"); auto margin_right = settings.GetDict().FindIntByDottedPath("margins.right"); auto page_ranges = *settings.GetDict().FindString("pageRanges"); auto header_template = *settings.GetDict().FindString("headerTemplate"); auto footer_template = *settings.GetDict().FindString("footerTemplate"); auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize"); absl::variant<printing::mojom::PrintPagesParamsPtr, std::string> print_pages_params = print_to_pdf::GetPrintPagesParams( web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(), landscape, display_header_footer, print_background, scale, paper_width, paper_height, margin_top, margin_bottom, margin_left, margin_right, absl::make_optional(header_template), absl::make_optional(footer_template), prefer_css_page_size); if (absl::holds_alternative<std::string>(print_pages_params)) { auto error = absl::get<std::string>(print_pages_params); promise.RejectWithErrorMessage("Invalid print parameters: " + error); return handle; } auto* manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!manager) { promise.RejectWithErrorMessage("Failed to find print manager"); return handle; } auto params = std::move( absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params)); params->params->document_cookie = unique_id.value_or(0); manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges, std::move(params), base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(), std::move(promise))); return handle; } void WebContents::OnPDFCreated( gin_helper::Promise<v8::Local<v8::Value>> promise, PrintViewManagerElectron::PrintResult print_result, scoped_refptr<base::RefCountedMemory> data) { if (print_result != PrintViewManagerElectron::PrintResult::PRINT_SUCCESS) { promise.RejectWithErrorMessage( "Failed to generate PDF: " + PrintViewManagerElectron::PrintResultToString(print_result)); return; } v8::Isolate* isolate = promise.isolate(); gin_helper::Locker locker(isolate); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope( v8::Local<v8::Context>::New(isolate, promise.GetContext())); v8::Local<v8::Value> buffer = node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()), data->size()) .ToLocalChecked(); promise.Resolve(buffer); } #endif void WebContents::AddWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsAddFileSystem(std::string(), path); } void WebContents::RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsRemoveFileSystem(path); } void WebContents::Undo() { web_contents()->Undo(); } void WebContents::Redo() { web_contents()->Redo(); } void WebContents::Cut() { web_contents()->Cut(); } void WebContents::Copy() { web_contents()->Copy(); } void WebContents::Paste() { web_contents()->Paste(); } void WebContents::PasteAndMatchStyle() { web_contents()->PasteAndMatchStyle(); } void WebContents::Delete() { web_contents()->Delete(); } void WebContents::SelectAll() { web_contents()->SelectAll(); } void WebContents::Unselect() { web_contents()->CollapseSelection(); } void WebContents::Replace(const std::u16string& word) { web_contents()->Replace(word); } void WebContents::ReplaceMisspelling(const std::u16string& word) { web_contents()->ReplaceMisspelling(word); } uint32_t WebContents::FindInPage(gin::Arguments* args) { std::u16string search_text; if (!args->GetNext(&search_text) || search_text.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must provide a non-empty search content"); return 0; } uint32_t request_id = ++find_in_page_request_id_; gin_helper::Dictionary dict; auto options = blink::mojom::FindOptions::New(); if (args->GetNext(&dict)) { dict.Get("forward", &options->forward); dict.Get("matchCase", &options->match_case); dict.Get("findNext", &options->new_session); } web_contents()->Find(request_id, search_text, std::move(options)); return request_id; } void WebContents::StopFindInPage(content::StopFindAction action) { web_contents()->StopFinding(action); } void WebContents::ShowDefinitionForSelection() { #if BUILDFLAG(IS_MAC) auto* const view = web_contents()->GetRenderWidgetHostView(); if (view) view->ShowDefinitionForSelection(); #endif } void WebContents::CopyImageAt(int x, int y) { auto* const host = web_contents()->GetPrimaryMainFrame(); if (host) host->CopyImageAt(x, y); } void WebContents::Focus() { // Focusing on WebContents does not automatically focus the window on macOS // and Linux, do it manually to match the behavior on Windows. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) if (owner_window()) owner_window()->Focus(true); #endif web_contents()->Focus(); } #if !BUILDFLAG(IS_MAC) bool WebContents::IsFocused() const { auto* view = web_contents()->GetRenderWidgetHostView(); if (!view) return false; if (GetType() != Type::kBackgroundPage) { auto* window = web_contents()->GetNativeView()->GetToplevelWindow(); if (window && !window->IsVisible()) return false; } return view->HasFocus(); } #endif void WebContents::SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event) { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); blink::WebInputEvent::Type type = gin::GetWebInputEventType(isolate, input_event); if (blink::WebInputEvent::IsMouseEventType(type)) { blink::WebMouseEvent mouse_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); #endif } else { rwh->ForwardMouseEvent(mouse_event); } return; } } else if (blink::WebInputEvent::IsKeyboardEventType(type)) { content::NativeWebKeyboardEvent keyboard_event( blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow()); if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) { rwh->ForwardKeyboardEvent(keyboard_event); return; } } else if (type == blink::WebInputEvent::Type::kMouseWheel) { blink::WebMouseWheelEvent mouse_wheel_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); #endif } else { // Chromium expects phase info in wheel events (and applies a // DCHECK to verify it). See: https://crbug.com/756524. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); // Send a synthetic wheel event with phaseEnded to finish scrolling. mouse_wheel_event.has_synthetic_phase = true; mouse_wheel_event.delta_x = 0; mouse_wheel_event.delta_y = 0; mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kEventNonBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); } return; } } isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object"))); } void WebContents::BeginFrameSubscription(gin::Arguments* args) { bool only_dirty = false; FrameSubscriber::FrameCaptureCallback callback; if (args->Length() > 1) { if (!args->GetNext(&only_dirty)) { args->ThrowError(); return; } } if (!args->GetNext(&callback)) { args->ThrowError(); return; } frame_subscriber_ = std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty); } void WebContents::EndFrameSubscription() { frame_subscriber_.reset(); } void WebContents::StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args) { base::FilePath file; std::vector<base::FilePath> files; if (!item.Get("files", &files) && item.Get("file", &file)) { files.push_back(file); } v8::Local<v8::Value> icon_value; if (!item.Get("icon", &icon_value)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'icon' parameter is required"); return; } NativeImage* icon = nullptr; if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) || icon->image().IsEmpty()) { return; } // Start dragging. if (!files.empty()) { base::CurrentThread::ScopedNestableTaskAllower allow; DragFileItems(files, icon->image(), web_contents()->GetNativeView()); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must specify either 'file' or 'files' option"); } } v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) { gfx::Rect rect; gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // get rect arguments if they exist args->GetNext(&rect); auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view) { promise.Resolve(gfx::Image()); return handle; } #if !BUILDFLAG(IS_MAC) // If the view's renderer is suspended this may fail on Windows/Linux - // bail if so. See CopyFromSurface in // content/public/browser/render_widget_host_view.h. auto* rfh = web_contents()->GetPrimaryMainFrame(); if (rfh && rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) { promise.Resolve(gfx::Image()); return handle; } #endif // BUILDFLAG(IS_MAC) // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); const float scale = display::Screen::GetScreen() ->GetDisplayNearestView(native_view) .device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, base::BindOnce(&OnCapturePageDone, std::move(promise))); return handle; } void WebContents::IncrementCapturerCount(gin::Arguments* args) { gfx::Size size; bool stay_hidden = false; bool stay_awake = false; // get size arguments if they exist args->GetNext(&size); // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); std::ignore = web_contents() ->IncrementCapturerCount(size, stay_hidden, stay_awake) .Release(); } void WebContents::DecrementCapturerCount(gin::Arguments* args) { bool stay_hidden = false; bool stay_awake = false; // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); web_contents()->DecrementCapturerCount(stay_hidden, stay_awake); } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const content::WebCursor& webcursor) { const ui::Cursor& cursor = webcursor.cursor(); if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor), gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()), cursor.image_scale_factor(), gfx::Size(cursor.custom_bitmap().width(), cursor.custom_bitmap().height()), cursor.custom_hotspot()); } else { Emit("cursor-changed", CursorTypeToString(cursor)); } } bool WebContents::IsGuest() const { return type_ == Type::kWebView; } void WebContents::AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id) { attached_ = true; if (guest_delegate_) guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id); } bool WebContents::IsOffScreen() const { #if BUILDFLAG(ENABLE_OSR) return type_ == Type::kOffScreen; #else return false; #endif } #if BUILDFLAG(ENABLE_OSR) void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) { Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap)); } void WebContents::StartPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(true); } void WebContents::StopPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(false); } bool WebContents::IsPainting() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv && osr_wcv->IsPainting(); } void WebContents::SetFrameRate(int frame_rate) { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetFrameRate(frame_rate); } int WebContents::GetFrameRate() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv ? osr_wcv->GetFrameRate() : 0; } #endif void WebContents::Invalidate() { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); #endif } else { auto* const window = owner_window(); if (window) window->Invalidate(); } } gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) { if (IsOffScreen() && wc == web_contents()) { auto* relay = NativeWindowRelay::FromWebContents(web_contents()); if (relay) { auto* owner_window = relay->GetNativeWindow(); return owner_window ? owner_window->GetSize() : gfx::Size(); } } return gfx::Size(); } void WebContents::SetZoomLevel(double level) { zoom_controller_->SetZoomLevel(level); } double WebContents::GetZoomLevel() const { return zoom_controller_->GetZoomLevel(); } void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) { if (factor < std::numeric_limits<double>::epsilon()) { thrower.ThrowError("'zoomFactor' must be a double greater than 0.0"); return; } auto level = blink::PageZoomFactorToZoomLevel(factor); SetZoomLevel(level); } double WebContents::GetZoomFactor() const { auto level = GetZoomLevel(); return blink::PageZoomLevelToZoomFactor(level); } void WebContents::SetTemporaryZoomLevel(double level) { zoom_controller_->SetTemporaryZoomLevel(level); } void WebContents::DoGetZoomLevel( electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback callback) { std::move(callback).Run(GetZoomLevel()); } std::vector<base::FilePath> WebContents::GetPreloadPaths() const { auto result = SessionPreferences::GetValidPreloads(GetBrowserContext()); if (auto* web_preferences = WebContentsPreferences::From(web_contents())) { base::FilePath preload; if (web_preferences->GetPreloadPath(&preload)) { result.emplace_back(preload); } } return result; } v8::Local<v8::Value> WebContents::GetLastWebPreferences( v8::Isolate* isolate) const { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (!web_preferences) return v8::Null(isolate); return gin::ConvertToV8(isolate, *web_preferences->last_preference()); } v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow( v8::Isolate* isolate) const { if (owner_window()) return BrowserWindow::From(isolate, owner_window()); else return v8::Null(isolate); } v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) { return v8::Local<v8::Value>::New(isolate, session_); } content::WebContents* WebContents::HostWebContents() const { if (!embedder_) return nullptr; return embedder_->web_contents(); } void WebContents::SetEmbedder(const WebContents* embedder) { if (embedder) { NativeWindow* owner_window = nullptr; auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents()); if (relay) { owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); content::RenderWidgetHostView* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->Hide(); rwhv->Show(); } } } void WebContents::SetDevToolsWebContents(const WebContents* devtools) { if (inspectable_web_contents_) inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents()); } v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const { gfx::NativeView ptr = web_contents()->GetNativeView(); auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr), sizeof(gfx::NativeView)); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) { if (devtools_web_contents_.IsEmpty()) return v8::Null(isolate); else return v8::Local<v8::Value>::New(isolate, devtools_web_contents_); } v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) { if (debugger_.IsEmpty()) { auto handle = electron::api::Debugger::Create(isolate, web_contents()); debugger_.Reset(isolate, handle.ToV8()); } return v8::Local<v8::Value>::New(isolate, debugger_); } content::RenderFrameHost* WebContents::MainFrame() { return web_contents()->GetPrimaryMainFrame(); } void WebContents::NotifyUserActivation() { content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame(); if (frame) frame->NotifyUserActivation( blink::mojom::UserActivationNotificationType::kInteraction); } void WebContents::SetImageAnimationPolicy(const std::string& new_policy) { auto* web_preferences = WebContentsPreferences::From(web_contents()); web_preferences->SetImageAnimationPolicy(new_policy); web_contents()->OnWebPreferencesChanged(); } v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("Failed to create memory dump"); return handle; } auto pid = frame_host->GetProcess()->GetProcess().Pid(); v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext()); memory_instrumentation::MemoryInstrumentation::GetInstance() ->RequestGlobalDumpForPid( pid, std::vector<std::string>(), base::BindOnce(&ElectronBindings::DidReceiveMemoryDump, std::move(context), std::move(promise), pid)); return handle; } v8::Local<v8::Promise> WebContents::TakeHeapSnapshot( v8::Isolate* isolate, const base::FilePath& file_path) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); base::ThreadRestrictions::ScopedAllowIO allow_io; base::File file(file_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); if (!file.IsValid()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } if (!frame_host->IsRenderFrameLive()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } // This dance with `base::Owned` is to ensure that the interface stays alive // until the callback is called. Otherwise it would be closed at the end of // this function. auto electron_renderer = std::make_unique<mojo::Remote<mojom::ElectronRenderer>>(); frame_host->GetRemoteInterfaces()->GetInterface( electron_renderer->BindNewPipeAndPassReceiver()); auto* raw_ptr = electron_renderer.get(); (*raw_ptr)->TakeHeapSnapshot( mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())), base::BindOnce( [](mojo::Remote<mojom::ElectronRenderer>* ep, gin_helper::Promise<void> promise, bool success) { if (success) { promise.Resolve(); } else { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } void WebContents::UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) { Emit("preferred-size-changed", pref_size); } bool WebContents::CanOverscrollContent() { return false; } std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) { return ShowEyeDropper(frame, listener); } void WebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener), params); } void WebContents::EnumerateDirectory( content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path); } bool WebContents::IsFullscreenForTabOrPending( const content::WebContents* source) { if (!owner_window()) return html_fullscreen_; bool in_transition = owner_window()->fullscreen_transition_state() != NativeWindow::FullScreenTransitionState::NONE; bool is_html_transition = owner_window()->fullscreen_transition_type() == NativeWindow::FullScreenTransitionType::HTML; return html_fullscreen_ || (in_transition && is_html_transition); } bool WebContents::TakeFocus(content::WebContents* source, bool reverse) { if (source && source->GetOutermostWebContents() == source) { // If this is the outermost web contents and the user has tabbed or // shift + tabbed through all the elements, reset the focus back to // the first or last element so that it doesn't stay in the body. source->FocusThroughTabTraversal(reverse); return true; } return false; } content::PictureInPictureResult WebContents::EnterPictureInPicture( content::WebContents* web_contents) { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) return PictureInPictureWindowManager::GetInstance() ->EnterVideoPictureInPicture(web_contents); #else return content::PictureInPictureResult::kNotSupported; #endif } void WebContents::ExitPictureInPicture() { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); #endif } void WebContents::DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) { base::FilePath path; auto it = saved_files_.find(url); if (it != saved_files_.end() && !save_as) { path = it->second; } else { file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.title = url; settings.default_path = base::FilePath::FromUTF8Unsafe(url); if (!file_dialog::ShowSaveDialogSync(settings, &path)) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "canceledSaveURL", base::Value(url)); return; } } saved_files_[url] = path; // Notify DevTools. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "savedURL", base::Value(url), base::Value(path.AsUTF8Unsafe())); file_task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteToFile, path, content)); } void WebContents::DevToolsAppendToFile(const std::string& url, const std::string& content) { auto it = saved_files_.find(url); if (it == saved_files_.end()) return; // Notify DevTools. inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL", base::Value(url)); file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&AppendToFile, it->second, content)); } void WebContents::DevToolsRequestFileSystems() { auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); if (file_system_paths.empty()) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List())); return; } std::vector<FileSystem> file_systems; for (const auto& file_system_path : file_system_paths) { base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path.first); std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id, file_system_path.first, file_system_path.second); file_systems.push_back(file_system); } base::Value::List file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(std::move(file_system_value))); } void WebContents::DevToolsAddFileSystem( const std::string& type, const base::FilePath& file_system_path) { base::FilePath path = file_system_path; if (path.empty()) { std::vector<base::FilePath> paths; file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY; if (!file_dialog::ShowOpenDialogSync(settings, &paths)) return; path = paths[0]; } std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe())) return; FileSystem file_system = CreateFileSystemStruct( GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type); base::Value::Dict file_system_value = CreateFileSystemValue(file_system); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->SetKey(path.AsUTF8Unsafe(), base::Value(type)); std::string error = ""; // No error inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemAdded", base::Value(error), base::Value(std::move(file_system_value))); } void WebContents::DevToolsRemoveFileSystem( const base::FilePath& file_system_path) { if (!inspectable_web_contents_) return; std::string path = file_system_path.AsUTF8Unsafe(); storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath( file_system_path); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->RemoveKey(path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemRemoved", base::Value(path)); } void WebContents::DevToolsIndexPath( int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsIndexingDone(request_id, file_system_path); return; } if (devtools_indexing_jobs_.count(request_id) != 0) return; std::vector<std::string> excluded_folders; std::unique_ptr<base::Value> parsed_excluded_folders = base::JSONReader::ReadDeprecated(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetListDeprecated()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsSearchCompleted(request_id, file_system_path, std::vector<std::string>()); return; } devtools_file_system_indexer_->SearchInPath( file_system_path, query, base::BindRepeating(&WebContents::OnDevToolsSearchCompleted, weak_factory_.GetWeakPtr(), request_id, file_system_path)); } void WebContents::DevToolsSetEyeDropperActive(bool active) { auto* web_contents = GetWebContents(); if (!web_contents) return; if (active) { eye_dropper_ = std::make_unique<DevToolsEyeDropper>( web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper, base::Unretained(this))); } else { eye_dropper_.reset(); } } void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) { base::Value::Dict color; color.Set("r", r); color.Set("g", g); color.Set("b", b); color.Set("a", a); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color))); } #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel WebContents::GetDevToolsWindowIcon() { return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{}; } #endif #if BUILDFLAG(IS_LINUX) void WebContents::GetDevToolsWindowWMClass(std::string* name, std::string* class_name) { *class_name = Browser::Get()->GetName(); *name = base::ToLowerASCII(*class_name); } #endif void WebContents::OnDevToolsIndexingWorkCalculated( int request_id, const std::string& file_system_path, int total_work) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id), base::Value(file_system_path), base::Value(total_work)); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingWorked", base::Value(request_id), base::Value(file_system_path), base::Value(worked)); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone", base::Value(request_id), base::Value(file_system_path)); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::Value::List file_paths_value; for (const auto& file_path : file_paths) file_paths_value.Append(file_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "searchCompleted", base::Value(request_id), base::Value(file_system_path), base::Value(std::move(file_paths_value))); } void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) { // Window is already in fullscreen mode, save the state. if (enter_fullscreen && owner_window_->IsFullscreen()) { native_fullscreen_ = true; UpdateHtmlApiFullscreen(true); return; } // Exit html fullscreen state but not window's fullscreen mode. if (!enter_fullscreen && native_fullscreen_) { UpdateHtmlApiFullscreen(false); return; } // Set fullscreen on window if allowed. auto* web_preferences = WebContentsPreferences::From(GetWebContents()); bool html_fullscreenable = web_preferences ? !web_preferences->ShouldDisableHtmlFullscreenWindowResize() : true; if (html_fullscreenable) owner_window_->SetFullScreen(enter_fullscreen); UpdateHtmlApiFullscreen(enter_fullscreen); native_fullscreen_ = false; } void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) { if (fullscreen == is_html_fullscreen()) return; html_fullscreen_ = fullscreen; // Notify renderer of the html fullscreen change. web_contents() ->GetRenderViewHost() ->GetWidget() ->SynchronizeVisualProperties(); // The embedder WebContents is separated from the frame tree of webview, so // we must manually sync their fullscreen states. if (embedder_) embedder_->SetHtmlApiFullscreen(fullscreen); if (fullscreen) { Emit("enter-html-full-screen"); owner_window_->NotifyWindowEnterHtmlFullScreen(); } else { Emit("leave-html-full-screen"); owner_window_->NotifyWindowLeaveHtmlFullScreen(); } // Make sure all child webviews quit html fullscreen. if (!fullscreen && !IsGuest()) { auto* manager = WebViewManager::GetWebViewManager(web_contents()); manager->ForEachGuest( web_contents(), base::BindRepeating([](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); api_web_contents->SetHtmlApiFullscreen(false); return false; })); } } // static v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = "WebContents"; templ->Set( gin::StringToSymbol(isolate, "isDestroyed"), gin::CreateFunctionTemplate( isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed), options)); // We use gin_helper::ObjectTemplateBuilder instead of // gin::ObjectTemplateBuilder here to handle the fact that WebContents is // destroyable. return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("getBackgroundThrottling", &WebContents::GetBackgroundThrottling) .SetMethod("setBackgroundThrottling", &WebContents::SetBackgroundThrottling) .SetMethod("getProcessId", &WebContents::GetProcessID) .SetMethod("getOSProcessId", &WebContents::GetOSProcessID) .SetMethod("equal", &WebContents::Equal) .SetMethod("_loadURL", &WebContents::LoadURL) .SetMethod("reload", &WebContents::Reload) .SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache) .SetMethod("downloadURL", &WebContents::DownloadURL) .SetMethod("getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) .SetMethod("stop", &WebContents::Stop) .SetMethod("canGoBack", &WebContents::CanGoBack) .SetMethod("goBack", &WebContents::GoBack) .SetMethod("canGoForward", &WebContents::CanGoForward) .SetMethod("goForward", &WebContents::GoForward) .SetMethod("canGoToOffset", &WebContents::CanGoToOffset) .SetMethod("goToOffset", &WebContents::GoToOffset) .SetMethod("canGoToIndex", &WebContents::CanGoToIndex) .SetMethod("goToIndex", &WebContents::GoToIndex) .SetMethod("getActiveIndex", &WebContents::GetActiveIndex) .SetMethod("clearHistory", &WebContents::ClearHistory) .SetMethod("length", &WebContents::GetHistoryLength) .SetMethod("isCrashed", &WebContents::IsCrashed) .SetMethod("forcefullyCrashRenderer", &WebContents::ForcefullyCrashRenderer) .SetMethod("setUserAgent", &WebContents::SetUserAgent) .SetMethod("getUserAgent", &WebContents::GetUserAgent) .SetMethod("savePage", &WebContents::SavePage) .SetMethod("openDevTools", &WebContents::OpenDevTools) .SetMethod("closeDevTools", &WebContents::CloseDevTools) .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened) .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused) .SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation) .SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation) .SetMethod("toggleDevTools", &WebContents::ToggleDevTools) .SetMethod("inspectElement", &WebContents::InspectElement) .SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts) .SetMethod("setAudioMuted", &WebContents::SetAudioMuted) .SetMethod("isAudioMuted", &WebContents::IsAudioMuted) .SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible) .SetMethod("undo", &WebContents::Undo) .SetMethod("redo", &WebContents::Redo) .SetMethod("cut", &WebContents::Cut) .SetMethod("copy", &WebContents::Copy) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("replace", &WebContents::Replace) .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling) .SetMethod("findInPage", &WebContents::FindInPage) .SetMethod("stopFindInPage", &WebContents::StopFindInPage) .SetMethod("focus", &WebContents::Focus) .SetMethod("isFocused", &WebContents::IsFocused) .SetMethod("sendInputEvent", &WebContents::SendInputEvent) .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("startDrag", &WebContents::StartDrag) .SetMethod("attachToIframe", &WebContents::AttachToIframe) .SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame) .SetMethod("isOffscreen", &WebContents::IsOffScreen) #if BUILDFLAG(ENABLE_OSR) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) #endif .SetMethod("invalidate", &WebContents::Invalidate) .SetMethod("setZoomLevel", &WebContents::SetZoomLevel) .SetMethod("getZoomLevel", &WebContents::GetZoomLevel) .SetMethod("setZoomFactor", &WebContents::SetZoomFactor) .SetMethod("getZoomFactor", &WebContents::GetZoomFactor) .SetMethod("getType", &WebContents::GetType) .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths) .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker) .SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker) .SetMethod("inspectSharedWorkerById", &WebContents::InspectSharedWorkerById) .SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers) #if BUILDFLAG(ENABLE_PRINTING) .SetMethod("_print", &WebContents::Print) .SetMethod("_printToPDF", &WebContents::PrintToPDF) #endif .SetMethod("_setNextChildWebPreferences", &WebContents::SetNextChildWebPreferences) .SetMethod("addWorkSpace", &WebContents::AddWorkSpace) .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("showDefinitionForSelection", &WebContents::ShowDefinitionForSelection) .SetMethod("copyImageAt", &WebContents::CopyImageAt) .SetMethod("capturePage", &WebContents::CapturePage) .SetMethod("setEmbedder", &WebContents::SetEmbedder) .SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents) .SetMethod("getNativeView", &WebContents::GetNativeView) .SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount) .SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount) .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot) .SetMethod("setImageAnimationPolicy", &WebContents::SetImageAnimationPolicy) .SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo) .SetProperty("id", &WebContents::ID) .SetProperty("session", &WebContents::Session) .SetProperty("hostWebContents", &WebContents::HostWebContents) .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents) .SetProperty("debugger", &WebContents::Debugger) .SetProperty("mainFrame", &WebContents::MainFrame) .Build(); } const char* WebContents::GetTypeName() { return "WebContents"; } ElectronBrowserContext* WebContents::GetBrowserContext() const { return static_cast<ElectronBrowserContext*>( web_contents()->GetBrowserContext()); } // static gin::Handle<WebContents> WebContents::New( v8::Isolate* isolate, const gin_helper::Dictionary& options) { gin::Handle<WebContents> handle = gin::CreateHandle(isolate, new WebContents(isolate, options)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static gin::Handle<WebContents> WebContents::CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) { gin::Handle<WebContents> handle = gin::CreateHandle( isolate, new WebContents(isolate, std::move(web_contents), type)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static WebContents* WebContents::From(content::WebContents* web_contents) { if (!web_contents) return nullptr; auto* data = static_cast<UserDataLink*>( web_contents->GetUserData(kElectronApiWebContentsKey)); return data ? data->web_contents.get() : nullptr; } // static gin::Handle<WebContents> WebContents::FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents) { WebContents* api_web_contents = From(web_contents); if (!api_web_contents) { api_web_contents = new WebContents(isolate, web_contents); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, api_web_contents, "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } } return gin::CreateHandle(isolate, api_web_contents); } // static gin::Handle<WebContents> WebContents::CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences) { // Check if webPreferences has |webContents| option. gin::Handle<WebContents> web_contents; if (web_preferences.GetHidden("webContents", &web_contents) && !web_contents.IsEmpty()) { // Set webPreferences from options if using an existing webContents. // These preferences will be used when the webContent launches new // render processes. auto* existing_preferences = WebContentsPreferences::From(web_contents->web_contents()); gin_helper::Dictionary web_preferences_dict; if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(), &web_preferences_dict)) { existing_preferences->SetFromDictionary(web_preferences_dict); absl::optional<SkColor> color = existing_preferences->GetBackgroundColor(); web_contents->web_contents()->SetPageBaseBackgroundColor(color); // Because web preferences don't recognize transparency, // only set rwhv background color if a color exists auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView(); if (rwhv && color.has_value()) SetBackgroundColor(rwhv, color.value()); } } else { // Create one if not. web_contents = WebContents::New(isolate, web_preferences); } return web_contents; } // static WebContents* WebContents::FromID(int32_t id) { return GetAllWebContents().Lookup(id); } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace electron::api namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) { WebContents* contents = WebContents::FromID(id); return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } gin::Handle<WebContents> WebContentsFromDevToolsTargetID( v8::Isolate* isolate, std::string target_id) { auto agent_host = content::DevToolsAgentHost::GetForId(target_id); WebContents* contents = agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr; return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8( v8::Isolate* isolate) { std::vector<gin::Handle<WebContents>> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue())); } return list; } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); dict.SetMethod("fromId", &WebContentsFromID); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
34,129
[Bug]: WCO on Windows occludes dev tools
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4.1 ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Using WCO and frameless windows on Windows, the WCO does not occlude the top right corner of the dev tools when they are placed on the right side. ### Actual Behavior Using WCO and frameless windows on Windows, the WCO occludes the top right corner of the dev tools when they are placed on the right side. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34129
https://github.com/electron/electron/pull/35209
eab7ab2c47c0750359a247450d9c7a41642b3dd1
4d54cadb281cceb9cf8de91773047ea2cc41da5f
2022-05-06T21:42:03Z
c++
2022-08-11T13:16:12Z
docs/api/web-contents.md
# webContents > Render and control web pages. Process: [Main](../glossary.md#main-process) `webContents` is an [EventEmitter][event-emitter]. It is responsible for rendering and controlling a web page and is a property of the [`BrowserWindow`](browser-window.md) object. An example of accessing the `webContents` object: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 1500 }) win.loadURL('http://github.com') const contents = win.webContents console.log(contents) ``` ## Methods These methods can be accessed from the `webContents` module: ```javascript const { webContents } = require('electron') console.log(webContents) ``` ### `webContents.getAllWebContents()` Returns `WebContents[]` - An array of all `WebContents` instances. This will contain web contents for all windows, webviews, opened devtools, and devtools extension background pages. ### `webContents.getFocusedWebContents()` Returns `WebContents` | null - The web contents that is focused in this application, otherwise returns `null`. ### `webContents.fromId(id)` * `id` Integer Returns `WebContents` | undefined - A WebContents instance with the given ID, or `undefined` if there is no WebContents associated with the given ID. ### `webContents.fromDevToolsTargetId(targetId)` * `targetId` string - The Chrome DevTools Protocol [TargetID](https://chromedevtools.github.io/devtools-protocol/tot/Target/#type-TargetID) associated with the WebContents instance. Returns `WebContents` | undefined - A WebContents instance with the given TargetID, or `undefined` if there is no WebContents associated with the given TargetID. When communicating with the [Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/), it can be useful to lookup a WebContents instance based on its assigned TargetID. ```js async function lookupTargetId (browserWindow) { const wc = browserWindow.webContents await wc.debugger.attach('1.3') const { targetInfo } = await wc.debugger.sendCommand('Target.getTargetInfo') const { targetId } = targetInfo const targetWebContents = await webContents.fromDevToolsTargetId(targetId) } ``` ## Class: WebContents > Render and control the contents of a BrowserWindow instance. Process: [Main](../glossary.md#main-process)<br /> _This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ ### Instance Events #### Event: 'did-finish-load' Emitted when the navigation is done, i.e. the spinner of the tab has stopped spinning, and the `onload` event was dispatched. #### Event: 'did-fail-load' Returns: * `event` Event * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer This event is like `did-finish-load` but emitted when the load failed. The full list of error codes and their meaning is available [here](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h). #### Event: 'did-fail-provisional-load' Returns: * `event` Event * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer This event is like `did-fail-load` but emitted when the load was cancelled (e.g. `window.stop()` was invoked). #### Event: 'did-frame-finish-load' Returns: * `event` Event * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when a frame has done navigation. #### Event: 'did-start-loading' Corresponds to the points in time when the spinner of the tab started spinning. #### Event: 'did-stop-loading' Corresponds to the points in time when the spinner of the tab stopped spinning. #### Event: 'dom-ready' Returns: * `event` Event Emitted when the document in the top-level frame is loaded. #### Event: 'page-title-updated' Returns: * `event` Event * `title` string * `explicitSet` boolean Fired when page title is set during navigation. `explicitSet` is false when title is synthesized from file url. #### Event: 'page-favicon-updated' Returns: * `event` Event * `favicons` string[] - Array of URLs. Emitted when page receives favicon urls. #### Event: 'did-create-window' Returns: * `window` BrowserWindow * `details` Object * `url` string - URL for the created window. * `frameName` string - Name given to the created window in the `window.open()` call. * `options` BrowserWindowConstructorOptions - The options used to create the BrowserWindow. They are merged in increasing precedence: parsed options from the `features` string from `window.open()`, security-related webPreferences inherited from the parent, and options given by [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). Unrecognized options are not filtered out. * `referrer` [Referrer](structures/referrer.md) - The referrer that will be passed to the new window. May or may not result in the `Referer` header being sent, depending on the referrer policy. * `postBody` [PostBody](structures/post-body.md) (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be `null`. Only defined when the window is being created by a form that set `target=_blank`. * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window`, `save-to-disk` and `other`. Emitted _after_ successful creation of a window via `window.open` in the renderer. Not emitted if the creation of the window is canceled from [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). See [`window.open()`](window-open.md) for more details and how to use this in conjunction with `webContents.setWindowOpenHandler`. #### Event: 'will-navigate' Returns: * `event` Event * `url` string Emitted when a user or the page wants to start navigation. It can happen when the `window.location` object is changed or a user clicks a link in the page. This event will not emit when the navigation is started programmatically with APIs like `webContents.loadURL` and `webContents.back`. It is also not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. Calling `event.preventDefault()` will prevent the navigation. #### Event: 'did-start-navigation' Returns: * `event` Event * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame (including main) starts navigating. `isInPlace` will be `true` for in-page navigations. #### Event: 'will-redirect' Returns: * `event` Event * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when a server side redirect occurs during navigation. For example a 302 redirect. This event will be emitted after `did-start-navigation` and always before the `did-redirect-navigation` event for the same navigation. Calling `event.preventDefault()` will prevent the navigation (not just the redirect). #### Event: 'did-redirect-navigation' Returns: * `event` Event * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted after a server side redirect occurs during navigation. For example a 302 redirect. This event cannot be prevented, if you want to prevent redirects you should checkout out the `will-redirect` event above. #### Event: 'did-navigate' Returns: * `event` Event * `url` string * `httpResponseCode` Integer - -1 for non HTTP navigations * `httpStatusText` string - empty for non HTTP navigations Emitted when a main frame navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. #### Event: 'did-frame-navigate' Returns: * `event` Event * `url` string * `httpResponseCode` Integer - -1 for non HTTP navigations * `httpStatusText` string - empty for non HTTP navigations, * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. #### Event: 'did-navigate-in-page' Returns: * `event` Event * `url` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when an in-page navigation happened in any frame. When in-page navigation happens, the page URL changes but does not cause navigation outside of the page. Examples of this occurring are when anchor links are clicked or when the DOM `hashchange` event is triggered. #### Event: 'will-prevent-unload' Returns: * `event` Event Emitted when a `beforeunload` event handler is attempting to cancel a page unload. Calling `event.preventDefault()` will ignore the `beforeunload` event handler and allow the page to be unloaded. ```javascript const { BrowserWindow, dialog } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('will-prevent-unload', (event) => { const choice = dialog.showMessageBoxSync(win, { type: 'question', buttons: ['Leave', 'Stay'], title: 'Do you want to leave this site?', message: 'Changes you made may not be saved.', defaultId: 0, cancelId: 1 }) const leave = (choice === 0) if (leave) { event.preventDefault() } }) ``` **Note:** This will be emitted for `BrowserViews` but will _not_ be respected - this is because we have chosen not to tie the `BrowserView` lifecycle to its owning BrowserWindow should one exist per the [specification](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event). #### Event: 'crashed' _Deprecated_ Returns: * `event` Event * `killed` boolean Emitted when the renderer process crashes or is killed. **Deprecated:** This event is superceded by the `render-process-gone` event which contains more information about why the render process disappeared. It isn't always because it crashed. The `killed` boolean can be replaced by checking `reason === 'killed'` when you switch to that event. #### Event: 'render-process-gone' Returns: * `event` Event * `details` Object * `reason` string - The reason the render process is gone. Possible values: * `clean-exit` - Process exited with an exit code of zero * `abnormal-exit` - Process exited with a non-zero exit code * `killed` - Process was sent a SIGTERM or otherwise killed externally * `crashed` - Process crashed * `oom` - Process ran out of memory * `launch-failed` - Process never successfully launched * `integrity-failure` - Windows code integrity checks failed * `exitCode` Integer - The exit code of the process, unless `reason` is `launch-failed`, in which case `exitCode` will be a platform-specific launch failure error code. Emitted when the renderer process unexpectedly disappears. This is normally because it was crashed or killed. #### Event: 'unresponsive' Emitted when the web page becomes unresponsive. #### Event: 'responsive' Emitted when the unresponsive web page becomes responsive again. #### Event: 'plugin-crashed' Returns: * `event` Event * `name` string * `version` string Emitted when a plugin process has crashed. #### Event: 'destroyed' Emitted when `webContents` is destroyed. #### Event: 'before-input-event' Returns: * `event` Event * `input` Object - Input properties. * `type` string - Either `keyUp` or `keyDown`. * `key` string - Equivalent to [KeyboardEvent.key][keyboardevent]. * `code` string - Equivalent to [KeyboardEvent.code][keyboardevent]. * `isAutoRepeat` boolean - Equivalent to [KeyboardEvent.repeat][keyboardevent]. * `isComposing` boolean - Equivalent to [KeyboardEvent.isComposing][keyboardevent]. * `shift` boolean - Equivalent to [KeyboardEvent.shiftKey][keyboardevent]. * `control` boolean - Equivalent to [KeyboardEvent.controlKey][keyboardevent]. * `alt` boolean - Equivalent to [KeyboardEvent.altKey][keyboardevent]. * `meta` boolean - Equivalent to [KeyboardEvent.metaKey][keyboardevent]. * `location` number - Equivalent to [KeyboardEvent.location][keyboardevent]. * `modifiers` string[] - See [InputEvent.modifiers](structures/input-event.md). Emitted before dispatching the `keydown` and `keyup` events in the page. Calling `event.preventDefault` will prevent the page `keydown`/`keyup` events and the menu shortcuts. To only prevent the menu shortcuts, use [`setIgnoreMenuShortcuts`](#contentssetignoremenushortcutsignore): ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('before-input-event', (event, input) => { // For example, only enable application menu keyboard shortcuts when // Ctrl/Cmd are down. win.webContents.setIgnoreMenuShortcuts(!input.control && !input.meta) }) ``` #### Event: 'enter-html-full-screen' Emitted when the window enters a full-screen state triggered by HTML API. #### Event: 'leave-html-full-screen' Emitted when the window leaves a full-screen state triggered by HTML API. #### Event: 'zoom-changed' Returns: * `event` Event * `zoomDirection` string - Can be `in` or `out`. Emitted when the user is requesting to change the zoom level using the mouse wheel. #### Event: 'blur' Emitted when the `WebContents` loses focus. #### Event: 'focus' Emitted when the `WebContents` gains focus. Note that on macOS, having focus means the `WebContents` is the first responder of window, so switching focus between windows would not trigger the `focus` and `blur` events of `WebContents`, as the first responder of each window is not changed. The `focus` and `blur` events of `WebContents` should only be used to detect focus change between different `WebContents` and `BrowserView` in the same window. #### Event: 'devtools-opened' Emitted when DevTools is opened. #### Event: 'devtools-closed' Emitted when DevTools is closed. #### Event: 'devtools-focused' Emitted when DevTools is focused / opened. #### Event: 'certificate-error' Returns: * `event` Event * `url` string * `error` string - The error code. * `certificate` [Certificate](structures/certificate.md) * `callback` Function * `isTrusted` boolean - Indicates whether the certificate can be considered trusted. * `isMainFrame` boolean Emitted when failed to verify the `certificate` for `url`. The usage is the same with [the `certificate-error` event of `app`](app.md#event-certificate-error). #### Event: 'select-client-certificate' Returns: * `event` Event * `url` URL * `certificateList` [Certificate[]](structures/certificate.md) * `callback` Function * `certificate` [Certificate](structures/certificate.md) - Must be a certificate from the given list. Emitted when a client certificate is requested. The usage is the same with [the `select-client-certificate` event of `app`](app.md#event-select-client-certificate). #### Event: 'login' Returns: * `event` Event * `authenticationResponseDetails` Object * `url` URL * `authInfo` Object * `isProxy` boolean * `scheme` string * `host` string * `port` Integer * `realm` string * `callback` Function * `username` string (optional) * `password` string (optional) Emitted when `webContents` wants to do basic auth. The usage is the same with [the `login` event of `app`](app.md#event-login). #### Event: 'found-in-page' Returns: * `event` Event * `result` Object * `requestId` Integer * `activeMatchOrdinal` Integer - Position of the active match. * `matches` Integer - Number of Matches. * `selectionArea` Rectangle - Coordinates of first match region. * `finalUpdate` boolean Emitted when a result is available for [`webContents.findInPage`] request. #### Event: 'media-started-playing' Emitted when media starts playing. #### Event: 'media-paused' Emitted when media is paused or done playing. #### Event: 'did-change-theme-color' Returns: * `event` Event * `color` (string | null) - Theme color is in format of '#rrggbb'. It is `null` when no theme color is set. Emitted when a page's theme color changes. This is usually due to encountering a meta tag: ```html <meta name='theme-color' content='#ff0000'> ``` #### Event: 'update-target-url' Returns: * `event` Event * `url` string Emitted when mouse moves over a link or the keyboard moves the focus to a link. #### Event: 'cursor-changed' Returns: * `event` Event * `type` string * `image` [NativeImage](native-image.md) (optional) * `scale` Float (optional) - scaling factor for the custom cursor. * `size` [Size](structures/size.md) (optional) - the size of the `image`. * `hotspot` [Point](structures/point.md) (optional) - coordinates of the custom cursor's hotspot. Emitted when the cursor's type changes. The `type` parameter can be `default`, `crosshair`, `pointer`, `text`, `wait`, `help`, `e-resize`, `n-resize`, `ne-resize`, `nw-resize`, `s-resize`, `se-resize`, `sw-resize`, `w-resize`, `ns-resize`, `ew-resize`, `nesw-resize`, `nwse-resize`, `col-resize`, `row-resize`, `m-panning`, `e-panning`, `n-panning`, `ne-panning`, `nw-panning`, `s-panning`, `se-panning`, `sw-panning`, `w-panning`, `move`, `vertical-text`, `cell`, `context-menu`, `alias`, `progress`, `nodrop`, `copy`, `none`, `not-allowed`, `zoom-in`, `zoom-out`, `grab`, `grabbing` or `custom`. If the `type` parameter is `custom`, the `image` parameter will hold the custom cursor image in a [`NativeImage`](native-image.md), and `scale`, `size` and `hotspot` will hold additional information about the custom cursor. #### Event: 'context-menu' Returns: * `event` Event * `params` Object * `x` Integer - x coordinate. * `y` Integer - y coordinate. * `frame` WebFrameMain - Frame from which the context menu was invoked. * `linkURL` string - URL of the link that encloses the node the context menu was invoked on. * `linkText` string - Text associated with the link. May be an empty string if the contents of the link are an image. * `pageURL` string - URL of the top level page that the context menu was invoked on. * `frameURL` string - URL of the subframe that the context menu was invoked on. * `srcURL` string - Source URL for the element that the context menu was invoked on. Elements with source URLs are images, audio and video. * `mediaType` string - Type of the node the context menu was invoked on. Can be `none`, `image`, `audio`, `video`, `canvas`, `file` or `plugin`. * `hasImageContents` boolean - Whether the context menu was invoked on an image which has non-empty contents. * `isEditable` boolean - Whether the context is editable. * `selectionText` string - Text of the selection that the context menu was invoked on. * `titleText` string - Title text of the selection that the context menu was invoked on. * `altText` string - Alt text of the selection that the context menu was invoked on. * `suggestedFilename` string - Suggested filename to be used when saving file through 'Save Link As' option of context menu. * `selectionRect` [Rectangle](structures/rectangle.md) - Rect representing the coordinates in the document space of the selection. * `selectionStartOffset` number - Start position of the selection text. * `referrerPolicy` [Referrer](structures/referrer.md) - The referrer policy of the frame on which the menu is invoked. * `misspelledWord` string - The misspelled word under the cursor, if any. * `dictionarySuggestions` string[] - An array of suggested words to show the user to replace the `misspelledWord`. Only available if there is a misspelled word and spellchecker is enabled. * `frameCharset` string - The character encoding of the frame on which the menu was invoked. * `inputFieldType` string - If the context menu was invoked on an input field, the type of that field. Possible values are `none`, `plainText`, `password`, `other`. * `spellcheckEnabled` boolean - If the context is editable, whether or not spellchecking is enabled. * `menuSourceType` string - Input source that invoked the context menu. Can be `none`, `mouse`, `keyboard`, `touch`, `touchMenu`, `longPress`, `longTap`, `touchHandle`, `stylus`, `adjustSelection`, or `adjustSelectionReset`. * `mediaFlags` Object - The flags for the media element the context menu was invoked on. * `inError` boolean - Whether the media element has crashed. * `isPaused` boolean - Whether the media element is paused. * `isMuted` boolean - Whether the media element is muted. * `hasAudio` boolean - Whether the media element has audio. * `isLooping` boolean - Whether the media element is looping. * `isControlsVisible` boolean - Whether the media element's controls are visible. * `canToggleControls` boolean - Whether the media element's controls are toggleable. * `canPrint` boolean - Whether the media element can be printed. * `canSave` boolean - Whether or not the media element can be downloaded. * `canShowPictureInPicture` boolean - Whether the media element can show picture-in-picture. * `isShowingPictureInPicture` boolean - Whether the media element is currently showing picture-in-picture. * `canRotate` boolean - Whether the media element can be rotated. * `canLoop` boolean - Whether the media element can be looped. * `editFlags` Object - These flags indicate whether the renderer believes it is able to perform the corresponding action. * `canUndo` boolean - Whether the renderer believes it can undo. * `canRedo` boolean - Whether the renderer believes it can redo. * `canCut` boolean - Whether the renderer believes it can cut. * `canCopy` boolean - Whether the renderer believes it can copy. * `canPaste` boolean - Whether the renderer believes it can paste. * `canDelete` boolean - Whether the renderer believes it can delete. * `canSelectAll` boolean - Whether the renderer believes it can select all. * `canEditRichly` boolean - Whether the renderer believes it can edit text richly. Emitted when there is a new context menu that needs to be handled. #### Event: 'select-bluetooth-device' Returns: * `event` Event * `devices` [BluetoothDevice[]](structures/bluetooth-device.md) * `callback` Function * `deviceId` string Emitted when bluetooth device needs to be selected on call to `navigator.bluetooth.requestDevice`. To use `navigator.bluetooth` api `webBluetooth` should be enabled. If `event.preventDefault` is not called, first available device will be selected. `callback` should be called with `deviceId` to be selected, passing empty string to `callback` will cancel the request. If no event listener is added for this event, all bluetooth requests will be cancelled. ```javascript const { app, BrowserWindow } = require('electron') let win = null app.commandLine.appendSwitch('enable-experimental-web-platform-features') app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('select-bluetooth-device', (event, deviceList, callback) => { event.preventDefault() const result = deviceList.find((device) => { return device.deviceName === 'test' }) if (!result) { callback('') } else { callback(result.deviceId) } }) }) ``` #### Event: 'paint' Returns: * `event` Event * `dirtyRect` [Rectangle](structures/rectangle.md) * `image` [NativeImage](native-image.md) - The image data of the whole frame. Emitted when a new frame is generated. Only the dirty area is passed in the buffer. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ webPreferences: { offscreen: true } }) win.webContents.on('paint', (event, dirty, image) => { // updateBitmap(dirty, image.getBitmap()) }) win.loadURL('http://github.com') ``` #### Event: 'devtools-reload-page' Emitted when the devtools window instructs the webContents to reload #### Event: 'will-attach-webview' Returns: * `event` Event * `webPreferences` WebPreferences - The web preferences that will be used by the guest page. This object can be modified to adjust the preferences for the guest page. * `params` Record<string, string> - The other `<webview>` parameters such as the `src` URL. This object can be modified to adjust the parameters of the guest page. Emitted when a `<webview>`'s web contents is being attached to this web contents. Calling `event.preventDefault()` will destroy the guest page. This event can be used to configure `webPreferences` for the `webContents` of a `<webview>` before it's loaded, and provides the ability to set settings that can't be set via `<webview>` attributes. #### Event: 'did-attach-webview' Returns: * `event` Event * `webContents` WebContents - The guest web contents that is used by the `<webview>`. Emitted when a `<webview>` has been attached to this web contents. #### Event: 'console-message' Returns: * `event` Event * `level` Integer - The log level, from 0 to 3. In order it matches `verbose`, `info`, `warning` and `error`. * `message` string - The actual console message * `line` Integer - The line number of the source that triggered this console message * `sourceId` string Emitted when the associated window logs a console message. #### Event: 'preload-error' Returns: * `event` Event * `preloadPath` string * `error` Error Emitted when the preload script `preloadPath` throws an unhandled exception `error`. #### Event: 'ipc-message' Returns: * `event` Event * `channel` string * `...args` any[] Emitted when the renderer process sends an asynchronous message via `ipcRenderer.send()`. See also [`webContents.ipc`](#contentsipc-readonly), which provides an [`IpcMain`](ipc-main.md)-like interface for responding to IPC messages specifically from this WebContents. #### Event: 'ipc-message-sync' Returns: * `event` Event * `channel` string * `...args` any[] Emitted when the renderer process sends a synchronous message via `ipcRenderer.sendSync()`. See also [`webContents.ipc`](#contentsipc-readonly), which provides an [`IpcMain`](ipc-main.md)-like interface for responding to IPC messages specifically from this WebContents. #### Event: 'preferred-size-changed' Returns: * `event` Event * `preferredSize` [Size](structures/size.md) - The minimum size needed to contain the layout of the document—without requiring scrolling. Emitted when the `WebContents` preferred size has changed. This event will only be emitted when `enablePreferredSizeMode` is set to `true` in `webPreferences`. #### Event: 'frame-created' Returns: * `event` Event * `details` Object * `frame` WebFrameMain Emitted when the [mainFrame](web-contents.md#contentsmainframe-readonly), an `<iframe>`, or a nested `<iframe>` is loaded within the page. ### Instance Methods #### `contents.loadURL(url[, options])` * `url` string * `options` Object (optional) * `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer url. * `userAgent` string (optional) - A user agent originating the request. * `extraHeaders` string (optional) - Extra headers separated by "\n". * `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional) * `baseURLForDataURL` string (optional) - Base url (with trailing path separator) for files to be loaded by the data url. This is needed only if the specified `url` is a data url and needs to load other files. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). A noop rejection handler is already attached, which avoids unhandled rejection errors. Loads the `url` in the window. The `url` must contain the protocol prefix, e.g. the `http://` or `file://`. If the load should bypass http cache then use the `pragma` header to achieve it. ```javascript const { webContents } = require('electron') const options = { extraHeaders: 'pragma: no-cache\n' } webContents.loadURL('https://github.com', options) ``` #### `contents.loadFile(filePath[, options])` * `filePath` string * `options` Object (optional) * `query` Record<string, string> (optional) - Passed to `url.format()`. * `search` string (optional) - Passed to `url.format()`. * `hash` string (optional) - Passed to `url.format()`. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). Loads the given file in the window, `filePath` should be a path to an HTML file relative to the root of your application. For instance an app structure like this: ```sh | root | - package.json | - src | - main.js | - index.html ``` Would require code like this ```js win.loadFile('src/index.html') ``` #### `contents.downloadURL(url)` * `url` string Initiates a download of the resource at `url` without navigating. The `will-download` event of `session` will be triggered. #### `contents.getURL()` Returns `string` - The URL of the current web page. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('http://github.com').then(() => { const currentURL = win.webContents.getURL() console.log(currentURL) }) ``` #### `contents.getTitle()` Returns `string` - The title of the current web page. #### `contents.isDestroyed()` Returns `boolean` - Whether the web page is destroyed. #### `contents.focus()` Focuses the web page. #### `contents.isFocused()` Returns `boolean` - Whether the web page is focused. #### `contents.isLoading()` Returns `boolean` - Whether web page is still loading resources. #### `contents.isLoadingMainFrame()` Returns `boolean` - Whether the main frame (and not just iframes or frames within it) is still loading. #### `contents.isWaitingForResponse()` Returns `boolean` - Whether the web page is waiting for a first-response from the main resource of the page. #### `contents.stop()` Stops any pending navigation. #### `contents.reload()` Reloads the current web page. #### `contents.reloadIgnoringCache()` Reloads current page and ignores cache. #### `contents.canGoBack()` Returns `boolean` - Whether the browser can go back to previous web page. #### `contents.canGoForward()` Returns `boolean` - Whether the browser can go forward to next web page. #### `contents.canGoToOffset(offset)` * `offset` Integer Returns `boolean` - Whether the web page can go to `offset`. #### `contents.clearHistory()` Clears the navigation history. #### `contents.goBack()` Makes the browser go back a web page. #### `contents.goForward()` Makes the browser go forward a web page. #### `contents.goToIndex(index)` * `index` Integer Navigates browser to the specified absolute web page index. #### `contents.goToOffset(offset)` * `offset` Integer Navigates to the specified offset from the "current entry". #### `contents.isCrashed()` Returns `boolean` - Whether the renderer process has crashed. #### `contents.forcefullyCrashRenderer()` Forcefully terminates the renderer process that is currently hosting this `webContents`. This will cause the `render-process-gone` event to be emitted with the `reason=killed || reason=crashed`. Please note that some webContents share renderer processes and therefore calling this method may also crash the host process for other webContents as well. Calling `reload()` immediately after calling this method will force the reload to occur in a new process. This should be used when this process is unstable or unusable, for instance in order to recover from the `unresponsive` event. ```js contents.on('unresponsive', async () => { const { response } = await dialog.showMessageBox({ message: 'App X has become unresponsive', title: 'Do you want to try forcefully reloading the app?', buttons: ['OK', 'Cancel'], cancelId: 1 }) if (response === 0) { contents.forcefullyCrashRenderer() contents.reload() } }) ``` #### `contents.setUserAgent(userAgent)` * `userAgent` string Overrides the user agent for this web page. #### `contents.getUserAgent()` Returns `string` - The user agent for this web page. #### `contents.insertCSS(css[, options])` * `css` string * `options` Object (optional) * `cssOrigin` string (optional) - Can be either 'user' or 'author'. Sets the [cascade origin](https://www.w3.org/TR/css3-cascade/#cascade-origin) of the inserted stylesheet. Default is 'author'. Returns `Promise<string>` - A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via `contents.removeInsertedCSS(key)`. Injects CSS into the current web page and returns a unique key for the inserted stylesheet. ```js contents.on('did-finish-load', () => { contents.insertCSS('html, body { background-color: #f00; }') }) ``` #### `contents.removeInsertedCSS(key)` * `key` string Returns `Promise<void>` - Resolves if the removal was successful. Removes the inserted CSS from the current web page. The stylesheet is identified by its key, which is returned from `contents.insertCSS(css)`. ```js contents.on('did-finish-load', async () => { const key = await contents.insertCSS('html, body { background-color: #f00; }') contents.removeInsertedCSS(key) }) ``` #### `contents.executeJavaScript(code[, userGesture])` * `code` string * `userGesture` boolean (optional) - Default is `false`. Returns `Promise<any>` - A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise. Evaluates `code` in page. In the browser window some HTML APIs like `requestFullScreen` can only be invoked by a gesture from the user. Setting `userGesture` to `true` will remove this limitation. Code execution will be suspended until web page stop loading. ```js contents.executeJavaScript('fetch("https://jsonplaceholder.typicode.com/users/1").then(resp => resp.json())', true) .then((result) => { console.log(result) // Will be the JSON object from the fetch call }) ``` #### `contents.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture])` * `worldId` Integer - The ID of the world to run the javascript in, `0` is the default world, `999` is the world used by Electron's `contextIsolation` feature. You can provide any integer here. * `scripts` [WebSource[]](structures/web-source.md) * `userGesture` boolean (optional) - Default is `false`. Returns `Promise<any>` - A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise. Works like `executeJavaScript` but evaluates `scripts` in an isolated context. #### `contents.setIgnoreMenuShortcuts(ignore)` * `ignore` boolean Ignore application menu shortcuts while this web contents is focused. #### `contents.setWindowOpenHandler(handler)` * `handler` Function<{action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}> * `details` Object * `url` string - The _resolved_ version of the URL passed to `window.open()`. e.g. opening a window with `window.open('foo')` will yield something like `https://the-origin/the/current/path/foo`. * `frameName` string - Name of the window provided in `window.open()` * `features` string - Comma separated list of window features provided to `window.open()`. * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window`, `save-to-disk` or `other`. * `referrer` [Referrer](structures/referrer.md) - The referrer that will be passed to the new window. May or may not result in the `Referer` header being sent, depending on the referrer policy. * `postBody` [PostBody](structures/post-body.md) (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be `null`. Only defined when the window is being created by a form that set `target=_blank`. Returns `{action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}` - `deny` cancels the creation of the new window. `allow` will allow the new window to be created. Specifying `overrideBrowserWindowOptions` allows customization of the created window. Returning an unrecognized value such as a null, undefined, or an object without a recognized 'action' value will result in a console error and have the same effect as returning `{action: 'deny'}`. Called before creating a window a new window is requested by the renderer, e.g. by `window.open()`, a link with `target="_blank"`, shift+clicking on a link, or submitting a form with `<form target="_blank">`. See [`window.open()`](window-open.md) for more details and how to use this in conjunction with `did-create-window`. #### `contents.setAudioMuted(muted)` * `muted` boolean Mute the audio on the current web page. #### `contents.isAudioMuted()` Returns `boolean` - Whether this page has been muted. #### `contents.isCurrentlyAudible()` Returns `boolean` - Whether audio is currently playing. #### `contents.setZoomFactor(factor)` * `factor` Double - Zoom factor; default is 1.0. Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0. The factor must be greater than 0.0. #### `contents.getZoomFactor()` Returns `number` - the current zoom factor. #### `contents.setZoomLevel(level)` * `level` number - Zoom level. Changes the zoom level to the specified level. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`. > **NOTE**: The zoom policy at the Chromium level is same-origin, meaning that the > zoom level for a specific domain propagates across all instances of windows with > the same domain. Differentiating the window URLs will make zoom work per-window. #### `contents.getZoomLevel()` Returns `number` - the current zoom level. #### `contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)` * `minimumLevel` number * `maximumLevel` number Returns `Promise<void>` Sets the maximum and minimum pinch-to-zoom level. > **NOTE**: Visual zoom is disabled by default in Electron. To re-enable it, call: > > ```js > contents.setVisualZoomLevelLimits(1, 3) > ``` #### `contents.undo()` Executes the editing command `undo` in web page. #### `contents.redo()` Executes the editing command `redo` in web page. #### `contents.cut()` Executes the editing command `cut` in web page. #### `contents.copy()` Executes the editing command `copy` in web page. #### `contents.copyImageAt(x, y)` * `x` Integer * `y` Integer Copy the image at the given position to the clipboard. #### `contents.paste()` Executes the editing command `paste` in web page. #### `contents.pasteAndMatchStyle()` Executes the editing command `pasteAndMatchStyle` in web page. #### `contents.delete()` Executes the editing command `delete` in web page. #### `contents.selectAll()` Executes the editing command `selectAll` in web page. #### `contents.unselect()` Executes the editing command `unselect` in web page. #### `contents.replace(text)` * `text` string Executes the editing command `replace` in web page. #### `contents.replaceMisspelling(text)` * `text` string Executes the editing command `replaceMisspelling` in web page. #### `contents.insertText(text)` * `text` string Returns `Promise<void>` Inserts `text` to the focused element. #### `contents.findInPage(text[, options])` * `text` string - Content to be searched, must not be empty. * `options` Object (optional) * `forward` boolean (optional) - Whether to search forward or backward, defaults to `true`. * `findNext` boolean (optional) - Whether to begin a new text finding session with this request. Should be `true` for initial requests, and `false` for follow-up requests. Defaults to `false`. * `matchCase` boolean (optional) - Whether search should be case-sensitive, defaults to `false`. Returns `Integer` - The request id used for the request. Starts a request to find all matches for the `text` in the web page. The result of the request can be obtained by subscribing to [`found-in-page`](web-contents.md#event-found-in-page) event. #### `contents.stopFindInPage(action)` * `action` string - Specifies the action to take place when ending [`webContents.findInPage`] request. * `clearSelection` - Clear the selection. * `keepSelection` - Translate the selection into a normal selection. * `activateSelection` - Focus and click the selection node. Stops any `findInPage` request for the `webContents` with the provided `action`. ```javascript const { webContents } = require('electron') webContents.on('found-in-page', (event, result) => { if (result.finalUpdate) webContents.stopFindInPage('clearSelection') }) const requestId = webContents.findInPage('api') console.log(requestId) ``` #### `contents.capturePage([rect])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured. Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md) Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. #### `contents.isBeingCaptured()` Returns `boolean` - Whether this page is being captured. It returns true when the capturer count is large then 0. #### `contents.incrementCapturerCount([size, stayHidden, stayAwake])` * `size` [Size](structures/size.md) (optional) - The preferred size for the capturer. * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Increase the capturer count by one. The page is considered visible when its browser window is hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true. This also affects the Page Visibility API. #### `contents.decrementCapturerCount([stayHidden, stayAwake])` * `stayHidden` boolean (optional) - Keep the page in hidden state instead of visible. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Decrease the capturer count by one. The page will be set to hidden or occluded state when its browser window is hidden or occluded and the capturer count reaches zero. If you want to decrease the hidden capturer count instead you should set `stayHidden` to true. #### `contents.getPrinters()` _Deprecated_ Get the system printer list. Returns [`PrinterInfo[]`](structures/printer-info.md) **Deprecated:** Should use the new [`contents.getPrintersAsync`](web-contents.md#contentsgetprintersasync) API. #### `contents.getPrintersAsync()` Get the system printer list. Returns `Promise<PrinterInfo[]>` - Resolves with a [`PrinterInfo[]`](structures/printer-info.md) #### `contents.print([options], [callback])` * `options` Object (optional) * `silent` boolean (optional) - Don't ask user for print settings. Default is `false`. * `printBackground` boolean (optional) - Prints the background color and image of the web page. Default is `false`. * `deviceName` string (optional) - Set the printer device name to use. Must be the system-defined name and not the 'friendly' name, e.g 'Brother_QL_820NWB' and not 'Brother QL-820NWB'. * `color` boolean (optional) - Set whether the printed web page will be in color or grayscale. Default is `true`. * `margins` Object (optional) * `marginType` string (optional) - Can be `default`, `none`, `printableArea`, or `custom`. If `custom` is chosen, you will also need to specify `top`, `bottom`, `left`, and `right`. * `top` number (optional) - The top margin of the printed web page, in pixels. * `bottom` number (optional) - The bottom margin of the printed web page, in pixels. * `left` number (optional) - The left margin of the printed web page, in pixels. * `right` number (optional) - The right margin of the printed web page, in pixels. * `landscape` boolean (optional) - Whether the web page should be printed in landscape mode. Default is `false`. * `scaleFactor` number (optional) - The scale factor of the web page. * `pagesPerSheet` number (optional) - The number of pages to print per page sheet. * `collate` boolean (optional) - Whether the web page should be collated. * `copies` number (optional) - The number of copies of the web page to print. * `pageRanges` Object[] (optional) - The page range to print. On macOS, only one range is honored. * `from` number - Index of the first page to print (0-based). * `to` number - Index of the last page to print (inclusive) (0-based). * `duplexMode` string (optional) - Set the duplex mode of the printed web page. Can be `simplex`, `shortEdge`, or `longEdge`. * `dpi` Record<string, number> (optional) * `horizontal` number (optional) - The horizontal dpi. * `vertical` number (optional) - The vertical dpi. * `header` string (optional) - string to be printed as page header. * `footer` string (optional) - string to be printed as page footer. * `pageSize` string | Size (optional) - Specify page size of the printed document. Can be `A3`, `A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` and `width`. * `callback` Function (optional) * `success` boolean - Indicates success of the print call. * `failureReason` string - Error description called back if the print fails. When a custom `pageSize` is passed, Chromium attempts to validate platform specific minimum values for `width_microns` and `height_microns`. Width and height must both be minimum 353 microns but may be higher on some operating systems. Prints window's web page. When `silent` is set to `true`, Electron will pick the system's default printer if `deviceName` is empty and the default settings for printing. Use `page-break-before: always;` CSS style to force to print to a new page. Example usage: ```js const options = { silent: true, deviceName: 'My-Printer', pageRanges: [{ from: 0, to: 1 }] } win.webContents.print(options, (success, errorType) => { if (!success) console.log(errorType) }) ``` #### `contents.printToPDF(options)` * `options` Object * `landscape` boolean (optional) - Paper orientation.`true` for landscape, `false` for portrait. Defaults to false. * `displayHeaderFooter` boolean (optional) - Whether to display header and footer. Defaults to false. * `printBackground` boolean (optional) - Whether to print background graphics. Defaults to false. * `scale` number(optional) - Scale of the webpage rendering. Defaults to 1. * `pageSize` string | Size (optional) - Specify page size of the generated PDF. Can be `A0`, `A1`, `A2`, `A3`, `A4`, `A5`, `A6`, `Legal`, `Letter`, `Tabloid`, `Ledger`, or an Object containing `height` and `width` in inches. Defaults to `Letter`. * `margins` Object (optional) * `top` number (optional) - Top margin in inches. Defaults to 1cm (~0.4 inches). * `bottom` number (optional) - Bottom margin in inches. Defaults to 1cm (~0.4 inches). * `left` number (optional) - Left margin in inches. Defaults to 1cm (~0.4 inches). * `right` number (optional) - Right margin in inches. Defaults to 1cm (~0.4 inches). * `pageRanges` string (optional) - Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages. * `headerTemplate` string (optional) - HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: `date` (formatted print date), `title` (document title), `url` (document location), `pageNumber` (current page number) and `totalPages` (total pages in the document). For example, `<span class=title></span>` would generate span containing the title. * `footerTemplate` string (optional) - HTML template for the print footer. Should use the same format as the `headerTemplate`. * `preferCSSPageSize` boolean (optional) - Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size. Returns `Promise<Buffer>` - Resolves with the generated PDF data. Prints the window's web page as PDF. The `landscape` will be ignored if `@page` CSS at-rule is used in the web page. An example of `webContents.printToPDF`: ```javascript const { BrowserWindow } = require('electron') const fs = require('fs') const path = require('path') const os = require('os') const win = new BrowserWindow() win.loadURL('http://github.com') win.webContents.on('did-finish-load', () => { // Use default printing options const pdfPath = path.join(os.homedir(), 'Desktop', 'temp.pdf') win.webContents.printToPDF({}).then(data => { fs.writeFile(pdfPath, data, (error) => { if (error) throw error console.log(`Wrote PDF successfully to ${pdfPath}`) }) }).catch(error => { console.log(`Failed to write PDF to ${pdfPath}: `, error) }) }) ``` See [Page.printToPdf](https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF) for more information. #### `contents.addWorkSpace(path)` * `path` string Adds the specified path to DevTools workspace. Must be used after DevTools creation: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.webContents.on('devtools-opened', () => { win.webContents.addWorkSpace(__dirname) }) ``` #### `contents.removeWorkSpace(path)` * `path` string Removes the specified path from DevTools workspace. #### `contents.setDevToolsWebContents(devToolsWebContents)` * `devToolsWebContents` WebContents Uses the `devToolsWebContents` as the target `WebContents` to show devtools. The `devToolsWebContents` must not have done any navigation, and it should not be used for other purposes after the call. By default Electron manages the devtools by creating an internal `WebContents` with native view, which developers have very limited control of. With the `setDevToolsWebContents` method, developers can use any `WebContents` to show the devtools in it, including `BrowserWindow`, `BrowserView` and `<webview>` tag. Note that closing the devtools does not destroy the `devToolsWebContents`, it is caller's responsibility to destroy `devToolsWebContents`. An example of showing devtools in a `<webview>` tag: ```html <html> <head> <style type="text/css"> * { margin: 0; } #browser { height: 70%; } #devtools { height: 30%; } </style> </head> <body> <webview id="browser" src="https://github.com"></webview> <webview id="devtools" src="about:blank"></webview> <script> const { ipcRenderer } = require('electron') const emittedOnce = (element, eventName) => new Promise(resolve => { element.addEventListener(eventName, event => resolve(event), { once: true }) }) const browserView = document.getElementById('browser') const devtoolsView = document.getElementById('devtools') const browserReady = emittedOnce(browserView, 'dom-ready') const devtoolsReady = emittedOnce(devtoolsView, 'dom-ready') Promise.all([browserReady, devtoolsReady]).then(() => { const targetId = browserView.getWebContentsId() const devtoolsId = devtoolsView.getWebContentsId() ipcRenderer.send('open-devtools', targetId, devtoolsId) }) </script> </body> </html> ``` ```js // Main process const { ipcMain, webContents } = require('electron') ipcMain.on('open-devtools', (event, targetContentsId, devtoolsContentsId) => { const target = webContents.fromId(targetContentsId) const devtools = webContents.fromId(devtoolsContentsId) target.setDevToolsWebContents(devtools) target.openDevTools() }) ``` An example of showing devtools in a `BrowserWindow`: ```js const { app, BrowserWindow } = require('electron') let win = null let devtools = null app.whenReady().then(() => { win = new BrowserWindow() devtools = new BrowserWindow() win.loadURL('https://github.com') win.webContents.setDevToolsWebContents(devtools.webContents) win.webContents.openDevTools({ mode: 'detach' }) }) ``` #### `contents.openDevTools([options])` * `options` Object (optional) * `mode` string - Opens the devtools with specified dock state, can be `left`, `right`, `bottom`, `undocked`, `detach`. Defaults to last used dock state. In `undocked` mode it's possible to dock back. In `detach` mode it's not. * `activate` boolean (optional) - Whether to bring the opened devtools window to the foreground. The default is `true`. Opens the devtools. When `contents` is a `<webview>` tag, the `mode` would be `detach` by default, explicitly passing an empty `mode` can force using last used dock state. #### `contents.closeDevTools()` Closes the devtools. #### `contents.isDevToolsOpened()` Returns `boolean` - Whether the devtools is opened. #### `contents.isDevToolsFocused()` Returns `boolean` - Whether the devtools view is focused . #### `contents.toggleDevTools()` Toggles the developer tools. #### `contents.inspectElement(x, y)` * `x` Integer * `y` Integer Starts inspecting element at position (`x`, `y`). #### `contents.inspectSharedWorker()` Opens the developer tools for the shared worker context. #### `contents.inspectSharedWorkerById(workerId)` * `workerId` string Inspects the shared worker based on its ID. #### `contents.getAllSharedWorkers()` Returns [`SharedWorkerInfo[]`](structures/shared-worker-info.md) - Information about all Shared Workers. #### `contents.inspectServiceWorker()` Opens the developer tools for the service worker context. #### `contents.send(channel, ...args)` * `channel` string * `...args` any[] Send an asynchronous message to the renderer process via `channel`, along with arguments. Arguments will be serialized with the [Structured Clone Algorithm][SCA], just like [`postMessage`][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. > **NOTE**: Sending non-standard JavaScript types such as DOM objects or > special Electron objects will throw an exception. The renderer process can handle the message by listening to `channel` with the [`ipcRenderer`](ipc-renderer.md) module. An example of sending messages from the main process to the renderer process: ```javascript // In the main process. const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL(`file://${__dirname}/index.html`) win.webContents.on('did-finish-load', () => { win.webContents.send('ping', 'whoooooooh!') }) }) ``` ```html <!-- index.html --> <html> <body> <script> require('electron').ipcRenderer.on('ping', (event, message) => { console.log(message) // Prints 'whoooooooh!' }) </script> </body> </html> ``` #### `contents.sendToFrame(frameId, channel, ...args)` * `frameId` Integer | [number, number] - the ID of the frame to send to, or a pair of `[processId, frameId]` if the frame is in a different process to the main frame. * `channel` string * `...args` any[] Send an asynchronous message to a specific frame in a renderer process via `channel`, along with arguments. Arguments will be serialized with the [Structured Clone Algorithm][SCA], just like [`postMessage`][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. > **NOTE:** Sending non-standard JavaScript types such as DOM objects or > special Electron objects will throw an exception. The renderer process can handle the message by listening to `channel` with the [`ipcRenderer`](ipc-renderer.md) module. If you want to get the `frameId` of a given renderer context you should use the `webFrame.routingId` value. E.g. ```js // In a renderer process console.log('My frameId is:', require('electron').webFrame.routingId) ``` You can also read `frameId` from all incoming IPC messages in the main process. ```js // In the main process ipcMain.on('ping', (event) => { console.info('Message came from frameId:', event.frameId) }) ``` #### `contents.postMessage(channel, message, [transfer])` * `channel` string * `message` any * `transfer` MessagePortMain[] (optional) Send a message to the renderer process, optionally transferring ownership of zero or more [`MessagePortMain`][] objects. The transferred `MessagePortMain` objects will be available in the renderer process by accessing the `ports` property of the emitted event. When they arrive in the renderer, they will be native DOM `MessagePort` objects. For example: ```js // Main process const { port1, port2 } = new MessageChannelMain() webContents.postMessage('port', { message: 'hello' }, [port1]) // Renderer process ipcRenderer.on('port', (e, msg) => { const [port] = e.ports // ... }) ``` #### `contents.enableDeviceEmulation(parameters)` * `parameters` Object * `screenPosition` string - Specify the screen type to emulate (default: `desktop`): * `desktop` - Desktop screen type. * `mobile` - Mobile screen type. * `screenSize` [Size](structures/size.md) - Set the emulated screen size (screenPosition == mobile). * `viewPosition` [Point](structures/point.md) - Position the view on the screen (screenPosition == mobile) (default: `{ x: 0, y: 0 }`). * `deviceScaleFactor` Integer - Set the device scale factor (if zero defaults to original device scale factor) (default: `0`). * `viewSize` [Size](structures/size.md) - Set the emulated view size (empty means no override) * `scale` Float - Scale of emulated view inside available space (not in fit to view mode) (default: `1`). Enable device emulation with the given parameters. #### `contents.disableDeviceEmulation()` Disable device emulation enabled by `webContents.enableDeviceEmulation`. #### `contents.sendInputEvent(inputEvent)` * `inputEvent` [MouseInputEvent](structures/mouse-input-event.md) | [MouseWheelInputEvent](structures/mouse-wheel-input-event.md) | [KeyboardInputEvent](structures/keyboard-input-event.md) Sends an input `event` to the page. **Note:** The [`BrowserWindow`](browser-window.md) containing the contents needs to be focused for `sendInputEvent()` to work. #### `contents.beginFrameSubscription([onlyDirty ,]callback)` * `onlyDirty` boolean (optional) - Defaults to `false`. * `callback` Function * `image` [NativeImage](native-image.md) * `dirtyRect` [Rectangle](structures/rectangle.md) Begin subscribing for presentation events and captured frames, the `callback` will be called with `callback(image, dirtyRect)` when there is a presentation event. The `image` is an instance of [NativeImage](native-image.md) that stores the captured frame. The `dirtyRect` is an object with `x, y, width, height` properties that describes which part of the page was repainted. If `onlyDirty` is set to `true`, `image` will only contain the repainted area. `onlyDirty` defaults to `false`. #### `contents.endFrameSubscription()` End subscribing for frame presentation events. #### `contents.startDrag(item)` * `item` Object * `file` string - The path to the file being dragged. * `files` string[] (optional) - The paths to the files being dragged. (`files` will override `file` field) * `icon` [NativeImage](native-image.md) | string - The image must be non-empty on macOS. Sets the `item` as dragging item for current drag-drop operation, `file` is the absolute path of the file to be dragged, and `icon` is the image showing under the cursor when dragging. #### `contents.savePage(fullPath, saveType)` * `fullPath` string - The absolute file path. * `saveType` string - Specify the save type. * `HTMLOnly` - Save only the HTML of the page. * `HTMLComplete` - Save complete-html page. * `MHTML` - Save complete-html page as MHTML. Returns `Promise<void>` - resolves if the page is saved. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.loadURL('https://github.com') win.webContents.on('did-finish-load', async () => { win.webContents.savePage('/tmp/test.html', 'HTMLComplete').then(() => { console.log('Page was saved successfully.') }).catch(err => { console.log(err) }) }) ``` #### `contents.showDefinitionForSelection()` _macOS_ Shows pop-up dictionary that searches the selected word on the page. #### `contents.isOffscreen()` Returns `boolean` - Indicates whether *offscreen rendering* is enabled. #### `contents.startPainting()` If *offscreen rendering* is enabled and not painting, start painting. #### `contents.stopPainting()` If *offscreen rendering* is enabled and painting, stop painting. #### `contents.isPainting()` Returns `boolean` - If *offscreen rendering* is enabled returns whether it is currently painting. #### `contents.setFrameRate(fps)` * `fps` Integer If *offscreen rendering* is enabled sets the frame rate to the specified number. Only values between 1 and 240 are accepted. #### `contents.getFrameRate()` Returns `Integer` - If *offscreen rendering* is enabled returns the current frame rate. #### `contents.invalidate()` Schedules a full repaint of the window this web contents is in. If *offscreen rendering* is enabled invalidates the frame and generates a new one through the `'paint'` event. #### `contents.getWebRTCIPHandlingPolicy()` Returns `string` - Returns the WebRTC IP Handling Policy. #### `contents.setWebRTCIPHandlingPolicy(policy)` * `policy` string - Specify the WebRTC IP Handling Policy. * `default` - Exposes user's public and local IPs. This is the default behavior. When this policy is used, WebRTC has the right to enumerate all interfaces and bind them to discover public interfaces. * `default_public_interface_only` - Exposes user's public IP, but does not expose user's local IP. When this policy is used, WebRTC should only use the default route used by http. This doesn't expose any local addresses. * `default_public_and_private_interfaces` - Exposes user's public and local IPs. When this policy is used, WebRTC should only use the default route used by http. This also exposes the associated default private address. Default route is the route chosen by the OS on a multi-homed endpoint. * `disable_non_proxied_udp` - Does not expose public or local IPs. When this policy is used, WebRTC should only use TCP to contact peers or servers unless the proxy server supports UDP. Setting the WebRTC IP handling policy allows you to control which IPs are exposed via WebRTC. See [BrowserLeaks](https://browserleaks.com/webrtc) for more details. #### `contents.getMediaSourceId(requestWebContents)` * `requestWebContents` WebContents - Web contents that the id will be registered to. Returns `string` - The identifier of a WebContents stream. This identifier can be used with `navigator.mediaDevices.getUserMedia` using a `chromeMediaSource` of `tab`. The identifier is restricted to the web contents that it is registered to and is only valid for 10 seconds. #### `contents.getOSProcessId()` Returns `Integer` - The operating system `pid` of the associated renderer process. #### `contents.getProcessId()` Returns `Integer` - The Chromium internal `pid` of the associated renderer. Can be compared to the `frameProcessId` passed by frame specific navigation events (e.g. `did-frame-navigate`) #### `contents.takeHeapSnapshot(filePath)` * `filePath` string - Path to the output file. Returns `Promise<void>` - Indicates whether the snapshot has been created successfully. Takes a V8 heap snapshot and saves it to `filePath`. #### `contents.getBackgroundThrottling()` Returns `boolean` - whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.setBackgroundThrottling(allowed)` * `allowed` boolean Controls whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.getType()` Returns `string` - the type of the webContent. Can be `backgroundPage`, `window`, `browserView`, `remote`, `webview` or `offscreen`. #### `contents.setImageAnimationPolicy(policy)` * `policy` string - Can be `animate`, `animateOnce` or `noAnimation`. Sets the image animation policy for this webContents. The policy only affects _new_ images, existing images that are currently being animated are unaffected. This is a known limitation in Chromium, you can force image animation to be recalculated with `img.src = img.src` which will result in no network traffic but will update the animation policy. This corresponds to the [animationPolicy][] accessibility feature in Chromium. [animationPolicy]: https://developer.chrome.com/docs/extensions/reference/accessibilityFeatures/#property-animationPolicy ### Instance Properties #### `contents.ipc` _Readonly_ An [`IpcMain`](ipc-main.md) scoped to just IPC messages sent from this WebContents. IPC messages sent with `ipcRenderer.send`, `ipcRenderer.sendSync` or `ipcRenderer.postMessage` will be delivered in the following order: 1. `contents.on('ipc-message')` 2. `contents.mainFrame.on(channel)` 3. `contents.ipc.on(channel)` 4. `ipcMain.on(channel)` Handlers registered with `invoke` will be checked in the following order. The first one that is defined will be called, the rest will be ignored. 1. `contents.mainFrame.handle(channel)` 2. `contents.handle(channel)` 3. `ipcMain.handle(channel)` A handler or event listener registered on the WebContents will receive IPC messages sent from any frame, including child frames. In most cases, only the main frame can send IPC messages. However, if the `nodeIntegrationInSubFrames` option is enabled, it is possible for child frames to send IPC messages also. In that case, handlers should check the `senderFrame` property of the IPC event to ensure that the message is coming from the expected frame. Alternatively, register handlers on the appropriate frame directly using the [`WebFrameMain.ipc`](web-frame-main.md#frameipc-readonly) interface. #### `contents.audioMuted` A `boolean` property that determines whether this page is muted. #### `contents.userAgent` A `string` property that determines the user agent for this web page. #### `contents.zoomLevel` A `number` property that determines the zoom level for this web contents. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`. #### `contents.zoomFactor` A `number` property that determines the zoom factor for this web contents. The zoom factor is the zoom percent divided by 100, so 300% = 3.0. #### `contents.frameRate` An `Integer` property that sets the frame rate of the web contents to the specified number. Only values between 1 and 240 are accepted. Only applicable if *offscreen rendering* is enabled. #### `contents.id` _Readonly_ A `Integer` representing the unique ID of this WebContents. Each ID is unique among all `WebContents` instances of the entire Electron application. #### `contents.session` _Readonly_ A [`Session`](session.md) used by this webContents. #### `contents.hostWebContents` _Readonly_ A [`WebContents`](web-contents.md) instance that might own this `WebContents`. #### `contents.devToolsWebContents` _Readonly_ A `WebContents | null` property that represents the of DevTools `WebContents` associated with a given `WebContents`. **Note:** Users should never store this object because it may become `null` when the DevTools has been closed. #### `contents.debugger` _Readonly_ A [`Debugger`](debugger.md) instance for this webContents. #### `contents.backgroundThrottling` A `boolean` property that determines whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.mainFrame` _Readonly_ A [`WebFrameMain`](web-frame-main.md) property that represents the top frame of the page's frame hierarchy. [keyboardevent]: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter [SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm [`postMessage`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
closed
electron/electron
https://github.com/electron/electron
34,129
[Bug]: WCO on Windows occludes dev tools
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4.1 ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Using WCO and frameless windows on Windows, the WCO does not occlude the top right corner of the dev tools when they are placed on the right side. ### Actual Behavior Using WCO and frameless windows on Windows, the WCO occludes the top right corner of the dev tools when they are placed on the right side. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34129
https://github.com/electron/electron/pull/35209
eab7ab2c47c0750359a247450d9c7a41642b3dd1
4d54cadb281cceb9cf8de91773047ea2cc41da5f
2022-05-06T21:42:03Z
c++
2022-08-11T13:16:12Z
shell/browser/api/electron_api_web_contents.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_web_contents.h" #include <limits> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/containers/id_map.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/no_destructor.h" #include "base/strings/utf_string_conversions.h" #include "base/task/current_thread.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/views/eye_dropper/eye_dropper.h" #include "chrome/common/pref_names.h" #include "components/embedder_support/user_agent_utils.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/security_state/content/content_utils.h" #include "components/security_state/core/security_state.h" #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck #include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/context_menu_params.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/desktop_streams_registry.h" #include "content/public/browser/download_request_utils.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/service_worker_context.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/referrer_type_converters.h" #include "content/public/common/webplugininfo.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/arguments.h" #include "gin/data_object_builder.h" #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/system/platform_handle.h" #include "ppapi/buildflags/buildflags.h" #include "printing/buildflags/buildflags.h" #include "printing/print_job_constants.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "shell/browser/api/electron_api_browser_window.h" #include "shell/browser/api/electron_api_debugger.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/api/electron_api_web_frame_main.h" #include "shell/browser/api/message_port.h" #include "shell/browser/browser.h" #include "shell/browser/child_web_contents_tracker.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_javascript_dialog_manager.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/file_select_helper.h" #include "shell/browser/native_window.h" #include "shell/browser/session_preferences.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_contents_zoom_controller.h" #include "shell/browser/web_view_guest_delegate.h" #include "shell/browser/web_view_manager.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/color_util.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/base_converter.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/content_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/net_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/language_util.h" #include "shell/common/mouse_util.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "shell/common/v8_value_serializer.h" #include "storage/browser/file_system/isolated_context.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "third_party/blink/public/mojom/frame/find_in_page.mojom.h" #include "third_party/blink/public/mojom/frame/fullscreen.mojom.h" #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" #include "third_party/blink/public/mojom/renderer_preferences.mojom.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/display/screen.h" #include "ui/events/base_event_utils.h" #if BUILDFLAG(ENABLE_OSR) #include "shell/browser/osr/osr_render_widget_host_view.h" #include "shell/browser/osr/osr_web_contents_view.h" #endif #if !BUILDFLAG(IS_MAC) #include "ui/aura/window.h" #else #include "ui/base/cocoa/defaults_utils.h" #endif #if BUILDFLAG(IS_LINUX) #include "ui/linux/linux_ui.h" #endif #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) #include "ui/gfx/font_render_params.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/script_executor.h" #include "extensions/browser/view_type_utils.h" #include "extensions/common/mojom/view_type.mojom.h" #include "shell/browser/extensions/electron_extension_web_contents_observer.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "chrome/browser/printing/print_view_manager_base.h" #include "components/printing/browser/print_manager_utils.h" #include "components/printing/browser/print_to_pdf/pdf_print_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" // nogncheck #include "printing/page_range.h" #include "shell/browser/printing/print_view_manager_electron.h" #if BUILDFLAG(IS_WIN) #include "printing/backend/win_helper.h" #endif #endif #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h" #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck #include "shell/browser/electron_pdf_web_contents_helper_client.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #endif #ifndef MAS_BUILD #include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck #endif namespace gin { #if BUILDFLAG(ENABLE_PRINTING) template <> struct Converter<printing::mojom::MarginType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::MarginType* out) { std::string type; if (ConvertFromV8(isolate, val, &type)) { if (type == "default") { *out = printing::mojom::MarginType::kDefaultMargins; return true; } if (type == "none") { *out = printing::mojom::MarginType::kNoMargins; return true; } if (type == "printableArea") { *out = printing::mojom::MarginType::kPrintableAreaMargins; return true; } if (type == "custom") { *out = printing::mojom::MarginType::kCustomMargins; return true; } } return false; } }; template <> struct Converter<printing::mojom::DuplexMode> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::DuplexMode* out) { std::string mode; if (ConvertFromV8(isolate, val, &mode)) { if (mode == "simplex") { *out = printing::mojom::DuplexMode::kSimplex; return true; } if (mode == "longEdge") { *out = printing::mojom::DuplexMode::kLongEdge; return true; } if (mode == "shortEdge") { *out = printing::mojom::DuplexMode::kShortEdge; return true; } } return false; } }; #endif template <> struct Converter<WindowOpenDisposition> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, WindowOpenDisposition val) { std::string disposition = "other"; switch (val) { case WindowOpenDisposition::CURRENT_TAB: disposition = "default"; break; case WindowOpenDisposition::NEW_FOREGROUND_TAB: disposition = "foreground-tab"; break; case WindowOpenDisposition::NEW_BACKGROUND_TAB: disposition = "background-tab"; break; case WindowOpenDisposition::NEW_POPUP: case WindowOpenDisposition::NEW_WINDOW: disposition = "new-window"; break; case WindowOpenDisposition::SAVE_TO_DISK: disposition = "save-to-disk"; break; default: break; } return gin::ConvertToV8(isolate, disposition); } }; template <> struct Converter<content::SavePageType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, content::SavePageType* out) { std::string save_type; if (!ConvertFromV8(isolate, val, &save_type)) return false; save_type = base::ToLowerASCII(save_type); if (save_type == "htmlonly") { *out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML; } else if (save_type == "htmlcomplete") { *out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML; } else if (save_type == "mhtml") { *out = content::SAVE_PAGE_TYPE_AS_MHTML; } else { return false; } return true; } }; template <> struct Converter<electron::api::WebContents::Type> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, electron::api::WebContents::Type val) { using Type = electron::api::WebContents::Type; std::string type; switch (val) { case Type::kBackgroundPage: type = "backgroundPage"; break; case Type::kBrowserWindow: type = "window"; break; case Type::kBrowserView: type = "browserView"; break; case Type::kRemote: type = "remote"; break; case Type::kWebView: type = "webview"; break; case Type::kOffScreen: type = "offscreen"; break; default: break; } return gin::ConvertToV8(isolate, type); } static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, electron::api::WebContents::Type* out) { using Type = electron::api::WebContents::Type; std::string type; if (!ConvertFromV8(isolate, val, &type)) return false; if (type == "backgroundPage") { *out = Type::kBackgroundPage; } else if (type == "browserView") { *out = Type::kBrowserView; } else if (type == "webview") { *out = Type::kWebView; #if BUILDFLAG(ENABLE_OSR) } else if (type == "offscreen") { *out = Type::kOffScreen; #endif } else { return false; } return true; } }; template <> struct Converter<scoped_refptr<content::DevToolsAgentHost>> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const scoped_refptr<content::DevToolsAgentHost>& val) { gin_helper::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("id", val->GetId()); dict.Set("url", val->GetURL().spec()); return dict.GetHandle(); } }; } // namespace gin namespace electron::api { namespace { base::IDMap<WebContents*>& GetAllWebContents() { static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents; return *s_all_web_contents; } // Called when CapturePage is done. void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); } absl::optional<base::TimeDelta> GetCursorBlinkInterval() { #if BUILDFLAG(IS_MAC) absl::optional<base::TimeDelta> system_value( ui::TextInsertionCaretBlinkPeriodFromDefaults()); if (system_value) return *system_value; #elif BUILDFLAG(IS_LINUX) if (auto* linux_ui = ui::LinuxUi::instance()) return linux_ui->GetCursorBlinkInterval(); #elif BUILDFLAG(IS_WIN) const auto system_msec = ::GetCaretBlinkTime(); if (system_msec != 0) { return (system_msec == INFINITE) ? base::TimeDelta() : base::Milliseconds(system_msec); } #endif return absl::nullopt; } #if BUILDFLAG(ENABLE_PRINTING) // This will return false if no printer with the provided device_name can be // found on the network. We need to check this because Chromium does not do // sanity checking of device_name validity and so will crash on invalid names. bool IsDeviceNameValid(const std::u16string& device_name) { #if BUILDFLAG(IS_MAC) base::ScopedCFTypeRef<CFStringRef> new_printer_id( base::SysUTF16ToCFStringRef(device_name)); PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get()); bool printer_exists = new_printer != nullptr; PMRelease(new_printer); return printer_exists; #else scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name)); #endif } // This function returns a validated device name. // If the user passed one to webContents.print(), we check that it's valid and // return it or fail if the network doesn't recognize it. If the user didn't // pass a device name, we first try to return the system default printer. If one // isn't set, then pull all the printers and use the first one or fail if none // exist. std::pair<std::string, std::u16string> GetDeviceNameToUse( const std::u16string& device_name) { #if BUILDFLAG(IS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ThreadRestrictions::ScopedAllowIO allow_io; #endif if (!device_name.empty()) { if (!IsDeviceNameValid(device_name)) return std::make_pair("Invalid deviceName provided", std::u16string()); return std::make_pair(std::string(), device_name); } scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); std::string printer_name; printing::mojom::ResultCode code = print_backend->GetDefaultPrinterName(printer_name); // We don't want to return if this fails since some devices won't have a // default printer. if (code != printing::mojom::ResultCode::kSuccess) LOG(ERROR) << "Failed to get default printer name"; if (printer_name.empty()) { printing::PrinterList printers; if (print_backend->EnumeratePrinters(printers) != printing::mojom::ResultCode::kSuccess) return std::make_pair("Failed to enumerate printers", std::u16string()); if (printers.empty()) return std::make_pair("No printers available on the network", std::u16string()); printer_name = printers.front().printer_name; } return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name)); } // Copied from // chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54 scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() { // USER_VISIBLE because the result is displayed in the print preview dialog. #if !BUILDFLAG(IS_WIN) static constexpr base::TaskTraits kTraits = { base::MayBlock(), base::TaskPriority::USER_VISIBLE}; #endif #if defined(USE_CUPS) // CUPS is thread safe. return base::ThreadPool::CreateTaskRunner(kTraits); #elif BUILDFLAG(IS_WIN) // Windows drivers are likely not thread-safe and need to be accessed on the // UI thread. return content::GetUIThreadTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); #else // Be conservative on unsupported platforms. return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits); #endif } #endif struct UserDataLink : public base::SupportsUserData::Data { explicit UserDataLink(base::WeakPtr<WebContents> contents) : web_contents(contents) {} base::WeakPtr<WebContents> web_contents; }; const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey; const char kRootName[] = "<root>"; struct FileSystem { FileSystem() = default; FileSystem(const std::string& type, const std::string& file_system_name, const std::string& root_url, const std::string& file_system_path) : type(type), file_system_name(file_system_name), root_url(root_url), file_system_path(file_system_path) {} std::string type; std::string file_system_name; std::string root_url; std::string file_system_path; }; std::string RegisterFileSystem(content::WebContents* web_contents, const base::FilePath& path) { auto* isolated_context = storage::IsolatedContext::GetInstance(); std::string root_name(kRootName); storage::IsolatedContext::ScopedFSHandle file_system = isolated_context->RegisterFileSystemForPath( storage::kFileSystemTypeLocal, std::string(), path, &root_name); content::ChildProcessSecurityPolicy* policy = content::ChildProcessSecurityPolicy::GetInstance(); content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost(); int renderer_id = render_view_host->GetProcess()->GetID(); policy->GrantReadFileSystem(renderer_id, file_system.id()); policy->GrantWriteFileSystem(renderer_id, file_system.id()); policy->GrantCreateFileForFileSystem(renderer_id, file_system.id()); policy->GrantDeleteFromFileSystem(renderer_id, file_system.id()); if (!policy->CanReadFile(renderer_id, path)) policy->GrantReadFile(renderer_id, path); return file_system.id(); } FileSystem CreateFileSystemStruct(content::WebContents* web_contents, const std::string& file_system_id, const std::string& file_system_path, const std::string& type) { const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL(); std::string file_system_name = storage::GetIsolatedFileSystemName(origin, file_system_id); std::string root_url = storage::GetIsolatedFileSystemRootURIString( origin, file_system_id, kRootName); return FileSystem(type, file_system_name, root_url, file_system_path); } base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) { base::Value::Dict value; value.Set("type", file_system.type); value.Set("fileSystemName", file_system.file_system_name); value.Set("rootURL", file_system.root_url); value.Set("fileSystemPath", file_system.file_system_path); return value; } void WriteToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::WriteFile(path, content.data(), content.size()); } void AppendToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::AppendToFile(path, content); } PrefService* GetPrefService(content::WebContents* web_contents) { auto* context = web_contents->GetBrowserContext(); return static_cast<electron::ElectronBrowserContext*>(context)->prefs(); } std::map<std::string, std::string> GetAddedFileSystemPaths( content::WebContents* web_contents) { auto* pref_service = GetPrefService(web_contents); const base::Value* file_system_paths_value = pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; if (file_system_paths_value) { const base::DictionaryValue* file_system_paths_dict; file_system_paths_value->GetAsDictionary(&file_system_paths_dict); for (auto it : file_system_paths_dict->DictItems()) { std::string type = it.second.is_string() ? it.second.GetString() : std::string(); result[it.first] = type; } } return result; } bool IsDevToolsFileSystemAdded(content::WebContents* web_contents, const std::string& file_system_path) { auto file_system_paths = GetAddedFileSystemPaths(web_contents); return file_system_paths.find(file_system_path) != file_system_paths.end(); } void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } } // namespace #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) { switch (view_type) { case extensions::mojom::ViewType::kExtensionBackgroundPage: return WebContents::Type::kBackgroundPage; case extensions::mojom::ViewType::kAppWindow: case extensions::mojom::ViewType::kComponent: case extensions::mojom::ViewType::kExtensionDialog: case extensions::mojom::ViewType::kExtensionPopup: case extensions::mojom::ViewType::kBackgroundContents: case extensions::mojom::ViewType::kExtensionGuest: case extensions::mojom::ViewType::kTabContents: case extensions::mojom::ViewType::kOffscreenDocument: case extensions::mojom::ViewType::kInvalid: return WebContents::Type::kRemote; } } #endif WebContents::WebContents(v8::Isolate* isolate, content::WebContents* web_contents) : content::WebContentsObserver(web_contents), type_(Type::kRemote), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // WebContents created by extension host will have valid ViewType set. extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents); if (view_type != extensions::mojom::ViewType::kInvalid) { InitWithExtensionView(isolate, web_contents, view_type); } extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents); #endif auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); SetUserAgent(GetBrowserContext()->GetUserAgent()); web_contents->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) : content::WebContentsObserver(web_contents.get()), type_(type), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { DCHECK(type != Type::kRemote) << "Can't take ownership of a remote WebContents"; auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); InitWithSessionAndOptions(isolate, std::move(web_contents), session, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options) : id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { // Read options. options.Get("backgroundThrottling", &background_throttling_); // Get type options.Get("type", &type_); #if BUILDFLAG(ENABLE_OSR) bool b = false; if (options.Get(options::kOffscreen, &b) && b) type_ = Type::kOffScreen; #endif // Init embedder earlier options.Get("embedder", &embedder_); // Whether to enable DevTools. options.Get("devTools", &enable_devtools_); // BrowserViews are not attached to a window initially so they should start // off as hidden. This is also important for compositor recycling. See: // https://github.com/electron/electron/pull/21372 bool initially_shown = type_ != Type::kBrowserView; options.Get(options::kShow, &initially_shown); // Obtain the session. std::string partition; gin::Handle<api::Session> session; if (options.Get("session", &session) && !session.IsEmpty()) { } else if (options.Get("partition", &partition)) { session = Session::FromPartition(isolate, partition); } else { // Use the default session if not specified. session = Session::FromPartition(isolate, ""); } session_.Reset(isolate, session.ToV8()); std::unique_ptr<content::WebContents> web_contents; if (IsGuest()) { scoped_refptr<content::SiteInstance> site_instance = content::SiteInstance::CreateForURL(session->browser_context(), GURL("chrome-guest://fake-host")); content::WebContents::CreateParams params(session->browser_context(), site_instance); guest_delegate_ = std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this); params.guest_delegate = guest_delegate_.get(); #if BUILDFLAG(ENABLE_OSR) if (embedder_ && embedder_->IsOffScreen()) { auto* view = new OffScreenWebContentsView( false, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); } else { #endif web_contents = content::WebContents::Create(params); #if BUILDFLAG(ENABLE_OSR) } } else if (IsOffScreen()) { // webPreferences does not have a transparent option, so if the window needs // to be transparent, that will be set at electron_api_browser_window.cc#L57 // and we then need to pull it back out and check it here. std::string background_color; options.GetHidden(options::kBackgroundColor, &background_color); bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT; content::WebContents::CreateParams params(session->browser_context()); auto* view = new OffScreenWebContentsView( transparent, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); #endif } else { content::WebContents::CreateParams params(session->browser_context()); params.initially_hidden = !initially_shown; web_contents = content::WebContents::Create(params); } InitWithSessionAndOptions(isolate, std::move(web_contents), session, options); } void WebContents::InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options) { WebContentsZoomController::CreateForWebContents(web_contents); zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents); double zoom_factor; if (options.Get(options::kZoomFactor, &zoom_factor)) zoom_controller_->SetDefaultZoomFactor(zoom_factor); } void WebContents::InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> owned_web_contents, gin::Handle<api::Session> session, const gin_helper::Dictionary& options) { Observe(owned_web_contents.get()); InitWithWebContents(std::move(owned_web_contents), session->browser_context(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); auto* prefs = web_contents()->GetMutableRendererPrefs(); // Collect preferred languages from OS and browser process. accept_languages // effects HTTP header, navigator.languages, and CJK fallback font selection. // // Note that an application locale set to the browser process might be // different with the one set to the preference list. // (e.g. overridden with --lang) std::string accept_languages = g_browser_process->GetApplicationLocale() + ","; for (auto const& language : electron::GetPreferredLanguages()) { if (language == g_browser_process->GetApplicationLocale()) continue; accept_languages += language + ","; } accept_languages.pop_back(); prefs->accept_languages = accept_languages; #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) // Update font settings. static const gfx::FontRenderParams params( gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr)); prefs->should_antialias_text = params.antialiasing; prefs->use_subpixel_positioning = params.subpixel_positioning; prefs->hinting = params.hinting; prefs->use_autohinter = params.autohinter; prefs->use_bitmaps = params.use_bitmaps; prefs->subpixel_rendering = params.subpixel_rendering; #endif // Honor the system's cursor blink rate settings if (auto interval = GetCursorBlinkInterval()) prefs->caret_blink_interval = *interval; // Save the preferences in C++. // If there's already a WebContentsPreferences object, we created it as part // of the webContents.setWindowOpenHandler path, so don't overwrite it. if (!WebContentsPreferences::From(web_contents())) { new WebContentsPreferences(web_contents(), options); } // Trigger re-calculation of webkit prefs. web_contents()->NotifyPreferencesChanged(); WebContentsPermissionHelper::CreateForWebContents(web_contents()); InitZoomController(web_contents(), options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents()); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents()); #endif AutofillDriverFactory::CreateForWebContents(web_contents()); SetUserAgent(GetBrowserContext()->GetUserAgent()); if (IsGuest()) { NativeWindow* owner_window = nullptr; if (embedder_) { // New WebContents's owner_window is the embedder's owner_window. auto* relay = NativeWindowRelay::FromWebContents(embedder_->web_contents()); if (relay) owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); } web_contents()->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void WebContents::InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::mojom::ViewType view_type) { // Must reassign type prior to calling `Init`. type_ = GetTypeFromViewType(view_type); if (type_ == Type::kRemote) return; if (type_ == Type::kBackgroundPage) // non-background-page WebContents are retained by other classes. We need // to pin here to prevent background-page WebContents from being GC'd. // The background page api::WebContents will live until the underlying // content::WebContents is destroyed. Pin(isolate); // Allow toggling DevTools for background pages Observe(web_contents); InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents), GetBrowserContext(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); } #endif void WebContents::InitWithWebContents( std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest) { browser_context_ = browser_context; web_contents->SetDelegate(this); #if BUILDFLAG(ENABLE_PRINTING) PrintViewManagerElectron::CreateForWebContents(web_contents.get()); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) pdf::PDFWebContentsHelper::CreateForWebContentsWithClient( web_contents.get(), std::make_unique<ElectronPDFWebContentsHelperClient>()); #endif // Determine whether the WebContents is offscreen. auto* web_preferences = WebContentsPreferences::From(web_contents.get()); offscreen_ = web_preferences && web_preferences->IsOffscreen(); // Create InspectableWebContents. inspectable_web_contents_ = std::make_unique<InspectableWebContents>( std::move(web_contents), browser_context->prefs(), is_guest); inspectable_web_contents_->SetDelegate(this); } WebContents::~WebContents() { if (!inspectable_web_contents_) { WebContentsDestroyed(); return; } inspectable_web_contents_->GetView()->SetDelegate(nullptr); // This event is only for internal use, which is emitted when WebContents is // being destroyed. Emit("will-destroy"); // For guest view based on OOPIF, the WebContents is released by the embedder // frame, and we need to clear the reference to the memory. bool not_owned_by_this = IsGuest() && attached_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // And background pages are owned by extensions::ExtensionHost. if (type_ == Type::kBackgroundPage) not_owned_by_this = true; #endif if (not_owned_by_this) { inspectable_web_contents_->ReleaseWebContents(); WebContentsDestroyed(); } // InspectableWebContents will be automatically destroyed. } void WebContents::DeleteThisIfAlive() { // It is possible that the FirstWeakCallback has been called but the // SecondWeakCallback has not, in this case the garbage collection of // WebContents has already started and we should not |delete this|. // Calling |GetWrapper| can detect this corner case. auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; delete this; } void WebContents::Destroy() { // The content::WebContents should be destroyed asynchronously when possible // as user may choose to destroy WebContents during an event of it. if (Browser::Get()->is_shutting_down() || IsGuest()) { DeleteThisIfAlive(); } else { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce( [](base::WeakPtr<WebContents> contents) { if (contents) contents->DeleteThisIfAlive(); }, GetWeakPtr())); } } bool WebContents::DidAddMessageToConsole( content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) { return Emit("console-message", static_cast<int32_t>(level), message, line_no, source_id); } void WebContents::OnCreateWindow( const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const std::string& features, const scoped_refptr<network::ResourceRequestBody>& body) { Emit("-new-window", target_url, frame_name, disposition, features, referrer, body); } void WebContents::WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) { ChildWebContentsTracker::CreateForWebContents(new_contents); auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents); tracker->url = params.target_url; tracker->frame_name = params.frame_name; tracker->referrer = params.referrer.To<content::Referrer>(); tracker->raw_features = params.raw_features; tracker->body = params.body; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary dict; gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate), &dict); pending_child_web_preferences_.Reset(); // Associate the preferences passed in via `setWindowOpenHandler` with the // content::WebContents that was just created for the child window. These // preferences will be picked up by the RenderWidgetHost via its call to the // delegate's OverrideWebkitPrefs. new WebContentsPreferences(new_contents, dict); } bool WebContents::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) { bool default_prevented = Emit( "-will-add-new-contents", params.target_url, params.frame_name, params.raw_features, params.disposition, *params.referrer, params.body); // If the app prevented the default, redirect to CreateCustomWebContents, // which always returns nullptr, which will result in the window open being // prevented (window.open() will return null in the renderer). return default_prevented; } void WebContents::SetNextChildWebPreferences( const gin_helper::Dictionary preferences) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); // Store these prefs for when Chrome calls WebContentsCreatedWithFullParams // with the new child contents. pending_child_web_preferences_.Reset(isolate, preferences.GetHandle()); } content::WebContents* WebContents::CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionConfig& partition_config, content::SessionStorageNamespace* session_storage_namespace) { return nullptr; } void WebContents::AddNewContents( content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, 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, initial_rect.x(), initial_rect.y(), initial_rect.width(), initial_rect.height(), tracker->url, tracker->frame_name, tracker->referrer, tracker->raw_features, tracker->body)) { api_web_contents->Destroy(); } } content::WebContents* WebContents::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { auto weak_this = GetWeakPtr(); if (params.disposition != WindowOpenDisposition::CURRENT_TAB) { Emit("-new-window", params.url, "", params.disposition, "", params.referrer, params.post_data); return nullptr; } if (!weak_this || !web_contents()) return nullptr; content::NavigationController::LoadURLParams load_url_params(params.url); load_url_params.referrer = params.referrer; load_url_params.transition_type = params.transition; load_url_params.extra_headers = params.extra_headers; load_url_params.should_replace_current_entry = params.should_replace_current_entry; load_url_params.is_renderer_initiated = params.is_renderer_initiated; load_url_params.started_from_context_menu = params.started_from_context_menu; load_url_params.initiator_origin = params.initiator_origin; load_url_params.source_site_instance = params.source_site_instance; load_url_params.frame_tree_node_id = params.frame_tree_node_id; load_url_params.redirect_chain = params.redirect_chain; load_url_params.has_user_gesture = params.user_gesture; load_url_params.blob_url_loader_factory = params.blob_url_loader_factory; load_url_params.href_translate = params.href_translate; load_url_params.reload_type = params.reload_type; if (params.post_data) { load_url_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; load_url_params.post_data = params.post_data; } source->GetController().LoadURLWithParams(load_url_params); return source; } void WebContents::BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen || type_ == Type::kBrowserView) *proceed_to_fire_unload = proceed; else *proceed_to_fire_unload = true; // Note that Chromium does not emit this for navigations. Emit("before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnSetContentBounds(rect); } void WebContents::CloseContents(content::WebContents* source) { Emit("close"); auto* autofill_driver_factory = AutofillDriverFactory::FromWebContents(web_contents()); if (autofill_driver_factory) { autofill_driver_factory->CloseAllPopups(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); } void WebContents::ActivateContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnActivateContents(); } void WebContents::UpdateTargetURL(content::WebContents* source, const GURL& url) { Emit("update-target-url", url); } bool WebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (type_ == Type::kWebView && embedder_) { // Send the unhandled keyboard events back to the embedder. return embedder_->HandleKeyboardEvent(source, event); } else { return PlatformHandleKeyboardEvent(source, event); } } #if !BUILDFLAG(IS_MAC) // NOTE: The macOS version of this function is found in // electron_api_web_contents_mac.mm, as it requires calling into objective-C // code. bool WebContents::PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { // Escape exits tabbed fullscreen mode. if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { ExitFullscreenModeForTab(source); return true; } // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts()) return false; // Let the NativeWindow handle other parts. if (owner_window()) { owner_window()->HandleKeyboardEvent(source, event); return true; } return false; } #endif content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (exclusive_access_manager_->HandleUserKeyEvent(event)) return content::KeyboardEventProcessingResult::HANDLED; if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kKeyUp) { bool prevent_default = Emit("before-input-event", event); if (prevent_default) { return content::KeyboardEventProcessingResult::HANDLED; } } return content::KeyboardEventProcessingResult::NOT_HANDLED; } void WebContents::ContentsZoomChange(bool zoom_in) { Emit("zoom-changed", zoom_in ? "in" : "out"); } Profile* WebContents::GetProfile() { return nullptr; } bool WebContents::IsFullscreen() const { return owner_window_ && owner_window_->IsFullscreen(); } void WebContents::EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) {} void WebContents::ExitFullscreen() {} void WebContents::UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool 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(callback); } void WebContents::OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed) { if (!allowed || !owner_window_) return; auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); if (IsFullscreenForTabOrPending(source)) { DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame()); return; } owner_window()->set_fullscreen_transition_type( NativeWindow::FullScreenTransitionType::HTML); exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); SetHtmlApiFullscreen(true); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { if (!owner_window_) return; // This needs to be called before we exit fullscreen on the native window, // or the controller will incorrectly think we weren't fullscreen and bail. exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab( source); SetHtmlApiFullscreen(false); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. Chrome does this indirectly from // `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) { Emit("unresponsive"); } void WebContents::RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) { Emit("responsive"); } bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) { Emit("context-menu", std::make_pair(params, &render_frame_host)); return true; } bool WebContents::OnGoToEntryOffset(int offset) { GoToOffset(offset); return false; } void WebContents::FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { if (!final_update) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate); result.Set("requestId", request_id); result.Set("matches", number_of_matches); result.Set("selectionArea", selection_rect); result.Set("activeMatchOrdinal", active_match_ordinal); result.Set("finalUpdate", final_update); // Deprecate after 2.0 Emit("found-in-page", result.GetHandle()); } void WebContents::RequestExclusivePointerAccess( content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed) { if (allowed) { exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse( web_contents, user_gesture, last_unlocked_by_target); } else { web_contents->GotResponseToLockMouseRequest( blink::mojom::PointerLockResult::kPermissionDenied); } } void WebContents::RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestPointerLockPermission( user_gesture, last_unlocked_by_target, base::BindOnce(&WebContents::RequestExclusivePointerAccess, base::Unretained(this))); } void WebContents::LostMouseLock() { exclusive_access_manager_->mouse_lock_controller()->LostMouseLock(); } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } void WebContents::CancelKeyboardLockRequest( content::WebContents* web_contents) { exclusive_access_manager_->keyboard_lock_controller() ->CancelKeyboardLockRequest(web_contents); } bool WebContents::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckMediaAccessPermission(security_origin, type); } void WebContents::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestMediaAccessPermission(request, std::move(callback)); } content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { if (!dialog_manager_) dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>(); return dialog_manager_.get(); } void WebContents::OnAudioStateChanged(bool audible) { Emit("-audio-state-changed", audible); } void WebContents::BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) { // Do nothing, we override this method just to avoid compilation error since // there are two virtual functions named BeforeUnloadFired. } void WebContents::HandleNewRenderFrame( content::RenderFrameHost* render_frame_host) { auto* rwhv = render_frame_host->GetView(); if (!rwhv) return; // Set the background color of RenderWidgetHostView. auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences) { absl::optional<SkColor> maybe_color = web_preferences->GetBackgroundColor(); web_contents()->SetPageBaseBackgroundColor(maybe_color); bool guest = IsGuest() || type_ == Type::kBrowserView; SkColor color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); SetBackgroundColor(rwhv, color); } if (!background_throttling_) render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false); auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (rwh_impl) rwh_impl->disable_hidden_ = !background_throttling_; auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->MaybeSetupMojoConnection(); } void WebContents::OnBackgroundColorChanged() { absl::optional<SkColor> color = web_contents()->GetBackgroundColor(); if (color.has_value()) { auto* const view = web_contents()->GetRenderWidgetHostView(); static_cast<content::RenderWidgetHostViewBase*>(view) ->SetContentBackgroundColor(color.value()); } } void WebContents::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { HandleNewRenderFrame(render_frame_host); // RenderFrameCreated is called for speculative frames which may not be // used in certain cross-origin navigations. Invoking // RenderFrameHost::GetLifecycleState currently crashes when called for // speculative frames so we need to filter it out for now. Check // https://crbug.com/1183639 for details on when this can be removed. auto* rfh_impl = static_cast<content::RenderFrameHostImpl*>(render_frame_host); if (rfh_impl->lifecycle_state() == content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) { return; } content::RenderFrameHost::LifecycleState lifecycle_state = render_frame_host->GetLifecycleState(); if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.SetGetter("frame", render_frame_host); Emit("frame-created", details); } } void WebContents::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { // A RenderFrameHost can be deleted when: // - A WebContents is removed and its containing frames are disposed. // - An <iframe> is removed from the DOM. // - Cross-origin navigation creates a new RFH in a separate process which // is swapped by content::RenderFrameHostManager. // // WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID // to find an existing instance of WebFrameMain. During a cross-origin // navigation, the deleted RFH will be the old host which was swapped out. In // this special case, we need to also ensure that WebFrameMain's internal RFH // matches before marking it as disposed. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame && web_frame->render_frame_host() == render_frame_host) web_frame->MarkRenderFrameDisposed(); } void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { // During cross-origin navigation, a FrameTreeNode will swap out its RFH. // If an instance of WebFrameMain exists, it will need to have its RFH // swapped as well. // // |old_host| can be a nullptr so we use |new_host| for looking up the // WebFrameMain instance. auto* web_frame = WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId()); if (web_frame) { web_frame->UpdateRenderFrameHost(new_host); } } void WebContents::FrameDeleted(int frame_tree_node_id) { auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id); if (web_frame) web_frame->Destroyed(); } void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) { // This event is necessary for tracking any states with respect to // intermediate render view hosts aka speculative render view hosts. Currently // used by object-registry.js to ref count remote objects. Emit("render-view-deleted", render_view_host->GetProcess()->GetID()); if (web_contents()->GetRenderViewHost() == render_view_host) { // When the RVH that has been deleted is the current RVH it means that the // the web contents are being closed. This is communicated by this event. // Currently tracked by guest-window-manager.ts to destroy the // BrowserWindow. Emit("current-render-view-deleted", render_view_host->GetProcess()->GetID()); } } void WebContents::PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) { auto weak_this = GetWeakPtr(); Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED); // User might destroy WebContents in the crashed event. if (!weak_this || !web_contents()) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.Set("reason", status); details.Set("exitCode", web_contents()->GetCrashedErrorCode()); Emit("render-process-gone", details); } void WebContents::PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) { #if BUILDFLAG(ENABLE_PLUGINS) content::WebPluginInfo info; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->GetPluginInfoByPath(plugin_path, &info); Emit("plugin-crashed", info.name, info.version); #endif // BUILDFLAG(ENABLE_PLUGINS) } void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) { Emit("media-started-playing"); } void WebContents::MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) { Emit("media-paused"); } void WebContents::DidChangeThemeColor() { auto theme_color = web_contents()->GetThemeColor(); if (theme_color) { Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value())); } else { Emit("did-change-theme-color", nullptr); } } void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) { set_fullscreen_frame(rfh); } void WebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { Emit("focus"); } void WebContents::OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) { Emit("blur"); } void WebContents::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->DOMContentLoaded(); if (!render_frame_host->GetParent()) Emit("dom-ready"); } void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); auto weak_this = GetWeakPtr(); Emit("did-frame-finish-load", is_main_frame, frame_process_id, frame_routing_id); // ⚠️WARNING!⚠️ // Emit() triggers JS which can call destroy() on |this|. It's not safe to // assume that |this| points to valid memory at this point. if (is_main_frame && weak_this && web_contents()) Emit("did-finish-load"); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& url, int error_code) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::DidStartLoading() { Emit("did-start-loading"); } void WebContents::DidStopLoading() { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences && web_preferences->ShouldUsePreferredSizeMode()) web_contents()->GetRenderViewHost()->EnablePreferredSizeMode(); Emit("did-stop-loading"); } bool WebContents::EmitNavigationEvent( const std::string& event, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId(); content::FrameTreeNode* frame_tree_node = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id); content::RenderFrameHostManager* render_manager = frame_tree_node->render_manager(); content::RenderFrameHost* frame_host = nullptr; if (render_manager) { frame_host = render_manager->speculative_frame_host(); if (!frame_host) frame_host = render_manager->current_frame_host(); } int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } bool is_same_document = navigation_handle->IsSameDocument(); auto url = navigation_handle->GetURL(); return Emit(event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Message", "channel", channel); // webContents.emit('-ipc-message', new Event(), internal, channel, // arguments); EmitWithSender("-ipc-message", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), internal, channel, std::move(arguments)); } void WebContents::Invoke( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::InvokeCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel); // webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments); EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::OnFirstNonEmptyLayout( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents()->GetPrimaryMainFrame()) { Emit("ready-to-show"); } } void WebContents::ReceivePostMessage( const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto wrapped_ports = MessagePort::EntanglePorts(isolate, std::move(message.ports)); v8::Local<v8::Value> message_value = electron::DeserializeV8Value(isolate, message); EmitWithSender("-ipc-ports", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), false, channel, message_value, std::move(wrapped_ports)); } void WebContents::MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel); // webContents.emit('-ipc-message-sync', new Event(sender, message), internal, // channel, arguments); EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments) { TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel); auto* target_web_contents = FromID(web_contents_id); if (target_web_contents) { content::RenderFrameHost* frame = target_web_contents->MainFrame(); DCHECK(frame); v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate()); gin::Handle<WebFrameMain> web_frame_main = WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame); if (!web_frame_main->CheckRenderFrame()) return; int32_t sender_id = ID(); web_frame_main->GetRendererApi()->Message(false /* internal */, channel, std::move(arguments), sender_id); } } void WebContents::MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel); // webContents.emit('ipc-message-host', new Event(), channel, args); EmitWithSender("ipc-message-host", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), channel, std::move(arguments)); } void WebContents::UpdateDraggableRegions( std::vector<mojom::DraggableRegionPtr> regions) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDraggableRegionsUpdated(regions); } void WebContents::DidStartNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-start-navigation", navigation_handle); } void WebContents::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-redirect-navigation", navigation_handle); } void WebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { // Don't focus content in an inactive window. if (!owner_window()) return; #if BUILDFLAG(IS_MAC) if (!owner_window()->IsActive()) return; #else if (!owner_window()->widget()->IsActive()) return; #endif // Don't focus content after subframe navigations. if (!navigation_handle->IsInMainFrame()) return; // Only focus for top-level contents. if (type_ != Type::kBrowserWindow) return; web_contents()->SetInitialFocus(); } void WebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (owner_window_) { owner_window_->NotifyLayoutWindowControlsOverlay(); } if (!navigation_handle->HasCommitted()) return; bool is_main_frame = navigation_handle->IsInMainFrame(); content::RenderFrameHost* frame_host = navigation_handle->GetRenderFrameHost(); int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } if (!navigation_handle->IsErrorPage()) { // FIXME: All the Emit() calls below could potentially result in |this| // being destroyed (by JS listening for the event and calling // webContents.destroy()). auto url = navigation_handle->GetURL(); bool is_same_document = navigation_handle->IsSameDocument(); if (is_same_document) { Emit("did-navigate-in-page", url, is_main_frame, frame_process_id, frame_routing_id); } else { const net::HttpResponseHeaders* http_response = navigation_handle->GetResponseHeaders(); std::string http_status_text; int http_response_code = -1; if (http_response) { http_status_text = http_response->GetStatusText(); http_response_code = http_response->response_code(); } Emit("did-frame-navigate", url, http_response_code, http_status_text, is_main_frame, frame_process_id, frame_routing_id); if (is_main_frame) { Emit("did-navigate", url, http_response_code, http_status_text); } } if (IsGuest()) Emit("load-commit", url, is_main_frame); } else { auto url = navigation_handle->GetURL(); int code = navigation_handle->GetNetErrorCode(); auto description = net::ErrorToShortString(code); Emit("did-fail-provisional-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); // Do not emit "did-fail-load" for canceled requests. if (code != net::ERR_ABORTED) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "Failed to load URL: " + url.possibly_invalid_spec() + " with error: " + description, "electron"); Emit("did-fail-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); } } content::NavigationEntry* entry = navigation_handle->GetNavigationEntry(); // This check is needed due to an issue in Chromium // Check the Chromium issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=1178663 // If a history entry has been made and the forward/back call has been made, // proceed with setting the new title if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK)) WebContents::TitleWasSet(entry); } void WebContents::TitleWasSet(content::NavigationEntry* entry) { std::u16string final_title; bool explicit_set = true; if (entry) { auto title = entry->GetTitle(); auto url = entry->GetURL(); if (url.SchemeIsFile() && title.empty()) { final_title = base::UTF8ToUTF16(url.ExtractFileName()); explicit_set = false; } else { final_title = title; } } else { final_title = web_contents()->GetTitle(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnPageTitleUpdated(final_title, explicit_set); Emit("page-title-updated", final_title, explicit_set); } void WebContents::DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) { std::set<GURL> unique_urls; for (const auto& iter : urls) { if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon) continue; const GURL& url = iter->icon_url; if (url.is_valid()) unique_urls.insert(url); } Emit("page-favicon-updated", unique_urls); } void WebContents::DevToolsReloadPage() { Emit("devtools-reload-page"); } void WebContents::DevToolsFocused() { Emit("devtools-focused"); } void WebContents::DevToolsOpened() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); DCHECK(inspectable_web_contents_); DCHECK(inspectable_web_contents_->GetDevToolsWebContents()); auto handle = FromOrCreate( isolate, inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_contents_.Reset(isolate, handle.ToV8()); // Set inspected tabID. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "setInspectedTabId", base::Value(ID())); // Inherit owner window in devtools when it doesn't have one. auto* devtools = inspectable_web_contents_->GetDevToolsWebContents(); bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey()); if (owner_window() && !has_window) handle->SetOwnerWindow(devtools, owner_window()); Emit("devtools-opened"); } void WebContents::DevToolsClosed() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); devtools_web_contents_.Reset(); Emit("devtools-closed"); } void WebContents::DevToolsResized() { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDevToolsResized(); } void WebContents::SetOwnerWindow(NativeWindow* owner_window) { SetOwnerWindow(GetWebContents(), owner_window); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } #if BUILDFLAG(ENABLE_OSR) auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); #endif } content::WebContents* WebContents::GetWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetWebContents(); } content::WebContents* WebContents::GetDevToolsWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetDevToolsWebContents(); } void WebContents::WebContentsDestroyed() { // Clear the pointer stored in wrapper. if (GetAllWebContents().Lookup(id_)) GetAllWebContents().Remove(id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; wrapper->SetAlignedPointerInInternalField(0, nullptr); // Tell WebViewGuestDelegate that the WebContents has been destroyed. if (guest_delegate_) guest_delegate_->WillDestroy(); Observe(nullptr); Emit("destroyed"); } void WebContents::NavigationEntryCommitted( const content::LoadCommittedDetails& details) { Emit("navigation-entry-committed", details.entry->GetURL(), details.is_same_document, details.did_replace_entry); } bool WebContents::GetBackgroundThrottling() const { return background_throttling_; } void WebContents::SetBackgroundThrottling(bool allowed) { background_throttling_ = allowed; auto* rfh = web_contents()->GetPrimaryMainFrame(); if (!rfh) return; auto* rwhv = rfh->GetView(); if (!rwhv) return; auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (!rwh_impl) return; rwh_impl->disable_hidden_ = !background_throttling_; web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed); if (rwh_impl->is_hidden()) { rwh_impl->WasShown({}); } } int WebContents::GetProcessID() const { return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents() ->GetPrimaryMainFrame() ->GetProcess() ->GetProcess() .Handle(); return base::GetProcId(process_handle); } WebContents::Type WebContents::GetType() const { return type_; } bool WebContents::Equal(const WebContents* web_contents) const { return ID() == web_contents->ID(); } GURL WebContents::GetURL() const { return web_contents()->GetLastCommittedURL(); } void WebContents::LoadURL(const GURL& url, const gin_helper::Dictionary& options) { if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) { Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL), net::ErrorToShortString(net::ERR_INVALID_URL), url.possibly_invalid_spec(), true); return; } content::NavigationController::LoadURLParams params(url); if (!options.Get("httpReferrer", &params.referrer)) { GURL http_referrer; if (options.Get("httpReferrer", &http_referrer)) params.referrer = content::Referrer(http_referrer.GetAsReferrer(), network::mojom::ReferrerPolicy::kDefault); } std::string user_agent; if (options.Get("userAgent", &user_agent)) SetUserAgent(user_agent); std::string extra_headers; if (options.Get("extraHeaders", &extra_headers)) params.extra_headers = extra_headers; scoped_refptr<network::ResourceRequestBody> body; if (options.Get("postData", &body)) { params.post_data = body; params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; } GURL base_url_for_data_url; if (options.Get("baseURLForDataURL", &base_url_for_data_url)) { params.base_url_for_data_url = base_url_for_data_url; params.load_type = content::NavigationController::LOAD_TYPE_DATA; } bool reload_ignoring_cache = false; if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) && reload_ignoring_cache) { params.reload_type = content::ReloadType::BYPASSING_CACHE; } // Calling LoadURLWithParams() can trigger JS which destroys |this|. auto weak_this = GetWeakPtr(); params.transition_type = ui::PageTransitionFromInt( ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; // Discard non-committed entries to ensure that we don't re-use a pending // entry web_contents()->GetController().DiscardNonCommittedEntries(); web_contents()->GetController().LoadURLWithParams(params); // ⚠️WARNING!⚠️ // LoadURLWithParams() triggers JS events which can call destroy() on |this|. // It's not safe to assume that |this| points to valid memory at this point. if (!weak_this || !web_contents()) return; // Required to make beforeunload handler work. NotifyUserActivation(); } // TODO(MarshallOfSound): Figure out what we need to do with post data here, I // believe the default behavior when we pass "true" is to phone out to the // delegate and then the controller expects this method to be called again with // "false" if the user approves the reload. For now this would result in // ".reload()" calls on POST data domains failing silently. Passing false would // result in them succeeding, but reposting which although more correct could be // considering a breaking change. void WebContents::Reload() { web_contents()->GetController().Reload(content::ReloadType::NORMAL, /* check_for_repost */ true); } void WebContents::ReloadIgnoringCache() { web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE, /* check_for_repost */ true); } void WebContents::DownloadURL(const GURL& url) { auto* browser_context = web_contents()->GetBrowserContext(); auto* download_manager = browser_context->GetDownloadManager(); std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); download_manager->DownloadUrl(std::move(download_params)); } std::u16string WebContents::GetTitle() const { return web_contents()->GetTitle(); } bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } bool WebContents::IsLoadingMainFrame() const { return web_contents()->ShouldShowLoadingUI(); } bool WebContents::IsWaitingForResponse() const { return web_contents()->IsWaitingForResponse(); } void WebContents::Stop() { web_contents()->Stop(); } bool WebContents::CanGoBack() const { return web_contents()->GetController().CanGoBack(); } void WebContents::GoBack() { if (CanGoBack()) web_contents()->GetController().GoBack(); } bool WebContents::CanGoForward() const { return web_contents()->GetController().CanGoForward(); } void WebContents::GoForward() { if (CanGoForward()) web_contents()->GetController().GoForward(); } bool WebContents::CanGoToOffset(int offset) const { return web_contents()->GetController().CanGoToOffset(offset); } void WebContents::GoToOffset(int offset) { if (CanGoToOffset(offset)) web_contents()->GetController().GoToOffset(offset); } bool WebContents::CanGoToIndex(int index) const { return index >= 0 && index < GetHistoryLength(); } void WebContents::GoToIndex(int index) { if (CanGoToIndex(index)) web_contents()->GetController().GoToIndex(index); } int WebContents::GetActiveIndex() const { return web_contents()->GetController().GetCurrentEntryIndex(); } void WebContents::ClearHistory() { // In some rare cases (normally while there is no real history) we are in a // state where we can't prune navigation entries if (web_contents()->GetController().CanPruneAllButLastCommitted()) { web_contents()->GetController().PruneAllButLastCommitted(); } } int WebContents::GetHistoryLength() const { return web_contents()->GetController().GetEntryCount(); } const std::string WebContents::GetWebRTCIPHandlingPolicy() const { return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy; } void WebContents::SetWebRTCIPHandlingPolicy( const std::string& webrtc_ip_handling_policy) { if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy) return; web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy = webrtc_ip_handling_policy; web_contents()->SyncRendererPrefs(); } std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) return std::string(); content::DesktopMediaID media_id( content::DesktopMediaID::TYPE_WEB_CONTENTS, content::DesktopMediaID::kNullId, content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(), frame_host->GetRoutingID())); auto* request_frame_host = request_web_contents->GetPrimaryMainFrame(); if (!request_frame_host) return std::string(); std::string id = content::DesktopStreamsRegistry::GetInstance()->RegisterStream( request_frame_host->GetProcess()->GetID(), request_frame_host->GetRoutingID(), url::Origin::Create(request_frame_host->GetLastCommittedURL() .DeprecatedGetOriginAsURL()), media_id, "", content::kRegistryStreamTypeTab); return id; } bool WebContents::IsCrashed() const { return web_contents()->IsCrashed(); } void WebContents::ForcefullyCrashRenderer() { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); if (!rwh) return; content::RenderProcessHost* rph = rwh->GetProcess(); if (rph) { #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // A generic |CrashDumpHungChildProcess()| is not implemented for Linux. // Instead we send an explicit IPC to crash on the renderer's IO thread. rph->ForceCrash(); #else // Try to generate a crash report for the hung process. #ifndef MAS_BUILD CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { blink::UserAgentOverride ua_override; ua_override.ua_string_override = user_agent; if (!user_agent.empty()) ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata(); web_contents()->SetUserAgentOverride(ua_override, false); } std::string WebContents::GetUserAgent() { return web_contents()->GetUserAgentOverride().ua_string_override; } v8::Local<v8::Promise> WebContents::SavePage( const base::FilePath& full_file_path, const content::SavePageType& save_type) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (!full_file_path.IsAbsolute()) { promise.RejectWithErrorMessage("Path must be absolute"); return handle; } auto* handler = new SavePageHandler(web_contents(), std::move(promise)); handler->Handle(full_file_path, save_type); return handle; } void WebContents::OpenDevTools(gin::Arguments* args) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; std::string state; if (type_ == Type::kWebView || type_ == Type::kBackgroundPage || !owner_window()) { state = "detach"; } bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->ShowDevTools(activate); } void WebContents::CloseDevTools() { if (type_ == Type::kRemote) return; DCHECK(inspectable_web_contents_); inspectable_web_contents_->CloseDevTools(); } bool WebContents::IsDevToolsOpened() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->IsDevToolsViewShowing(); } bool WebContents::IsDevToolsFocused() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetView()->IsDevToolsViewFocused(); } void WebContents::EnableDeviceEmulation( const blink::DeviceEmulationParams& params) { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->EnableDeviceEmulation(params); } } } void WebContents::DisableDeviceEmulation() { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->DisableDeviceEmulation(); } } } void WebContents::ToggleDevTools() { if (IsDevToolsOpened()) CloseDevTools(); else OpenDevTools(nullptr); } void WebContents::InspectElement(int x, int y) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; DCHECK(inspectable_web_contents_); if (!inspectable_web_contents_->GetDevToolsWebContents()) OpenDevTools(nullptr); inspectable_web_contents_->InspectElement(x, y); } void WebContents::InspectSharedWorkerById(const std::string& workerId) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { if (agent_host->GetId() == workerId) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } } std::vector<scoped_refptr<content::DevToolsAgentHost>> WebContents::GetAllSharedWorkers() { std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers; if (type_ == Type::kRemote) return shared_workers; if (!enable_devtools_) return shared_workers; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { shared_workers.push_back(agent_host); } } return shared_workers; } void WebContents::InspectSharedWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::InspectServiceWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeServiceWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::SetIgnoreMenuShortcuts(bool ignore) { auto* web_preferences = WebContentsPreferences::From(web_contents()); DCHECK(web_preferences); web_preferences->SetIgnoreMenuShortcuts(ignore); } void WebContents::SetAudioMuted(bool muted) { web_contents()->SetAudioMuted(muted); } bool WebContents::IsAudioMuted() { return web_contents()->IsAudioMuted(); } bool WebContents::IsCurrentlyAudible() { return web_contents()->IsCurrentlyAudible(); } #if BUILDFLAG(ENABLE_PRINTING) void WebContents::OnGetDeviceNameToUse( base::Value::Dict print_settings, printing::CompletionCallback print_callback, bool silent, // <error, device_name> std::pair<std::string, std::u16string> info) { // The content::WebContents might be already deleted at this point, and the // PrintViewManagerElectron class does not do null check. if (!web_contents()) { if (print_callback) std::move(print_callback).Run(false, "failed"); return; } if (!info.first.empty()) { if (print_callback) std::move(print_callback).Run(false, info.first); return; } // If the user has passed a deviceName use it, otherwise use default printer. print_settings.Set(printing::kSettingDeviceName, info.second); auto* print_view_manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!print_view_manager) return; auto* focused_frame = web_contents()->GetFocusedFrame(); auto* rfh = focused_frame && focused_frame->HasSelection() ? focused_frame : web_contents()->GetPrimaryMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); base::Value::Dict settings; if (args->Length() >= 1 && !args->GetNext(&options)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid print settings specified."); return; } printing::CompletionCallback callback; if (args->Length() == 2 && !args->GetNext(&callback)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid optional callback provided."); return; } // Set optional silent printing bool silent = false; options.Get("silent", &silent); bool print_background = false; options.Get("printBackground", &print_background); settings.Set(printing::kSettingShouldPrintBackgrounds, print_background); // Set custom margin settings gin_helper::Dictionary margins = gin::Dictionary::CreateEmpty(args->isolate()); if (options.Get("margins", &margins)) { printing::mojom::MarginType margin_type = printing::mojom::MarginType::kDefaultMargins; margins.Get("marginType", &margin_type); settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type)); if (margin_type == printing::mojom::MarginType::kCustomMargins) { base::Value::Dict custom_margins; int top = 0; margins.Get("top", &top); custom_margins.Set(printing::kSettingMarginTop, top); int bottom = 0; margins.Get("bottom", &bottom); custom_margins.Set(printing::kSettingMarginBottom, bottom); int left = 0; margins.Get("left", &left); custom_margins.Set(printing::kSettingMarginLeft, left); int right = 0; margins.Get("right", &right); custom_margins.Set(printing::kSettingMarginRight, right); settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins)); } } else { settings.Set( printing::kSettingMarginsType, static_cast<int>(printing::mojom::MarginType::kDefaultMargins)); } // Set whether to print color or greyscale bool print_color = true; options.Get("color", &print_color); auto const color_model = print_color ? printing::mojom::ColorModel::kColor : printing::mojom::ColorModel::kGray; settings.Set(printing::kSettingColor, static_cast<int>(color_model)); // Is the orientation landscape or portrait. bool landscape = false; options.Get("landscape", &landscape); settings.Set(printing::kSettingLandscape, landscape); // We set the default to the system's default printer and only update // if at the Chromium level if the user overrides. // Printer device name as opened by the OS. std::u16string device_name; options.Get("deviceName", &device_name); int scale_factor = 100; options.Get("scaleFactor", &scale_factor); settings.Set(printing::kSettingScaleFactor, scale_factor); int pages_per_sheet = 1; options.Get("pagesPerSheet", &pages_per_sheet); settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet); // True if the user wants to print with collate. bool collate = true; options.Get("collate", &collate); settings.Set(printing::kSettingCollate, collate); // The number of individual copies to print int copies = 1; options.Get("copies", &copies); settings.Set(printing::kSettingCopies, copies); // Strings to be printed as headers and footers if requested by the user. std::string header; options.Get("header", &header); std::string footer; options.Get("footer", &footer); if (!(header.empty() && footer.empty())) { settings.Set(printing::kSettingHeaderFooterEnabled, true); settings.Set(printing::kSettingHeaderFooterTitle, header); settings.Set(printing::kSettingHeaderFooterURL, footer); } else { settings.Set(printing::kSettingHeaderFooterEnabled, false); } // We don't want to allow the user to enable these settings // but we need to set them or a CHECK is hit. settings.Set(printing::kSettingPrinterType, static_cast<int>(printing::mojom::PrinterType::kLocal)); settings.Set(printing::kSettingShouldPrintSelectionOnly, false); settings.Set(printing::kSettingRasterizePdf, false); // Set custom page ranges to print std::vector<gin_helper::Dictionary> page_ranges; if (options.Get("pageRanges", &page_ranges)) { base::Value::List page_range_list; for (auto& range : page_ranges) { int from, to; if (range.Get("from", &from) && range.Get("to", &to)) { base::Value::Dict range; // Chromium uses 1-based page ranges, so increment each by 1. range.Set(printing::kSettingPageRangeFrom, from + 1); range.Set(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range)); } else { continue; } } if (!page_range_list.empty()) settings.Set(printing::kSettingPageRange, std::move(page_range_list)); } // Duplex type user wants to use. printing::mojom::DuplexMode duplex_mode = printing::mojom::DuplexMode::kSimplex; options.Get("duplexMode", &duplex_mode); settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode)); // We've already done necessary parameter sanitization at the // JS level, so we can simply pass this through. base::Value media_size(base::Value::Type::DICTIONARY); if (options.Get("mediaSize", &media_size)) settings.Set(printing::kSettingMediaSize, std::move(media_size)); // Set custom dots per inch (dpi) gin_helper::Dictionary dpi_settings; int dpi = 72; if (options.Get("dpi", &dpi_settings)) { int horizontal = 72; dpi_settings.Get("horizontal", &horizontal); settings.Set(printing::kSettingDpiHorizontal, horizontal); int vertical = 72; dpi_settings.Get("vertical", &vertical); settings.Set(printing::kSettingDpiVertical, vertical); } else { settings.Set(printing::kSettingDpiHorizontal, dpi); settings.Set(printing::kSettingDpiVertical, dpi); } print_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name), base::BindOnce(&WebContents::OnGetDeviceNameToUse, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), silent)); } // Partially duplicated and modified from // headless/lib/browser/protocol/page_handler.cc;l=41 v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); // This allows us to track headless printing calls. auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID); auto landscape = settings.GetDict().FindBool("landscape"); auto display_header_footer = settings.GetDict().FindBool("displayHeaderFooter"); auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds"); auto scale = settings.GetDict().FindDouble("scale"); auto paper_width = settings.GetDict().FindInt("paperWidth"); auto paper_height = settings.GetDict().FindInt("paperHeight"); auto margin_top = settings.GetDict().FindIntByDottedPath("margins.top"); auto margin_bottom = settings.GetDict().FindIntByDottedPath("margins.bottom"); auto margin_left = settings.GetDict().FindIntByDottedPath("margins.left"); auto margin_right = settings.GetDict().FindIntByDottedPath("margins.right"); auto page_ranges = *settings.GetDict().FindString("pageRanges"); auto header_template = *settings.GetDict().FindString("headerTemplate"); auto footer_template = *settings.GetDict().FindString("footerTemplate"); auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize"); absl::variant<printing::mojom::PrintPagesParamsPtr, std::string> print_pages_params = print_to_pdf::GetPrintPagesParams( web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(), landscape, display_header_footer, print_background, scale, paper_width, paper_height, margin_top, margin_bottom, margin_left, margin_right, absl::make_optional(header_template), absl::make_optional(footer_template), prefer_css_page_size); if (absl::holds_alternative<std::string>(print_pages_params)) { auto error = absl::get<std::string>(print_pages_params); promise.RejectWithErrorMessage("Invalid print parameters: " + error); return handle; } auto* manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!manager) { promise.RejectWithErrorMessage("Failed to find print manager"); return handle; } auto params = std::move( absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params)); params->params->document_cookie = unique_id.value_or(0); manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges, std::move(params), base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(), std::move(promise))); return handle; } void WebContents::OnPDFCreated( gin_helper::Promise<v8::Local<v8::Value>> promise, PrintViewManagerElectron::PrintResult print_result, scoped_refptr<base::RefCountedMemory> data) { if (print_result != PrintViewManagerElectron::PrintResult::PRINT_SUCCESS) { promise.RejectWithErrorMessage( "Failed to generate PDF: " + PrintViewManagerElectron::PrintResultToString(print_result)); return; } v8::Isolate* isolate = promise.isolate(); gin_helper::Locker locker(isolate); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope( v8::Local<v8::Context>::New(isolate, promise.GetContext())); v8::Local<v8::Value> buffer = node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()), data->size()) .ToLocalChecked(); promise.Resolve(buffer); } #endif void WebContents::AddWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsAddFileSystem(std::string(), path); } void WebContents::RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsRemoveFileSystem(path); } void WebContents::Undo() { web_contents()->Undo(); } void WebContents::Redo() { web_contents()->Redo(); } void WebContents::Cut() { web_contents()->Cut(); } void WebContents::Copy() { web_contents()->Copy(); } void WebContents::Paste() { web_contents()->Paste(); } void WebContents::PasteAndMatchStyle() { web_contents()->PasteAndMatchStyle(); } void WebContents::Delete() { web_contents()->Delete(); } void WebContents::SelectAll() { web_contents()->SelectAll(); } void WebContents::Unselect() { web_contents()->CollapseSelection(); } void WebContents::Replace(const std::u16string& word) { web_contents()->Replace(word); } void WebContents::ReplaceMisspelling(const std::u16string& word) { web_contents()->ReplaceMisspelling(word); } uint32_t WebContents::FindInPage(gin::Arguments* args) { std::u16string search_text; if (!args->GetNext(&search_text) || search_text.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must provide a non-empty search content"); return 0; } uint32_t request_id = ++find_in_page_request_id_; gin_helper::Dictionary dict; auto options = blink::mojom::FindOptions::New(); if (args->GetNext(&dict)) { dict.Get("forward", &options->forward); dict.Get("matchCase", &options->match_case); dict.Get("findNext", &options->new_session); } web_contents()->Find(request_id, search_text, std::move(options)); return request_id; } void WebContents::StopFindInPage(content::StopFindAction action) { web_contents()->StopFinding(action); } void WebContents::ShowDefinitionForSelection() { #if BUILDFLAG(IS_MAC) auto* const view = web_contents()->GetRenderWidgetHostView(); if (view) view->ShowDefinitionForSelection(); #endif } void WebContents::CopyImageAt(int x, int y) { auto* const host = web_contents()->GetPrimaryMainFrame(); if (host) host->CopyImageAt(x, y); } void WebContents::Focus() { // Focusing on WebContents does not automatically focus the window on macOS // and Linux, do it manually to match the behavior on Windows. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) if (owner_window()) owner_window()->Focus(true); #endif web_contents()->Focus(); } #if !BUILDFLAG(IS_MAC) bool WebContents::IsFocused() const { auto* view = web_contents()->GetRenderWidgetHostView(); if (!view) return false; if (GetType() != Type::kBackgroundPage) { auto* window = web_contents()->GetNativeView()->GetToplevelWindow(); if (window && !window->IsVisible()) return false; } return view->HasFocus(); } #endif void WebContents::SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event) { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); blink::WebInputEvent::Type type = gin::GetWebInputEventType(isolate, input_event); if (blink::WebInputEvent::IsMouseEventType(type)) { blink::WebMouseEvent mouse_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); #endif } else { rwh->ForwardMouseEvent(mouse_event); } return; } } else if (blink::WebInputEvent::IsKeyboardEventType(type)) { content::NativeWebKeyboardEvent keyboard_event( blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow()); if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) { rwh->ForwardKeyboardEvent(keyboard_event); return; } } else if (type == blink::WebInputEvent::Type::kMouseWheel) { blink::WebMouseWheelEvent mouse_wheel_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); #endif } else { // Chromium expects phase info in wheel events (and applies a // DCHECK to verify it). See: https://crbug.com/756524. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); // Send a synthetic wheel event with phaseEnded to finish scrolling. mouse_wheel_event.has_synthetic_phase = true; mouse_wheel_event.delta_x = 0; mouse_wheel_event.delta_y = 0; mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kEventNonBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); } return; } } isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object"))); } void WebContents::BeginFrameSubscription(gin::Arguments* args) { bool only_dirty = false; FrameSubscriber::FrameCaptureCallback callback; if (args->Length() > 1) { if (!args->GetNext(&only_dirty)) { args->ThrowError(); return; } } if (!args->GetNext(&callback)) { args->ThrowError(); return; } frame_subscriber_ = std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty); } void WebContents::EndFrameSubscription() { frame_subscriber_.reset(); } void WebContents::StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args) { base::FilePath file; std::vector<base::FilePath> files; if (!item.Get("files", &files) && item.Get("file", &file)) { files.push_back(file); } v8::Local<v8::Value> icon_value; if (!item.Get("icon", &icon_value)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'icon' parameter is required"); return; } NativeImage* icon = nullptr; if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) || icon->image().IsEmpty()) { return; } // Start dragging. if (!files.empty()) { base::CurrentThread::ScopedNestableTaskAllower allow; DragFileItems(files, icon->image(), web_contents()->GetNativeView()); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must specify either 'file' or 'files' option"); } } v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) { gfx::Rect rect; gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // get rect arguments if they exist args->GetNext(&rect); auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view) { promise.Resolve(gfx::Image()); return handle; } #if !BUILDFLAG(IS_MAC) // If the view's renderer is suspended this may fail on Windows/Linux - // bail if so. See CopyFromSurface in // content/public/browser/render_widget_host_view.h. auto* rfh = web_contents()->GetPrimaryMainFrame(); if (rfh && rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) { promise.Resolve(gfx::Image()); return handle; } #endif // BUILDFLAG(IS_MAC) // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); const float scale = display::Screen::GetScreen() ->GetDisplayNearestView(native_view) .device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, base::BindOnce(&OnCapturePageDone, std::move(promise))); return handle; } void WebContents::IncrementCapturerCount(gin::Arguments* args) { gfx::Size size; bool stay_hidden = false; bool stay_awake = false; // get size arguments if they exist args->GetNext(&size); // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); std::ignore = web_contents() ->IncrementCapturerCount(size, stay_hidden, stay_awake) .Release(); } void WebContents::DecrementCapturerCount(gin::Arguments* args) { bool stay_hidden = false; bool stay_awake = false; // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); web_contents()->DecrementCapturerCount(stay_hidden, stay_awake); } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const content::WebCursor& webcursor) { const ui::Cursor& cursor = webcursor.cursor(); if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor), gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()), cursor.image_scale_factor(), gfx::Size(cursor.custom_bitmap().width(), cursor.custom_bitmap().height()), cursor.custom_hotspot()); } else { Emit("cursor-changed", CursorTypeToString(cursor)); } } bool WebContents::IsGuest() const { return type_ == Type::kWebView; } void WebContents::AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id) { attached_ = true; if (guest_delegate_) guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id); } bool WebContents::IsOffScreen() const { #if BUILDFLAG(ENABLE_OSR) return type_ == Type::kOffScreen; #else return false; #endif } #if BUILDFLAG(ENABLE_OSR) void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) { Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap)); } void WebContents::StartPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(true); } void WebContents::StopPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(false); } bool WebContents::IsPainting() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv && osr_wcv->IsPainting(); } void WebContents::SetFrameRate(int frame_rate) { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetFrameRate(frame_rate); } int WebContents::GetFrameRate() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv ? osr_wcv->GetFrameRate() : 0; } #endif void WebContents::Invalidate() { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); #endif } else { auto* const window = owner_window(); if (window) window->Invalidate(); } } gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) { if (IsOffScreen() && wc == web_contents()) { auto* relay = NativeWindowRelay::FromWebContents(web_contents()); if (relay) { auto* owner_window = relay->GetNativeWindow(); return owner_window ? owner_window->GetSize() : gfx::Size(); } } return gfx::Size(); } void WebContents::SetZoomLevel(double level) { zoom_controller_->SetZoomLevel(level); } double WebContents::GetZoomLevel() const { return zoom_controller_->GetZoomLevel(); } void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) { if (factor < std::numeric_limits<double>::epsilon()) { thrower.ThrowError("'zoomFactor' must be a double greater than 0.0"); return; } auto level = blink::PageZoomFactorToZoomLevel(factor); SetZoomLevel(level); } double WebContents::GetZoomFactor() const { auto level = GetZoomLevel(); return blink::PageZoomLevelToZoomFactor(level); } void WebContents::SetTemporaryZoomLevel(double level) { zoom_controller_->SetTemporaryZoomLevel(level); } void WebContents::DoGetZoomLevel( electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback callback) { std::move(callback).Run(GetZoomLevel()); } std::vector<base::FilePath> WebContents::GetPreloadPaths() const { auto result = SessionPreferences::GetValidPreloads(GetBrowserContext()); if (auto* web_preferences = WebContentsPreferences::From(web_contents())) { base::FilePath preload; if (web_preferences->GetPreloadPath(&preload)) { result.emplace_back(preload); } } return result; } v8::Local<v8::Value> WebContents::GetLastWebPreferences( v8::Isolate* isolate) const { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (!web_preferences) return v8::Null(isolate); return gin::ConvertToV8(isolate, *web_preferences->last_preference()); } v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow( v8::Isolate* isolate) const { if (owner_window()) return BrowserWindow::From(isolate, owner_window()); else return v8::Null(isolate); } v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) { return v8::Local<v8::Value>::New(isolate, session_); } content::WebContents* WebContents::HostWebContents() const { if (!embedder_) return nullptr; return embedder_->web_contents(); } void WebContents::SetEmbedder(const WebContents* embedder) { if (embedder) { NativeWindow* owner_window = nullptr; auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents()); if (relay) { owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); content::RenderWidgetHostView* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->Hide(); rwhv->Show(); } } } void WebContents::SetDevToolsWebContents(const WebContents* devtools) { if (inspectable_web_contents_) inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents()); } v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const { gfx::NativeView ptr = web_contents()->GetNativeView(); auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr), sizeof(gfx::NativeView)); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) { if (devtools_web_contents_.IsEmpty()) return v8::Null(isolate); else return v8::Local<v8::Value>::New(isolate, devtools_web_contents_); } v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) { if (debugger_.IsEmpty()) { auto handle = electron::api::Debugger::Create(isolate, web_contents()); debugger_.Reset(isolate, handle.ToV8()); } return v8::Local<v8::Value>::New(isolate, debugger_); } content::RenderFrameHost* WebContents::MainFrame() { return web_contents()->GetPrimaryMainFrame(); } void WebContents::NotifyUserActivation() { content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame(); if (frame) frame->NotifyUserActivation( blink::mojom::UserActivationNotificationType::kInteraction); } void WebContents::SetImageAnimationPolicy(const std::string& new_policy) { auto* web_preferences = WebContentsPreferences::From(web_contents()); web_preferences->SetImageAnimationPolicy(new_policy); web_contents()->OnWebPreferencesChanged(); } v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("Failed to create memory dump"); return handle; } auto pid = frame_host->GetProcess()->GetProcess().Pid(); v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext()); memory_instrumentation::MemoryInstrumentation::GetInstance() ->RequestGlobalDumpForPid( pid, std::vector<std::string>(), base::BindOnce(&ElectronBindings::DidReceiveMemoryDump, std::move(context), std::move(promise), pid)); return handle; } v8::Local<v8::Promise> WebContents::TakeHeapSnapshot( v8::Isolate* isolate, const base::FilePath& file_path) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); base::ThreadRestrictions::ScopedAllowIO allow_io; base::File file(file_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); if (!file.IsValid()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } if (!frame_host->IsRenderFrameLive()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } // This dance with `base::Owned` is to ensure that the interface stays alive // until the callback is called. Otherwise it would be closed at the end of // this function. auto electron_renderer = std::make_unique<mojo::Remote<mojom::ElectronRenderer>>(); frame_host->GetRemoteInterfaces()->GetInterface( electron_renderer->BindNewPipeAndPassReceiver()); auto* raw_ptr = electron_renderer.get(); (*raw_ptr)->TakeHeapSnapshot( mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())), base::BindOnce( [](mojo::Remote<mojom::ElectronRenderer>* ep, gin_helper::Promise<void> promise, bool success) { if (success) { promise.Resolve(); } else { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } void WebContents::UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) { Emit("preferred-size-changed", pref_size); } bool WebContents::CanOverscrollContent() { return false; } std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) { return ShowEyeDropper(frame, listener); } void WebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener), params); } void WebContents::EnumerateDirectory( content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path); } bool WebContents::IsFullscreenForTabOrPending( const content::WebContents* source) { if (!owner_window()) return html_fullscreen_; bool in_transition = owner_window()->fullscreen_transition_state() != NativeWindow::FullScreenTransitionState::NONE; bool is_html_transition = owner_window()->fullscreen_transition_type() == NativeWindow::FullScreenTransitionType::HTML; return html_fullscreen_ || (in_transition && is_html_transition); } bool WebContents::TakeFocus(content::WebContents* source, bool reverse) { if (source && source->GetOutermostWebContents() == source) { // If this is the outermost web contents and the user has tabbed or // shift + tabbed through all the elements, reset the focus back to // the first or last element so that it doesn't stay in the body. source->FocusThroughTabTraversal(reverse); return true; } return false; } content::PictureInPictureResult WebContents::EnterPictureInPicture( content::WebContents* web_contents) { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) return PictureInPictureWindowManager::GetInstance() ->EnterVideoPictureInPicture(web_contents); #else return content::PictureInPictureResult::kNotSupported; #endif } void WebContents::ExitPictureInPicture() { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); #endif } void WebContents::DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) { base::FilePath path; auto it = saved_files_.find(url); if (it != saved_files_.end() && !save_as) { path = it->second; } else { file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.title = url; settings.default_path = base::FilePath::FromUTF8Unsafe(url); if (!file_dialog::ShowSaveDialogSync(settings, &path)) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "canceledSaveURL", base::Value(url)); return; } } saved_files_[url] = path; // Notify DevTools. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "savedURL", base::Value(url), base::Value(path.AsUTF8Unsafe())); file_task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteToFile, path, content)); } void WebContents::DevToolsAppendToFile(const std::string& url, const std::string& content) { auto it = saved_files_.find(url); if (it == saved_files_.end()) return; // Notify DevTools. inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL", base::Value(url)); file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&AppendToFile, it->second, content)); } void WebContents::DevToolsRequestFileSystems() { auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); if (file_system_paths.empty()) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List())); return; } std::vector<FileSystem> file_systems; for (const auto& file_system_path : file_system_paths) { base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path.first); std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id, file_system_path.first, file_system_path.second); file_systems.push_back(file_system); } base::Value::List file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(std::move(file_system_value))); } void WebContents::DevToolsAddFileSystem( const std::string& type, const base::FilePath& file_system_path) { base::FilePath path = file_system_path; if (path.empty()) { std::vector<base::FilePath> paths; file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY; if (!file_dialog::ShowOpenDialogSync(settings, &paths)) return; path = paths[0]; } std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe())) return; FileSystem file_system = CreateFileSystemStruct( GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type); base::Value::Dict file_system_value = CreateFileSystemValue(file_system); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->SetKey(path.AsUTF8Unsafe(), base::Value(type)); std::string error = ""; // No error inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemAdded", base::Value(error), base::Value(std::move(file_system_value))); } void WebContents::DevToolsRemoveFileSystem( const base::FilePath& file_system_path) { if (!inspectable_web_contents_) return; std::string path = file_system_path.AsUTF8Unsafe(); storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath( file_system_path); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->RemoveKey(path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemRemoved", base::Value(path)); } void WebContents::DevToolsIndexPath( int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsIndexingDone(request_id, file_system_path); return; } if (devtools_indexing_jobs_.count(request_id) != 0) return; std::vector<std::string> excluded_folders; std::unique_ptr<base::Value> parsed_excluded_folders = base::JSONReader::ReadDeprecated(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetListDeprecated()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsSearchCompleted(request_id, file_system_path, std::vector<std::string>()); return; } devtools_file_system_indexer_->SearchInPath( file_system_path, query, base::BindRepeating(&WebContents::OnDevToolsSearchCompleted, weak_factory_.GetWeakPtr(), request_id, file_system_path)); } void WebContents::DevToolsSetEyeDropperActive(bool active) { auto* web_contents = GetWebContents(); if (!web_contents) return; if (active) { eye_dropper_ = std::make_unique<DevToolsEyeDropper>( web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper, base::Unretained(this))); } else { eye_dropper_.reset(); } } void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) { base::Value::Dict color; color.Set("r", r); color.Set("g", g); color.Set("b", b); color.Set("a", a); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color))); } #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel WebContents::GetDevToolsWindowIcon() { return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{}; } #endif #if BUILDFLAG(IS_LINUX) void WebContents::GetDevToolsWindowWMClass(std::string* name, std::string* class_name) { *class_name = Browser::Get()->GetName(); *name = base::ToLowerASCII(*class_name); } #endif void WebContents::OnDevToolsIndexingWorkCalculated( int request_id, const std::string& file_system_path, int total_work) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id), base::Value(file_system_path), base::Value(total_work)); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingWorked", base::Value(request_id), base::Value(file_system_path), base::Value(worked)); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone", base::Value(request_id), base::Value(file_system_path)); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::Value::List file_paths_value; for (const auto& file_path : file_paths) file_paths_value.Append(file_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "searchCompleted", base::Value(request_id), base::Value(file_system_path), base::Value(std::move(file_paths_value))); } void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) { // Window is already in fullscreen mode, save the state. if (enter_fullscreen && owner_window_->IsFullscreen()) { native_fullscreen_ = true; UpdateHtmlApiFullscreen(true); return; } // Exit html fullscreen state but not window's fullscreen mode. if (!enter_fullscreen && native_fullscreen_) { UpdateHtmlApiFullscreen(false); return; } // Set fullscreen on window if allowed. auto* web_preferences = WebContentsPreferences::From(GetWebContents()); bool html_fullscreenable = web_preferences ? !web_preferences->ShouldDisableHtmlFullscreenWindowResize() : true; if (html_fullscreenable) owner_window_->SetFullScreen(enter_fullscreen); UpdateHtmlApiFullscreen(enter_fullscreen); native_fullscreen_ = false; } void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) { if (fullscreen == is_html_fullscreen()) return; html_fullscreen_ = fullscreen; // Notify renderer of the html fullscreen change. web_contents() ->GetRenderViewHost() ->GetWidget() ->SynchronizeVisualProperties(); // The embedder WebContents is separated from the frame tree of webview, so // we must manually sync their fullscreen states. if (embedder_) embedder_->SetHtmlApiFullscreen(fullscreen); if (fullscreen) { Emit("enter-html-full-screen"); owner_window_->NotifyWindowEnterHtmlFullScreen(); } else { Emit("leave-html-full-screen"); owner_window_->NotifyWindowLeaveHtmlFullScreen(); } // Make sure all child webviews quit html fullscreen. if (!fullscreen && !IsGuest()) { auto* manager = WebViewManager::GetWebViewManager(web_contents()); manager->ForEachGuest( web_contents(), base::BindRepeating([](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); api_web_contents->SetHtmlApiFullscreen(false); return false; })); } } // static v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = "WebContents"; templ->Set( gin::StringToSymbol(isolate, "isDestroyed"), gin::CreateFunctionTemplate( isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed), options)); // We use gin_helper::ObjectTemplateBuilder instead of // gin::ObjectTemplateBuilder here to handle the fact that WebContents is // destroyable. return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("getBackgroundThrottling", &WebContents::GetBackgroundThrottling) .SetMethod("setBackgroundThrottling", &WebContents::SetBackgroundThrottling) .SetMethod("getProcessId", &WebContents::GetProcessID) .SetMethod("getOSProcessId", &WebContents::GetOSProcessID) .SetMethod("equal", &WebContents::Equal) .SetMethod("_loadURL", &WebContents::LoadURL) .SetMethod("reload", &WebContents::Reload) .SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache) .SetMethod("downloadURL", &WebContents::DownloadURL) .SetMethod("getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) .SetMethod("stop", &WebContents::Stop) .SetMethod("canGoBack", &WebContents::CanGoBack) .SetMethod("goBack", &WebContents::GoBack) .SetMethod("canGoForward", &WebContents::CanGoForward) .SetMethod("goForward", &WebContents::GoForward) .SetMethod("canGoToOffset", &WebContents::CanGoToOffset) .SetMethod("goToOffset", &WebContents::GoToOffset) .SetMethod("canGoToIndex", &WebContents::CanGoToIndex) .SetMethod("goToIndex", &WebContents::GoToIndex) .SetMethod("getActiveIndex", &WebContents::GetActiveIndex) .SetMethod("clearHistory", &WebContents::ClearHistory) .SetMethod("length", &WebContents::GetHistoryLength) .SetMethod("isCrashed", &WebContents::IsCrashed) .SetMethod("forcefullyCrashRenderer", &WebContents::ForcefullyCrashRenderer) .SetMethod("setUserAgent", &WebContents::SetUserAgent) .SetMethod("getUserAgent", &WebContents::GetUserAgent) .SetMethod("savePage", &WebContents::SavePage) .SetMethod("openDevTools", &WebContents::OpenDevTools) .SetMethod("closeDevTools", &WebContents::CloseDevTools) .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened) .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused) .SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation) .SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation) .SetMethod("toggleDevTools", &WebContents::ToggleDevTools) .SetMethod("inspectElement", &WebContents::InspectElement) .SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts) .SetMethod("setAudioMuted", &WebContents::SetAudioMuted) .SetMethod("isAudioMuted", &WebContents::IsAudioMuted) .SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible) .SetMethod("undo", &WebContents::Undo) .SetMethod("redo", &WebContents::Redo) .SetMethod("cut", &WebContents::Cut) .SetMethod("copy", &WebContents::Copy) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("replace", &WebContents::Replace) .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling) .SetMethod("findInPage", &WebContents::FindInPage) .SetMethod("stopFindInPage", &WebContents::StopFindInPage) .SetMethod("focus", &WebContents::Focus) .SetMethod("isFocused", &WebContents::IsFocused) .SetMethod("sendInputEvent", &WebContents::SendInputEvent) .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("startDrag", &WebContents::StartDrag) .SetMethod("attachToIframe", &WebContents::AttachToIframe) .SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame) .SetMethod("isOffscreen", &WebContents::IsOffScreen) #if BUILDFLAG(ENABLE_OSR) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) #endif .SetMethod("invalidate", &WebContents::Invalidate) .SetMethod("setZoomLevel", &WebContents::SetZoomLevel) .SetMethod("getZoomLevel", &WebContents::GetZoomLevel) .SetMethod("setZoomFactor", &WebContents::SetZoomFactor) .SetMethod("getZoomFactor", &WebContents::GetZoomFactor) .SetMethod("getType", &WebContents::GetType) .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths) .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker) .SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker) .SetMethod("inspectSharedWorkerById", &WebContents::InspectSharedWorkerById) .SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers) #if BUILDFLAG(ENABLE_PRINTING) .SetMethod("_print", &WebContents::Print) .SetMethod("_printToPDF", &WebContents::PrintToPDF) #endif .SetMethod("_setNextChildWebPreferences", &WebContents::SetNextChildWebPreferences) .SetMethod("addWorkSpace", &WebContents::AddWorkSpace) .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("showDefinitionForSelection", &WebContents::ShowDefinitionForSelection) .SetMethod("copyImageAt", &WebContents::CopyImageAt) .SetMethod("capturePage", &WebContents::CapturePage) .SetMethod("setEmbedder", &WebContents::SetEmbedder) .SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents) .SetMethod("getNativeView", &WebContents::GetNativeView) .SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount) .SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount) .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot) .SetMethod("setImageAnimationPolicy", &WebContents::SetImageAnimationPolicy) .SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo) .SetProperty("id", &WebContents::ID) .SetProperty("session", &WebContents::Session) .SetProperty("hostWebContents", &WebContents::HostWebContents) .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents) .SetProperty("debugger", &WebContents::Debugger) .SetProperty("mainFrame", &WebContents::MainFrame) .Build(); } const char* WebContents::GetTypeName() { return "WebContents"; } ElectronBrowserContext* WebContents::GetBrowserContext() const { return static_cast<ElectronBrowserContext*>( web_contents()->GetBrowserContext()); } // static gin::Handle<WebContents> WebContents::New( v8::Isolate* isolate, const gin_helper::Dictionary& options) { gin::Handle<WebContents> handle = gin::CreateHandle(isolate, new WebContents(isolate, options)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static gin::Handle<WebContents> WebContents::CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) { gin::Handle<WebContents> handle = gin::CreateHandle( isolate, new WebContents(isolate, std::move(web_contents), type)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static WebContents* WebContents::From(content::WebContents* web_contents) { if (!web_contents) return nullptr; auto* data = static_cast<UserDataLink*>( web_contents->GetUserData(kElectronApiWebContentsKey)); return data ? data->web_contents.get() : nullptr; } // static gin::Handle<WebContents> WebContents::FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents) { WebContents* api_web_contents = From(web_contents); if (!api_web_contents) { api_web_contents = new WebContents(isolate, web_contents); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, api_web_contents, "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } } return gin::CreateHandle(isolate, api_web_contents); } // static gin::Handle<WebContents> WebContents::CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences) { // Check if webPreferences has |webContents| option. gin::Handle<WebContents> web_contents; if (web_preferences.GetHidden("webContents", &web_contents) && !web_contents.IsEmpty()) { // Set webPreferences from options if using an existing webContents. // These preferences will be used when the webContent launches new // render processes. auto* existing_preferences = WebContentsPreferences::From(web_contents->web_contents()); gin_helper::Dictionary web_preferences_dict; if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(), &web_preferences_dict)) { existing_preferences->SetFromDictionary(web_preferences_dict); absl::optional<SkColor> color = existing_preferences->GetBackgroundColor(); web_contents->web_contents()->SetPageBaseBackgroundColor(color); // Because web preferences don't recognize transparency, // only set rwhv background color if a color exists auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView(); if (rwhv && color.has_value()) SetBackgroundColor(rwhv, color.value()); } } else { // Create one if not. web_contents = WebContents::New(isolate, web_preferences); } return web_contents; } // static WebContents* WebContents::FromID(int32_t id) { return GetAllWebContents().Lookup(id); } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace electron::api namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) { WebContents* contents = WebContents::FromID(id); return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } gin::Handle<WebContents> WebContentsFromDevToolsTargetID( v8::Isolate* isolate, std::string target_id) { auto agent_host = content::DevToolsAgentHost::GetForId(target_id); WebContents* contents = agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr; return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8( v8::Isolate* isolate) { std::vector<gin::Handle<WebContents>> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue())); } return list; } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); dict.SetMethod("fromId", &WebContentsFromID); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
32,705
<webview>.capturePage() test very unreliable
the `<webview>.capturePage() returns a Promise with a NativeImage` test was disabled in https://github.com/electron/electron/pull/32419 due to severe flakiness. Follow up & fix.
https://github.com/electron/electron/issues/32705
https://github.com/electron/electron/pull/35213
4cb57ad1a0e7096336694fdfcbab54f7068265fe
81766707fcc2f234785e1907c25c094a4a27adb7
2022-02-02T00:21:28Z
c++
2022-08-15T08:06:02Z
spec-main/webview-spec.ts
import * as path from 'path'; import * as url from 'url'; import { BrowserWindow, session, ipcMain, app, WebContents } from 'electron/main'; import { closeAllWindows } from './window-helpers'; import { emittedOnce, emittedUntil } from './events-helpers'; import { ifit, delay, defer, itremote, useRemoteContext } from './spec-helpers'; import { expect } from 'chai'; import * as http from 'http'; import { AddressInfo } from 'net'; declare let WebView: any; 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, '..', 'spec', '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 emittedOnce(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 emittedOnce(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 emittedOnce(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 emittedOnce(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 emittedOnce(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 = emittedOnce(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 = emittedOnce(w, 'ready-to-show'); const pongSignal1 = emittedOnce(ipcMain, 'pong'); w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html')); await pongSignal1; const pongSignal2 = emittedOnce(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 emittedOnce(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 = emittedOnce(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 = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(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.replace(/\\/g, '/')}/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); // 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); 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 emittedOnce(ipcMain, 'answer'); expect(runtimeId).to.match(/^[a-z]{32}$/); expect(tabId).to.equal(childWebContentsId); }); }); 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 = emittedOnce(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 emittedOnce(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 = emittedOnce(w.webContents, 'did-attach-webview'); const readyPromise = emittedOnce(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 = emittedOnce(w.webContents, 'did-attach-webview'); 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); const loadWebViewWindow = async () => { const w = new BrowserWindow({ webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); const attachPromise = emittedOnce(w.webContents, 'did-attach-webview'); const loadPromise = emittedOnce(w.webContents, 'did-finish-load'); const readyPromise = emittedOnce(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 delay(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 = emittedOnce(ipcMain, 'fullscreenchange'); await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await parentFullscreen; expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.true(); const close = emittedOnce(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 = emittedOnce(ipcMain, 'fullscreenchange'); const enterHTMLFS = emittedOnce(w.webContents, 'enter-html-full-screen'); const leaveHTMLFS = emittedOnce(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 = emittedOnce(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 = emittedOnce(w, 'enter-full-screen'); await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); await webview.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; await delay(0); expect(w.isFullScreen()).to.be.false(); const close = emittedOnce(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 = emittedOnce(w, 'enter-full-screen'); await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); await leaveFullScreen; await delay(0); expect(w.isFullScreen()).to.be.false(); const close = emittedOnce(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 = emittedOnce(w.webContents, 'did-attach-webview'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const enterFSWindow = emittedOnce(w, 'enter-html-full-screen'); const enterFSWebview = emittedOnce(webContents, 'enter-html-full-screen'); await webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFSWindow; await enterFSWebview; const leaveFSWindow = emittedOnce(w, 'leave-html-full-screen'); const leaveFSWebview = emittedOnce(webContents, 'leave-html-full-screen'); webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); await leaveFSWebview; await leaveFSWindow; const close = emittedOnce(w, 'closed'); w.close(); await close; }); it('should support user gesture', async () => { const [w, webview] = await loadWebViewWindow(); const waitForEnterHtmlFullScreen = emittedOnce(webview, 'enter-html-full-screen'); const jsScript = "document.querySelector('video').webkitRequestFullscreen()"; webview.executeJavaScript(jsScript, true); await waitForEnterHtmlFullScreen; const close = emittedOnce(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 emittedOnce(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 emittedOnce(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 emittedOnce(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 emittedOnce(ipcMain, 'answer'); const expectedContent = 'Blocked a frame with origin "file://" from accessing a cross-origin frame.'; expect(content).to.equal(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 emittedOnce(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 emittedOnce(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 emittedOnce(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 = emittedOnce(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/media.html`, partition, nodeintegration: 'on' }); const [, webViewContents] = await emittedOnce(app, 'web-contents-created'); setUpRequestHandler(webViewContents.id, 'media'); const [, errorName] = await errorFromRenderer; expect(errorName).to.equal('PermissionDeniedError'); }); it('emits when using navigator.geolocation api', async () => { const errorFromRenderer = emittedOnce(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/geolocation.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await emittedOnce(app, 'web-contents-created'); 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 = emittedOnce(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/midi.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await emittedOnce(app, 'web-contents-created'); 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 = emittedOnce(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/midi-sysex.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await emittedOnce(app, 'web-contents-created'); 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 emittedOnce(app, 'web-contents-created'); await setUpRequestHandler(webViewContents.id, 'openExternal'); }); it('emits when using Notification.requestPermission', async () => { const errorFromRenderer = emittedOnce(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/notification.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await emittedOnce(app, 'web-contents-created'); 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(`{ document.querySelectorAll('webview').forEach(el => 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(resolve => w.addEventListener('ipc-message', resolve, { once: true })); const message = 'boom!'; w.sendToFrame(frameId, 'ping', message); const { channel, args } = await new Promise(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(0, '127.0.0.1', () => { const port = (server.address() as AddressInfo).port; loadWebView(w, { httpreferrer: referrer, src: `http://127.0.0.1:${port}` }); }); }); 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(`{ document.querySelectorAll('webview').forEach(el => 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 uri = await new Promise<string>(resolve => server.listen(0, '127.0.0.1', () => { resolve(`http://127.0.0.1:${(server.address() as AddressInfo).port}`); })); defer(() => { server.close(); }); const event = await loadWebViewAndWaitForEvent(w, { src: `${uri}/302` }, 'did-redirect-navigation'); expect(event.url).to.equal(`${uri}/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 clicked', async () => { const { url } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/webview-will-navigate.html` }, 'will-navigate'); expect(url).to.equal('http://host/'); }); }); 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}) })`); }); }); 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(() => {}); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; 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 new Promise(resolve => setTimeout(resolve)); 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'); }); }); }); });
closed
electron/electron
https://github.com/electron/electron
32,705
<webview>.capturePage() test very unreliable
the `<webview>.capturePage() returns a Promise with a NativeImage` test was disabled in https://github.com/electron/electron/pull/32419 due to severe flakiness. Follow up & fix.
https://github.com/electron/electron/issues/32705
https://github.com/electron/electron/pull/35213
4cb57ad1a0e7096336694fdfcbab54f7068265fe
81766707fcc2f234785e1907c25c094a4a27adb7
2022-02-02T00:21:28Z
c++
2022-08-15T08:06:02Z
spec/webview-spec.js
const { expect } = require('chai'); const path = require('path'); const http = require('http'); const url = require('url'); const { ipcRenderer } = require('electron'); const { emittedOnce, waitForEvent } = require('./events-helpers'); const { ifdescribe, ifit, delay } = require('./spec-helpers'); const features = process._linkedBinding('electron_common_features'); const nativeModulesEnabled = !process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS; /* Most of the APIs here don't use standard callbacks */ /* eslint-disable standard/no-callback-literal */ describe('<webview> tag', function () { this.timeout(3 * 60 * 1000); const fixtures = path.join(__dirname, 'fixtures'); let webview = null; const loadWebView = async (webview, attributes = {}) => { for (const [name, value] of Object.entries(attributes)) { webview.setAttribute(name, value); } document.body.appendChild(webview); await waitForEvent(webview, 'did-finish-load'); return webview; }; const startLoadingWebViewAndWaitForMessage = async (webview, attributes = {}) => { loadWebView(webview, attributes); // Don't wait for load to be finished. const event = await waitForEvent(webview, 'console-message'); return event.message; }; beforeEach(() => { webview = new WebView(); }); afterEach(() => { if (!document.body.contains(webview)) { document.body.appendChild(webview); } webview.remove(); }); // 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('<webview>.reload()', () => { it('should emit beforeunload handler', async () => { await loadWebView(webview, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/beforeunload-false.html` }); // Event handler has to be added before reload. const waitForOnbeforeunload = waitForEvent(webview, 'ipc-message'); webview.reload(); const { channel } = await waitForOnbeforeunload; expect(channel).to.equal('onbeforeunload'); }); }); describe('<webview>.goForward()', () => { it('should work after a replaced history entry', (done) => { let loadCount = 1; const listener = (e) => { if (loadCount === 1) { 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(); } else if (loadCount === 2) { 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.removeEventListener('ipc-message', listener); } }; const loadListener = () => { try { if (loadCount === 1) { webview.src = `file://${fixtures}/pages/base-page.html`; } else if (loadCount === 2) { expect(webview.canGoBack()).to.be.true(); expect(webview.canGoForward()).to.be.false(); webview.goBack(); } else if (loadCount === 3) { webview.goForward(); } else if (loadCount === 4) { expect(webview.canGoBack()).to.be.true(); expect(webview.canGoForward()).to.be.false(); webview.removeEventListener('did-finish-load', loadListener); done(); } loadCount += 1; } catch (e) { done(e); } }; webview.addEventListener('ipc-message', listener); webview.addEventListener('did-finish-load', loadListener); loadWebView(webview, { nodeintegration: 'on', src: `file://${fixtures}/pages/history-replace.html` }); }); }); // FIXME: https://github.com/electron/electron/issues/19397 xdescribe('<webview>.clearHistory()', () => { it('should clear the navigation history', async () => { const message = waitForEvent(webview, 'ipc-message'); await loadWebView(webview, { nodeintegration: 'on', src: `file://${fixtures}/pages/history.html` }); const event = await message; expect(event.channel).to.equal('history'); expect(event.args[0]).to.equal(2); expect(webview.canGoBack()).to.be.true(); webview.clearHistory(); expect(webview.canGoBack()).to.be.false(); }); }); describe('basic auth', () => { const auth = require('basic-auth'); it('should authenticate with correct credentials', (done) => { 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'); } server.close(); }); server.listen(0, '127.0.0.1', () => { const port = server.address().port; webview.addEventListener('ipc-message', (e) => { try { expect(e.channel).to.equal(message); done(); } catch (e) { done(e); } }); loadWebView(webview, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/basic-auth.html?port=${port}` }); }); }); }); describe('executeJavaScript', () => { it('can return the result of the executed script', async () => { await loadWebView(webview, { src: 'about:blank' }); const jsScript = "'4'+2"; const expectedResult = '42'; const result = await webview.executeJavaScript(jsScript); expect(result).to.equal(expectedResult); }); }); it('supports inserting CSS', async () => { await loadWebView(webview, { src: `file://${fixtures}/pages/base-page.html` }); await webview.insertCSS('body { background-repeat: round; }'); const result = await webview.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('round'); }); it('supports removing inserted CSS', async () => { await loadWebView(webview, { src: `file://${fixtures}/pages/base-page.html` }); const key = await webview.insertCSS('body { background-repeat: round; }'); await webview.removeInsertedCSS(key); const result = await webview.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('repeat'); }); describe('sendInputEvent', () => { it('can send keyboard event', async () => { loadWebView(webview, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/onkeyup.html` }); await waitForEvent(webview, 'dom-ready'); const waitForIpcMessage = waitForEvent(webview, 'ipc-message'); 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 () => { loadWebView(webview, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/onmouseup.html` }); await waitForEvent(webview, 'dom-ready'); const waitForIpcMessage = waitForEvent(webview, 'ipc-message'); 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('media-started-playing media-paused events', () => { beforeEach(function () { if (!document.createElement('audio').canPlayType('audio/wav')) { this.skip(); } }); it('emits when audio starts and stops playing', async () => { await loadWebView(webview, { src: `file://${fixtures}/pages/base-page.html` }); // With the new autoplay policy, audio elements must be unmuted // see https://goo.gl/xX8pDD. const source = ` const audio = document.createElement("audio") audio.src = "../assets/tone.wav" document.body.appendChild(audio); audio.play() `; webview.executeJavaScript(source, true); await waitForEvent(webview, 'media-started-playing'); webview.executeJavaScript('document.querySelector("audio").pause()', true); await waitForEvent(webview, 'media-paused'); }); }); describe('<webview>.getWebContentsId', () => { it('can return the WebContents ID', async () => { const src = 'about:blank'; await loadWebView(webview, { src }); expect(webview.getWebContentsId()).to.be.a('number'); }); }); // TODO(nornagon): this seems to have become much less reliable as of // https://github.com/electron/electron/pull/32419. Tracked at // https://github.com/electron/electron/issues/32705. describe.skip('<webview>.capturePage()', () => { before(function () { // TODO(miniak): figure out why this is failing on windows if (process.platform === 'win32') { this.skip(); } }); it('returns a Promise with a NativeImage', async () => { const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E'; await loadWebView(webview, { src }); const image = await 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); }); }); 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(webview, { src }); await expect(webview.printToPDF(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(webview, { src }); const data = await webview.printToPDF({}); expect(data).to.be.an.instanceof(Uint8Array).that.is.not.empty(); }); }); describe('DOM events', () => { let div; beforeEach(() => { div = document.createElement('div'); div.style.width = '100px'; div.style.height = '10px'; div.style.overflow = 'hidden'; webview.style.height = '100%'; webview.style.width = '100%'; }); afterEach(() => { if (div != null) div.remove(); }); const generateSpecs = (description, sandbox) => { describe(description, () => { // TODO(nornagon): disabled during chromium roll 2019-06-11 due to a // 'ResizeObserver loop limit exceeded' error on Windows xit('emits resize events', async () => { const firstResizeSignal = waitForEvent(webview, 'resize'); const domReadySignal = waitForEvent(webview, 'dom-ready'); webview.src = `file://${fixtures}/pages/a.html`; webview.webpreferences = `sandbox=${sandbox ? 'yes' : 'no'}`; div.appendChild(webview); document.body.appendChild(div); const firstResizeEvent = await firstResizeSignal; expect(firstResizeEvent.target).to.equal(webview); expect(firstResizeEvent.newWidth).to.equal(100); expect(firstResizeEvent.newHeight).to.equal(10); await domReadySignal; const secondResizeSignal = waitForEvent(webview, 'resize'); const newWidth = 1234; const newHeight = 789; div.style.width = `${newWidth}px`; div.style.height = `${newHeight}px`; const secondResizeEvent = await secondResizeSignal; expect(secondResizeEvent.target).to.equal(webview); expect(secondResizeEvent.newWidth).to.equal(newWidth); expect(secondResizeEvent.newHeight).to.equal(newHeight); }); it('emits focus event', async () => { const domReadySignal = waitForEvent(webview, 'dom-ready'); webview.src = `file://${fixtures}/pages/a.html`; webview.webpreferences = `sandbox=${sandbox ? 'yes' : 'no'}`; document.body.appendChild(webview); await domReadySignal; // If this test fails, check if webview.focus() still works. const focusSignal = waitForEvent(webview, 'focus'); webview.focus(); await focusSignal; }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); });
closed
electron/electron
https://github.com/electron/electron
32,705
<webview>.capturePage() test very unreliable
the `<webview>.capturePage() returns a Promise with a NativeImage` test was disabled in https://github.com/electron/electron/pull/32419 due to severe flakiness. Follow up & fix.
https://github.com/electron/electron/issues/32705
https://github.com/electron/electron/pull/35213
4cb57ad1a0e7096336694fdfcbab54f7068265fe
81766707fcc2f234785e1907c25c094a4a27adb7
2022-02-02T00:21:28Z
c++
2022-08-15T08:06:02Z
spec-main/webview-spec.ts
import * as path from 'path'; import * as url from 'url'; import { BrowserWindow, session, ipcMain, app, WebContents } from 'electron/main'; import { closeAllWindows } from './window-helpers'; import { emittedOnce, emittedUntil } from './events-helpers'; import { ifit, delay, defer, itremote, useRemoteContext } from './spec-helpers'; import { expect } from 'chai'; import * as http from 'http'; import { AddressInfo } from 'net'; declare let WebView: any; 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, '..', 'spec', '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 emittedOnce(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 emittedOnce(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 emittedOnce(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 emittedOnce(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 emittedOnce(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 = emittedOnce(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 = emittedOnce(w, 'ready-to-show'); const pongSignal1 = emittedOnce(ipcMain, 'pong'); w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html')); await pongSignal1; const pongSignal2 = emittedOnce(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 emittedOnce(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 = emittedOnce(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 = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(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.replace(/\\/g, '/')}/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); // 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); 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 emittedOnce(ipcMain, 'answer'); expect(runtimeId).to.match(/^[a-z]{32}$/); expect(tabId).to.equal(childWebContentsId); }); }); 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 = emittedOnce(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 emittedOnce(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 = emittedOnce(w.webContents, 'did-attach-webview'); const readyPromise = emittedOnce(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 = emittedOnce(w.webContents, 'did-attach-webview'); 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); const loadWebViewWindow = async () => { const w = new BrowserWindow({ webPreferences: { webviewTag: true, nodeIntegration: true, contextIsolation: false } }); const attachPromise = emittedOnce(w.webContents, 'did-attach-webview'); const loadPromise = emittedOnce(w.webContents, 'did-finish-load'); const readyPromise = emittedOnce(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 delay(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 = emittedOnce(ipcMain, 'fullscreenchange'); await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await parentFullscreen; expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.true(); const close = emittedOnce(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 = emittedOnce(ipcMain, 'fullscreenchange'); const enterHTMLFS = emittedOnce(w.webContents, 'enter-html-full-screen'); const leaveHTMLFS = emittedOnce(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 = emittedOnce(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 = emittedOnce(w, 'enter-full-screen'); await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); await webview.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; await delay(0); expect(w.isFullScreen()).to.be.false(); const close = emittedOnce(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 = emittedOnce(w, 'enter-full-screen'); await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); await leaveFullScreen; await delay(0); expect(w.isFullScreen()).to.be.false(); const close = emittedOnce(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 = emittedOnce(w.webContents, 'did-attach-webview'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const enterFSWindow = emittedOnce(w, 'enter-html-full-screen'); const enterFSWebview = emittedOnce(webContents, 'enter-html-full-screen'); await webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFSWindow; await enterFSWebview; const leaveFSWindow = emittedOnce(w, 'leave-html-full-screen'); const leaveFSWebview = emittedOnce(webContents, 'leave-html-full-screen'); webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); await leaveFSWebview; await leaveFSWindow; const close = emittedOnce(w, 'closed'); w.close(); await close; }); it('should support user gesture', async () => { const [w, webview] = await loadWebViewWindow(); const waitForEnterHtmlFullScreen = emittedOnce(webview, 'enter-html-full-screen'); const jsScript = "document.querySelector('video').webkitRequestFullscreen()"; webview.executeJavaScript(jsScript, true); await waitForEnterHtmlFullScreen; const close = emittedOnce(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 emittedOnce(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 emittedOnce(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 emittedOnce(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 emittedOnce(ipcMain, 'answer'); const expectedContent = 'Blocked a frame with origin "file://" from accessing a cross-origin frame.'; expect(content).to.equal(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 emittedOnce(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 emittedOnce(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 emittedOnce(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 = emittedOnce(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/media.html`, partition, nodeintegration: 'on' }); const [, webViewContents] = await emittedOnce(app, 'web-contents-created'); setUpRequestHandler(webViewContents.id, 'media'); const [, errorName] = await errorFromRenderer; expect(errorName).to.equal('PermissionDeniedError'); }); it('emits when using navigator.geolocation api', async () => { const errorFromRenderer = emittedOnce(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/geolocation.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await emittedOnce(app, 'web-contents-created'); 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 = emittedOnce(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/midi.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await emittedOnce(app, 'web-contents-created'); 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 = emittedOnce(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/midi-sysex.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await emittedOnce(app, 'web-contents-created'); 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 emittedOnce(app, 'web-contents-created'); await setUpRequestHandler(webViewContents.id, 'openExternal'); }); it('emits when using Notification.requestPermission', async () => { const errorFromRenderer = emittedOnce(ipcMain, 'message'); loadWebView(w.webContents, { src: `file://${fixtures}/pages/permissions/notification.html`, partition, nodeintegration: 'on', webpreferences: 'contextIsolation=no' }); const [, webViewContents] = await emittedOnce(app, 'web-contents-created'); 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(`{ document.querySelectorAll('webview').forEach(el => 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(resolve => w.addEventListener('ipc-message', resolve, { once: true })); const message = 'boom!'; w.sendToFrame(frameId, 'ping', message); const { channel, args } = await new Promise(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(0, '127.0.0.1', () => { const port = (server.address() as AddressInfo).port; loadWebView(w, { httpreferrer: referrer, src: `http://127.0.0.1:${port}` }); }); }); 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(`{ document.querySelectorAll('webview').forEach(el => 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 uri = await new Promise<string>(resolve => server.listen(0, '127.0.0.1', () => { resolve(`http://127.0.0.1:${(server.address() as AddressInfo).port}`); })); defer(() => { server.close(); }); const event = await loadWebViewAndWaitForEvent(w, { src: `${uri}/302` }, 'did-redirect-navigation'); expect(event.url).to.equal(`${uri}/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 clicked', async () => { const { url } = await loadWebViewAndWaitForEvent(w, { src: `file://${fixtures}/pages/webview-will-navigate.html` }, 'will-navigate'); expect(url).to.equal('http://host/'); }); }); 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}) })`); }); }); 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(() => {}); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; 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 new Promise(resolve => setTimeout(resolve)); 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'); }); }); }); });
closed
electron/electron
https://github.com/electron/electron
32,705
<webview>.capturePage() test very unreliable
the `<webview>.capturePage() returns a Promise with a NativeImage` test was disabled in https://github.com/electron/electron/pull/32419 due to severe flakiness. Follow up & fix.
https://github.com/electron/electron/issues/32705
https://github.com/electron/electron/pull/35213
4cb57ad1a0e7096336694fdfcbab54f7068265fe
81766707fcc2f234785e1907c25c094a4a27adb7
2022-02-02T00:21:28Z
c++
2022-08-15T08:06:02Z
spec/webview-spec.js
const { expect } = require('chai'); const path = require('path'); const http = require('http'); const url = require('url'); const { ipcRenderer } = require('electron'); const { emittedOnce, waitForEvent } = require('./events-helpers'); const { ifdescribe, ifit, delay } = require('./spec-helpers'); const features = process._linkedBinding('electron_common_features'); const nativeModulesEnabled = !process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS; /* Most of the APIs here don't use standard callbacks */ /* eslint-disable standard/no-callback-literal */ describe('<webview> tag', function () { this.timeout(3 * 60 * 1000); const fixtures = path.join(__dirname, 'fixtures'); let webview = null; const loadWebView = async (webview, attributes = {}) => { for (const [name, value] of Object.entries(attributes)) { webview.setAttribute(name, value); } document.body.appendChild(webview); await waitForEvent(webview, 'did-finish-load'); return webview; }; const startLoadingWebViewAndWaitForMessage = async (webview, attributes = {}) => { loadWebView(webview, attributes); // Don't wait for load to be finished. const event = await waitForEvent(webview, 'console-message'); return event.message; }; beforeEach(() => { webview = new WebView(); }); afterEach(() => { if (!document.body.contains(webview)) { document.body.appendChild(webview); } webview.remove(); }); // 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('<webview>.reload()', () => { it('should emit beforeunload handler', async () => { await loadWebView(webview, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/beforeunload-false.html` }); // Event handler has to be added before reload. const waitForOnbeforeunload = waitForEvent(webview, 'ipc-message'); webview.reload(); const { channel } = await waitForOnbeforeunload; expect(channel).to.equal('onbeforeunload'); }); }); describe('<webview>.goForward()', () => { it('should work after a replaced history entry', (done) => { let loadCount = 1; const listener = (e) => { if (loadCount === 1) { 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(); } else if (loadCount === 2) { 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.removeEventListener('ipc-message', listener); } }; const loadListener = () => { try { if (loadCount === 1) { webview.src = `file://${fixtures}/pages/base-page.html`; } else if (loadCount === 2) { expect(webview.canGoBack()).to.be.true(); expect(webview.canGoForward()).to.be.false(); webview.goBack(); } else if (loadCount === 3) { webview.goForward(); } else if (loadCount === 4) { expect(webview.canGoBack()).to.be.true(); expect(webview.canGoForward()).to.be.false(); webview.removeEventListener('did-finish-load', loadListener); done(); } loadCount += 1; } catch (e) { done(e); } }; webview.addEventListener('ipc-message', listener); webview.addEventListener('did-finish-load', loadListener); loadWebView(webview, { nodeintegration: 'on', src: `file://${fixtures}/pages/history-replace.html` }); }); }); // FIXME: https://github.com/electron/electron/issues/19397 xdescribe('<webview>.clearHistory()', () => { it('should clear the navigation history', async () => { const message = waitForEvent(webview, 'ipc-message'); await loadWebView(webview, { nodeintegration: 'on', src: `file://${fixtures}/pages/history.html` }); const event = await message; expect(event.channel).to.equal('history'); expect(event.args[0]).to.equal(2); expect(webview.canGoBack()).to.be.true(); webview.clearHistory(); expect(webview.canGoBack()).to.be.false(); }); }); describe('basic auth', () => { const auth = require('basic-auth'); it('should authenticate with correct credentials', (done) => { 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'); } server.close(); }); server.listen(0, '127.0.0.1', () => { const port = server.address().port; webview.addEventListener('ipc-message', (e) => { try { expect(e.channel).to.equal(message); done(); } catch (e) { done(e); } }); loadWebView(webview, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/basic-auth.html?port=${port}` }); }); }); }); describe('executeJavaScript', () => { it('can return the result of the executed script', async () => { await loadWebView(webview, { src: 'about:blank' }); const jsScript = "'4'+2"; const expectedResult = '42'; const result = await webview.executeJavaScript(jsScript); expect(result).to.equal(expectedResult); }); }); it('supports inserting CSS', async () => { await loadWebView(webview, { src: `file://${fixtures}/pages/base-page.html` }); await webview.insertCSS('body { background-repeat: round; }'); const result = await webview.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('round'); }); it('supports removing inserted CSS', async () => { await loadWebView(webview, { src: `file://${fixtures}/pages/base-page.html` }); const key = await webview.insertCSS('body { background-repeat: round; }'); await webview.removeInsertedCSS(key); const result = await webview.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('repeat'); }); describe('sendInputEvent', () => { it('can send keyboard event', async () => { loadWebView(webview, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/onkeyup.html` }); await waitForEvent(webview, 'dom-ready'); const waitForIpcMessage = waitForEvent(webview, 'ipc-message'); 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 () => { loadWebView(webview, { nodeintegration: 'on', webpreferences: 'contextIsolation=no', src: `file://${fixtures}/pages/onmouseup.html` }); await waitForEvent(webview, 'dom-ready'); const waitForIpcMessage = waitForEvent(webview, 'ipc-message'); 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('media-started-playing media-paused events', () => { beforeEach(function () { if (!document.createElement('audio').canPlayType('audio/wav')) { this.skip(); } }); it('emits when audio starts and stops playing', async () => { await loadWebView(webview, { src: `file://${fixtures}/pages/base-page.html` }); // With the new autoplay policy, audio elements must be unmuted // see https://goo.gl/xX8pDD. const source = ` const audio = document.createElement("audio") audio.src = "../assets/tone.wav" document.body.appendChild(audio); audio.play() `; webview.executeJavaScript(source, true); await waitForEvent(webview, 'media-started-playing'); webview.executeJavaScript('document.querySelector("audio").pause()', true); await waitForEvent(webview, 'media-paused'); }); }); describe('<webview>.getWebContentsId', () => { it('can return the WebContents ID', async () => { const src = 'about:blank'; await loadWebView(webview, { src }); expect(webview.getWebContentsId()).to.be.a('number'); }); }); // TODO(nornagon): this seems to have become much less reliable as of // https://github.com/electron/electron/pull/32419. Tracked at // https://github.com/electron/electron/issues/32705. describe.skip('<webview>.capturePage()', () => { before(function () { // TODO(miniak): figure out why this is failing on windows if (process.platform === 'win32') { this.skip(); } }); it('returns a Promise with a NativeImage', async () => { const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E'; await loadWebView(webview, { src }); const image = await 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); }); }); 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(webview, { src }); await expect(webview.printToPDF(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(webview, { src }); const data = await webview.printToPDF({}); expect(data).to.be.an.instanceof(Uint8Array).that.is.not.empty(); }); }); describe('DOM events', () => { let div; beforeEach(() => { div = document.createElement('div'); div.style.width = '100px'; div.style.height = '10px'; div.style.overflow = 'hidden'; webview.style.height = '100%'; webview.style.width = '100%'; }); afterEach(() => { if (div != null) div.remove(); }); const generateSpecs = (description, sandbox) => { describe(description, () => { // TODO(nornagon): disabled during chromium roll 2019-06-11 due to a // 'ResizeObserver loop limit exceeded' error on Windows xit('emits resize events', async () => { const firstResizeSignal = waitForEvent(webview, 'resize'); const domReadySignal = waitForEvent(webview, 'dom-ready'); webview.src = `file://${fixtures}/pages/a.html`; webview.webpreferences = `sandbox=${sandbox ? 'yes' : 'no'}`; div.appendChild(webview); document.body.appendChild(div); const firstResizeEvent = await firstResizeSignal; expect(firstResizeEvent.target).to.equal(webview); expect(firstResizeEvent.newWidth).to.equal(100); expect(firstResizeEvent.newHeight).to.equal(10); await domReadySignal; const secondResizeSignal = waitForEvent(webview, 'resize'); const newWidth = 1234; const newHeight = 789; div.style.width = `${newWidth}px`; div.style.height = `${newHeight}px`; const secondResizeEvent = await secondResizeSignal; expect(secondResizeEvent.target).to.equal(webview); expect(secondResizeEvent.newWidth).to.equal(newWidth); expect(secondResizeEvent.newHeight).to.equal(newHeight); }); it('emits focus event', async () => { const domReadySignal = waitForEvent(webview, 'dom-ready'); webview.src = `file://${fixtures}/pages/a.html`; webview.webpreferences = `sandbox=${sandbox ? 'yes' : 'no'}`; document.body.appendChild(webview); await domReadySignal; // If this test fails, check if webview.focus() still works. const focusSignal = waitForEvent(webview, 'focus'); webview.focus(); await focusSignal; }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); });
closed
electron/electron
https://github.com/electron/electron
32,926
[Bug]: Renderer process crashes on power resume
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 13.1.7 ### What operating system are you using? Windows ### Operating System Version Windows 10 build 19043 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Application should resume after power resume ### Actual Behavior White screen in browser window after power resume (not always) ### Testcase Gist URL _No response_ ### Additional Information There are no algorithm to 100% reproduce, just wake up computer and you may see white screen in electron app Access violation exception Call stack: AppName.exe!uv__wake_all_loops() Line 170 C AppName.exe!uv__system_resume_callback(void * Context, unsigned long Type, void * Setting) Line 41 C powrprof.dll!PowerpResumeSuspendCallback() Unknown UMPDC.dll!00007ffd8b3d37c3() Unknown UMPDC.dll!00007ffd8b3d371d() Unknown UMPDC.dll!00007ffd8b3d35ca() Unknown ntdll.dll!TppAlpcpExecuteCallback() Unknown ntdll.dll!TppWorkerThread() Unknown KERNEL32.DLL!BaseThreadInitThunk() Unknown ntdll.dll!RtlUserThreadStart() Unknown
https://github.com/electron/electron/issues/32926
https://github.com/electron/electron/pull/35322
9c2d89476c4e0af61458e2951e4042ff8db3da2b
cbc1ee5775375b7ec92f8c38bcbb157833b1b8a0
2022-02-16T08:17:58Z
c++
2022-08-15T14:40:52Z
shell/common/node_bindings.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/node_bindings.h" #include <algorithm> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/base_paths.h" #include "base/command_line.h" #include "base/environment.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_paths.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "shell/browser/api/electron_api_app.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/electron_command_line.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/gin_helper/locker.h" #include "shell/common/gin_helper/microtasks_scope.h" #include "shell/common/mac/main_application_bundle.h" #include "shell/common/node_includes.h" #include "third_party/blink/renderer/bindings/core/v8/v8_initializer.h" // nogncheck #if !defined(MAS_BUILD) #include "shell/common/crash_keys.h" #endif #define ELECTRON_BUILTIN_MODULES(V) \ V(electron_browser_app) \ V(electron_browser_auto_updater) \ V(electron_browser_browser_view) \ V(electron_browser_content_tracing) \ V(electron_browser_crash_reporter) \ V(electron_browser_dialog) \ V(electron_browser_event) \ V(electron_browser_event_emitter) \ V(electron_browser_global_shortcut) \ V(electron_browser_in_app_purchase) \ V(electron_browser_menu) \ V(electron_browser_message_port) \ V(electron_browser_native_theme) \ V(electron_browser_net) \ V(electron_browser_notification) \ V(electron_browser_power_monitor) \ V(electron_browser_power_save_blocker) \ V(electron_browser_protocol) \ V(electron_browser_printing) \ V(electron_browser_push_notifications) \ V(electron_browser_safe_storage) \ V(electron_browser_session) \ V(electron_browser_screen) \ V(electron_browser_system_preferences) \ V(electron_browser_base_window) \ V(electron_browser_tray) \ V(electron_browser_view) \ V(electron_browser_web_contents) \ V(electron_browser_web_contents_view) \ V(electron_browser_web_frame_main) \ V(electron_browser_web_view_manager) \ V(electron_browser_window) \ V(electron_common_asar) \ V(electron_common_clipboard) \ V(electron_common_command_line) \ V(electron_common_environment) \ V(electron_common_features) \ V(electron_common_native_image) \ V(electron_common_shell) \ V(electron_common_v8_util) \ V(electron_renderer_context_bridge) \ V(electron_renderer_crash_reporter) \ V(electron_renderer_ipc) \ V(electron_renderer_web_frame) #define ELECTRON_VIEWS_MODULES(V) V(electron_browser_image_view) #define ELECTRON_DESKTOP_CAPTURER_MODULE(V) V(electron_browser_desktop_capturer) #define ELECTRON_TESTING_MODULE(V) V(electron_common_testing) // This is used to load built-in modules. Instead of using // __attribute__((constructor)), we call the _register_<modname> // function for each built-in modules explicitly. This is only // forward declaration. The definitions are in each module's // implementation when calling the NODE_LINKED_MODULE_CONTEXT_AWARE. #define V(modname) void _register_##modname(); ELECTRON_BUILTIN_MODULES(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_MODULES(V) #endif #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER) ELECTRON_DESKTOP_CAPTURER_MODULE(V) #endif #if DCHECK_IS_ON() ELECTRON_TESTING_MODULE(V) #endif #undef V namespace { void stop_and_close_uv_loop(uv_loop_t* loop) { uv_stop(loop); auto const ensure_closing = [](uv_handle_t* handle, void*) { // We should be using the UvHandle wrapper everywhere, in which case // all handles should already be in a closing state... DCHECK(uv_is_closing(handle)); // ...but if a raw handle got through, through, do the right thing anyway if (!uv_is_closing(handle)) { uv_close(handle, nullptr); } }; uv_walk(loop, ensure_closing, nullptr); // All remaining handles are in a closing state now. // Pump the event loop so that they can finish closing. for (;;) if (uv_run(loop, UV_RUN_DEFAULT) == 0) break; DCHECK_EQ(0, uv_loop_alive(loop)); } bool g_is_initialized = false; void V8FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; #if !defined(MAS_BUILD) electron::crash_keys::SetCrashKey("electron.v8-fatal.message", message); electron::crash_keys::SetCrashKey("electron.v8-fatal.location", location); #endif volatile int* zero = nullptr; *zero = 0; } bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context, v8::Local<v8::String>) { // If we're running with contextIsolation enabled in the renderer process, // fall back to Blink's logic. v8::Isolate* isolate = context->GetIsolate(); if (node::Environment::GetCurrent(isolate) == nullptr) { if (gin_helper::Locker::IsBrowserProcess()) return false; return blink::V8Initializer::WasmCodeGenerationCheckCallbackInMainThread( context, v8::String::Empty(isolate)); } return node::AllowWasmCodeGenerationCallback(context, v8::String::Empty(isolate)); } void ErrorMessageListener(v8::Local<v8::Message> message, v8::Local<v8::Value> data) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); gin_helper::MicrotasksScope microtasks_scope( isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); node::Environment* env = node::Environment::GetCurrent(isolate); if (env) { // Emit the after() hooks now that the exception has been handled. // Analogous to node/lib/internal/process/execution.js#L176-L180 if (env->async_hooks()->fields()[node::AsyncHooks::kAfter]) { while (env->async_hooks()->fields()[node::AsyncHooks::kStackLength]) { node::AsyncWrap::EmitAfter(env, env->execution_async_id()); env->async_hooks()->pop_async_context(env->execution_async_id()); } } // Ensure that the async id stack is properly cleared so the async // hook stack does not become corrupted. env->async_hooks()->clear_async_id_stack(); } } const std::unordered_set<base::StringPiece, base::StringPieceHash> GetAllowedDebugOptions() { if (electron::fuses::IsNodeCliInspectEnabled()) { // Only allow DebugOptions in non-ELECTRON_RUN_AS_NODE mode return { "--inspect", "--inspect-brk", "--inspect-port", "--debug", "--debug-brk", "--debug-port", "--inspect-brk-node", "--inspect-publish-uid", }; } // If node CLI inspect support is disabled, allow no debug options. return {}; } // Initialize Node.js cli options to pass to Node.js // See https://nodejs.org/api/cli.html#cli_options void SetNodeCliFlags() { const std::unordered_set<base::StringPiece, base::StringPieceHash> allowed = GetAllowedDebugOptions(); const auto argv = base::CommandLine::ForCurrentProcess()->argv(); std::vector<std::string> args; // TODO(codebytere): We need to set the first entry in args to the // process name owing to src/node_options-inl.h#L286-L290 but this is // redundant and so should be refactored upstream. args.reserve(argv.size() + 1); args.emplace_back("electron"); for (const auto& arg : argv) { #if BUILDFLAG(IS_WIN) const auto& option = base::WideToUTF8(arg); #else const auto& option = arg; #endif const auto stripped = base::StringPiece(option).substr(0, option.find('=')); // Only allow in no-op (--) option or DebugOptions if (allowed.count(stripped) != 0 || stripped == "--") args.push_back(option); } std::vector<std::string> errors; const int exit_code = ProcessGlobalArgs(&args, nullptr, &errors, node::kDisallowedInEnvironment); const std::string err_str = "Error parsing Node.js cli flags "; if (exit_code != 0) { LOG(ERROR) << err_str; } else if (!errors.empty()) { LOG(ERROR) << err_str << base::JoinString(errors, " "); } } // Initialize NODE_OPTIONS to pass to Node.js // See https://nodejs.org/api/cli.html#cli_node_options_options void SetNodeOptions(base::Environment* env) { // Options that are unilaterally disallowed const std::set<std::string> disallowed = { "--openssl-config", "--use-bundled-ca", "--use-openssl-ca", "--force-fips", "--enable-fips"}; // Subset of options allowed in packaged apps const std::set<std::string> allowed_in_packaged = {"--max-http-header-size", "--http-parser"}; if (env->HasVar("NODE_OPTIONS")) { if (electron::fuses::IsNodeOptionsEnabled()) { std::string options; env->GetVar("NODE_OPTIONS", &options); std::vector<std::string> parts = base::SplitString( options, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); bool is_packaged_app = electron::api::App::IsPackaged(); for (const auto& part : parts) { // Strip off values passed to individual NODE_OPTIONs std::string option = part.substr(0, part.find('=')); if (is_packaged_app && allowed_in_packaged.find(option) == allowed_in_packaged.end()) { // Explicitly disallow majority of NODE_OPTIONS in packaged apps LOG(ERROR) << "Most NODE_OPTIONs are not supported in packaged apps." << " See documentation for more details."; options.erase(options.find(option), part.length()); } else if (disallowed.find(option) != disallowed.end()) { // Remove NODE_OPTIONS specifically disallowed for use in Node.js // through Electron owing to constraints like BoringSSL. LOG(ERROR) << "The NODE_OPTION " << option << " is not supported in Electron"; options.erase(options.find(option), part.length()); } } // overwrite new NODE_OPTIONS without unsupported variables env->SetVar("NODE_OPTIONS", options); } else { LOG(ERROR) << "NODE_OPTIONS have been disabled in this app"; env->SetVar("NODE_OPTIONS", ""); } } } } // namespace namespace electron { namespace { base::FilePath GetResourcesPath() { #if BUILDFLAG(IS_MAC) return MainApplicationBundlePath().Append("Contents").Append("Resources"); #else auto* command_line = base::CommandLine::ForCurrentProcess(); base::FilePath exec_path(command_line->GetProgram()); base::PathService::Get(base::FILE_EXE, &exec_path); return exec_path.DirName().Append(FILE_PATH_LITERAL("resources")); #endif } } // namespace NodeBindings::NodeBindings(BrowserEnvironment browser_env) : browser_env_(browser_env) { if (browser_env == BrowserEnvironment::kWorker) { uv_loop_init(&worker_loop_); uv_loop_ = &worker_loop_; } else { uv_loop_ = uv_default_loop(); } // Interrupt embed polling when a handle is started. uv_loop_configure(uv_loop_, UV_LOOP_INTERRUPT_ON_IO_CHANGE); } NodeBindings::~NodeBindings() { // Quit the embed thread. embed_closed_ = true; uv_sem_post(&embed_sem_); WakeupEmbedThread(); // Wait for everything to be done. uv_thread_join(&embed_thread_); // Clear uv. uv_sem_destroy(&embed_sem_); dummy_uv_handle_.reset(); // Clean up worker loop if (in_worker_loop()) stop_and_close_uv_loop(uv_loop_); } void NodeBindings::RegisterBuiltinModules() { #define V(modname) _register_##modname(); ELECTRON_BUILTIN_MODULES(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_MODULES(V) #endif #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER) ELECTRON_DESKTOP_CAPTURER_MODULE(V) #endif #if DCHECK_IS_ON() ELECTRON_TESTING_MODULE(V) #endif #undef V } bool NodeBindings::IsInitialized() { return g_is_initialized; } void NodeBindings::Initialize() { TRACE_EVENT0("electron", "NodeBindings::Initialize"); // Open node's error reporting system for browser process. #if BUILDFLAG(IS_LINUX) // Get real command line in renderer process forked by zygote. if (browser_env_ != BrowserEnvironment::kBrowser) ElectronCommandLine::InitializeFromCommandLine(); #endif // Explicitly register electron's builtin modules. RegisterBuiltinModules(); // Parse and set Node.js cli flags. SetNodeCliFlags(); auto env = base::Environment::Create(); SetNodeOptions(env.get()); std::vector<std::string> argv = {"electron"}; std::vector<std::string> exec_argv; std::vector<std::string> errors; uint64_t process_flags = node::ProcessFlags::kEnableStdioInheritance; if (!fuses::IsNodeOptionsEnabled()) process_flags |= node::ProcessFlags::kDisableNodeOptionsEnv; int exit_code = node::InitializeNodeWithArgs( &argv, &exec_argv, &errors, static_cast<node::ProcessFlags::Flags>(process_flags)); for (const std::string& error : errors) fprintf(stderr, "%s: %s\n", argv[0].c_str(), error.c_str()); if (exit_code != 0) exit(exit_code); #if BUILDFLAG(IS_WIN) // uv_init overrides error mode to suppress the default crash dialog, bring // it back if user wants to show it. if (browser_env_ == BrowserEnvironment::kBrowser || env->HasVar("ELECTRON_DEFAULT_ERROR_MODE")) SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX); #endif g_is_initialized = true; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform) { #if BUILDFLAG(IS_WIN) auto& atom_args = ElectronCommandLine::argv(); std::vector<std::string> args(atom_args.size()); std::transform(atom_args.cbegin(), atom_args.cend(), args.begin(), [](auto& a) { return base::WideToUTF8(a); }); #else auto args = ElectronCommandLine::argv(); #endif // Feed node the path to initialization script. std::string process_type; switch (browser_env_) { case BrowserEnvironment::kBrowser: process_type = "browser"; break; case BrowserEnvironment::kRenderer: process_type = "renderer"; break; case BrowserEnvironment::kWorker: process_type = "worker"; break; } v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary global(isolate, context->Global()); // Do not set DOM globals for renderer process. // We must set this before the node bootstrapper which is run inside // CreateEnvironment if (browser_env_ != BrowserEnvironment::kBrowser) global.Set("_noBrowserGlobals", true); if (browser_env_ == BrowserEnvironment::kBrowser) { const std::vector<std::string> search_paths = {"app.asar", "app", "default_app.asar"}; const std::vector<std::string> app_asar_search_paths = {"app.asar"}; context->Global()->SetPrivate( context, v8::Private::ForApi( isolate, gin::ConvertToV8(isolate, "appSearchPaths").As<v8::String>()), gin::ConvertToV8(isolate, electron::fuses::IsOnlyLoadAppFromAsarEnabled() ? app_asar_search_paths : search_paths)); } std::vector<std::string> exec_args; base::FilePath resources_path = GetResourcesPath(); std::string init_script = "electron/js2c/" + process_type + "_init"; args.insert(args.begin() + 1, init_script); if (!isolate_data_) isolate_data_ = node::CreateIsolateData(isolate, uv_loop_, platform); node::Environment* env; uint64_t flags = node::EnvironmentFlags::kDefaultFlags | node::EnvironmentFlags::kHideConsoleWindows | node::EnvironmentFlags::kNoGlobalSearchPaths; if (browser_env_ != BrowserEnvironment::kBrowser) { // Only one ESM loader can be registered per isolate - // in renderer processes this should be blink. We need to tell Node.js // not to register its handler (overriding blinks) in non-browser processes. flags |= node::EnvironmentFlags::kNoRegisterESMLoader | node::EnvironmentFlags::kNoCreateInspector; } if (!electron::fuses::IsNodeCliInspectEnabled()) { // If --inspect and friends are disabled we also shouldn't listen for // SIGUSR1 flags |= node::EnvironmentFlags::kNoStartDebugSignalHandler; } v8::TryCatch try_catch(isolate); env = node::CreateEnvironment( isolate_data_, context, args, exec_args, static_cast<node::EnvironmentFlags::Flags>(flags)); if (try_catch.HasCaught()) { std::string err_msg = "Failed to initialize node environment in process: " + process_type; v8::Local<v8::Message> message = try_catch.Message(); std::string msg; if (!message.IsEmpty() && gin::ConvertFromV8(isolate, message->Get(), &msg)) err_msg += " , with error: " + msg; LOG(ERROR) << err_msg; } DCHECK(env); // Clean up the global _noBrowserGlobals that we unironically injected into // the global scope if (browser_env_ != BrowserEnvironment::kBrowser) { // We need to bootstrap the env in non-browser processes so that // _noBrowserGlobals is read correctly before we remove it global.Delete("_noBrowserGlobals"); } node::IsolateSettings is; // Use a custom fatal error callback to allow us to add // crash message and location to CrashReports. is.fatal_error_callback = V8FatalErrorCallback; // We don't want to abort either in the renderer or browser processes. // We already listen for uncaught exceptions and handle them there. is.should_abort_on_uncaught_exception_callback = [](v8::Isolate*) { return false; }; // Use a custom callback here to allow us to leverage Blink's logic in the // renderer process. is.allow_wasm_code_generation_callback = AllowWasmCodeGenerationCallback; if (browser_env_ == BrowserEnvironment::kBrowser) { // Node.js requires that microtask checkpoints be explicitly invoked. is.policy = v8::MicrotasksPolicy::kExplicit; } else { // Blink expects the microtasks policy to be kScoped, but Node.js expects it // to be kExplicit. In the renderer, there can be many contexts within the // same isolate, so we don't want to change the existing policy here, which // could be either kExplicit or kScoped depending on whether we're executing // from within a Node.js or a Blink entrypoint. Instead, the policy is // toggled to kExplicit when entering Node.js through UvRunOnce. is.policy = context->GetIsolate()->GetMicrotasksPolicy(); // We do not want to use Node.js' message listener as it interferes with // Blink's. is.flags &= ~node::IsolateSettingsFlags::MESSAGE_LISTENER_WITH_ERROR_LEVEL; // Isolate message listeners are additive (you can add multiple), so instead // we add an extra one here to ensure that the async hook stack is properly // cleared when errors are thrown. context->GetIsolate()->AddMessageListenerWithErrorLevel( ErrorMessageListener, v8::Isolate::kMessageError); // We do not want to use the promise rejection callback that Node.js uses, // because it does not send PromiseRejectionEvents to the global script // context. We need to use the one Blink already provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK; // We do not want to use the stack trace callback that Node.js uses, // because it relies on Node.js being aware of the current Context and // that's not always the case. We need to use the one Blink already // provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK; } node::SetIsolateUpForNode(context->GetIsolate(), is); gin_helper::Dictionary process(context->GetIsolate(), env->process_object()); process.SetReadOnly("type", process_type); process.Set("resourcesPath", resources_path); // The path to helper app. base::FilePath helper_exec_path; base::PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path); process.Set("helperExecPath", helper_exec_path); return env; } void NodeBindings::LoadEnvironment(node::Environment* env) { node::LoadEnvironment(env, node::StartExecutionCallback{}); gin_helper::EmitEvent(env->isolate(), env->process_object(), "loaded"); } void NodeBindings::PrepareEmbedThread() { // IOCP does not change for the process until the loop is recreated, // we ensure that there is only a single polling thread satisfying // the concurrency limit set from CreateIoCompletionPort call by // uv_loop_init for the lifetime of this process. // More background can be found at: // https://github.com/microsoft/vscode/issues/142786#issuecomment-1061673400 if (initialized_) return; // Add dummy handle for libuv, otherwise libuv would quit when there is // nothing to do. uv_async_init(uv_loop_, dummy_uv_handle_.get(), nullptr); // Start worker that will interrupt main loop when having uv events. uv_sem_init(&embed_sem_, 0); uv_thread_create(&embed_thread_, EmbedThreadRunner, this); } void NodeBindings::StartPolling() { // Avoid calling UvRunOnce if the loop is already active, // otherwise it can lead to situations were the number of active // threads processing on IOCP is greater than the concurrency limit. if (initialized_) return; initialized_ = true; // The MessageLoop should have been created, remember the one in main thread. task_runner_ = base::ThreadTaskRunnerHandle::Get(); // Run uv loop for once to give the uv__io_poll a chance to add all events. UvRunOnce(); } void NodeBindings::UvRunOnce() { node::Environment* env = uv_env(); // When doing navigation without restarting renderer process, it may happen // that the node environment is destroyed but the message loop is still there. // In this case we should not run uv loop. if (!env) return; v8::HandleScope handle_scope(env->isolate()); // Enter node context while dealing with uv events. v8::Context::Scope context_scope(env->context()); // Node.js expects `kExplicit` microtasks policy and will run microtasks // checkpoints after every call into JavaScript. Since we use a different // policy in the renderer - switch to `kExplicit` and then drop back to the // previous policy value. auto old_policy = env->isolate()->GetMicrotasksPolicy(); DCHECK_EQ(v8::MicrotasksScope::GetCurrentDepth(env->isolate()), 0); env->isolate()->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall"); // Deal with uv events. int r = uv_run(uv_loop_, UV_RUN_NOWAIT); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_END0("devtools.timeline", "FunctionCall"); env->isolate()->SetMicrotasksPolicy(old_policy); if (r == 0) base::RunLoop().QuitWhenIdle(); // Quit from uv. // Tell the worker thread to continue polling. uv_sem_post(&embed_sem_); } void NodeBindings::WakeupMainThread() { DCHECK(task_runner_); task_runner_->PostTask(FROM_HERE, base::BindOnce(&NodeBindings::UvRunOnce, weak_factory_.GetWeakPtr())); } void NodeBindings::WakeupEmbedThread() { uv_async_send(dummy_uv_handle_.get()); } // static void NodeBindings::EmbedThreadRunner(void* arg) { auto* self = static_cast<NodeBindings*>(arg); while (true) { // Wait for the main loop to deal with events. uv_sem_wait(&self->embed_sem_); if (self->embed_closed_) break; // Wait for something to happen in uv loop. // Note that the PollEvents() is implemented by derived classes, so when // this class is being destructed the PollEvents() would not be available // anymore. Because of it we must make sure we only invoke PollEvents() // when this class is alive. self->PollEvents(); if (self->embed_closed_) break; // Deal with event in main thread. self->WakeupMainThread(); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,926
[Bug]: Renderer process crashes on power resume
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 13.1.7 ### What operating system are you using? Windows ### Operating System Version Windows 10 build 19043 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Application should resume after power resume ### Actual Behavior White screen in browser window after power resume (not always) ### Testcase Gist URL _No response_ ### Additional Information There are no algorithm to 100% reproduce, just wake up computer and you may see white screen in electron app Access violation exception Call stack: AppName.exe!uv__wake_all_loops() Line 170 C AppName.exe!uv__system_resume_callback(void * Context, unsigned long Type, void * Setting) Line 41 C powrprof.dll!PowerpResumeSuspendCallback() Unknown UMPDC.dll!00007ffd8b3d37c3() Unknown UMPDC.dll!00007ffd8b3d371d() Unknown UMPDC.dll!00007ffd8b3d35ca() Unknown ntdll.dll!TppAlpcpExecuteCallback() Unknown ntdll.dll!TppWorkerThread() Unknown KERNEL32.DLL!BaseThreadInitThunk() Unknown ntdll.dll!RtlUserThreadStart() Unknown
https://github.com/electron/electron/issues/32926
https://github.com/electron/electron/pull/35322
9c2d89476c4e0af61458e2951e4042ff8db3da2b
cbc1ee5775375b7ec92f8c38bcbb157833b1b8a0
2022-02-16T08:17:58Z
c++
2022-08-15T14:40:52Z
shell/common/node_bindings.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/node_bindings.h" #include <algorithm> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/base_paths.h" #include "base/command_line.h" #include "base/environment.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_paths.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "shell/browser/api/electron_api_app.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/electron_command_line.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/gin_helper/locker.h" #include "shell/common/gin_helper/microtasks_scope.h" #include "shell/common/mac/main_application_bundle.h" #include "shell/common/node_includes.h" #include "third_party/blink/renderer/bindings/core/v8/v8_initializer.h" // nogncheck #if !defined(MAS_BUILD) #include "shell/common/crash_keys.h" #endif #define ELECTRON_BUILTIN_MODULES(V) \ V(electron_browser_app) \ V(electron_browser_auto_updater) \ V(electron_browser_browser_view) \ V(electron_browser_content_tracing) \ V(electron_browser_crash_reporter) \ V(electron_browser_dialog) \ V(electron_browser_event) \ V(electron_browser_event_emitter) \ V(electron_browser_global_shortcut) \ V(electron_browser_in_app_purchase) \ V(electron_browser_menu) \ V(electron_browser_message_port) \ V(electron_browser_native_theme) \ V(electron_browser_net) \ V(electron_browser_notification) \ V(electron_browser_power_monitor) \ V(electron_browser_power_save_blocker) \ V(electron_browser_protocol) \ V(electron_browser_printing) \ V(electron_browser_push_notifications) \ V(electron_browser_safe_storage) \ V(electron_browser_session) \ V(electron_browser_screen) \ V(electron_browser_system_preferences) \ V(electron_browser_base_window) \ V(electron_browser_tray) \ V(electron_browser_view) \ V(electron_browser_web_contents) \ V(electron_browser_web_contents_view) \ V(electron_browser_web_frame_main) \ V(electron_browser_web_view_manager) \ V(electron_browser_window) \ V(electron_common_asar) \ V(electron_common_clipboard) \ V(electron_common_command_line) \ V(electron_common_environment) \ V(electron_common_features) \ V(electron_common_native_image) \ V(electron_common_shell) \ V(electron_common_v8_util) \ V(electron_renderer_context_bridge) \ V(electron_renderer_crash_reporter) \ V(electron_renderer_ipc) \ V(electron_renderer_web_frame) #define ELECTRON_VIEWS_MODULES(V) V(electron_browser_image_view) #define ELECTRON_DESKTOP_CAPTURER_MODULE(V) V(electron_browser_desktop_capturer) #define ELECTRON_TESTING_MODULE(V) V(electron_common_testing) // This is used to load built-in modules. Instead of using // __attribute__((constructor)), we call the _register_<modname> // function for each built-in modules explicitly. This is only // forward declaration. The definitions are in each module's // implementation when calling the NODE_LINKED_MODULE_CONTEXT_AWARE. #define V(modname) void _register_##modname(); ELECTRON_BUILTIN_MODULES(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_MODULES(V) #endif #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER) ELECTRON_DESKTOP_CAPTURER_MODULE(V) #endif #if DCHECK_IS_ON() ELECTRON_TESTING_MODULE(V) #endif #undef V namespace { void stop_and_close_uv_loop(uv_loop_t* loop) { uv_stop(loop); auto const ensure_closing = [](uv_handle_t* handle, void*) { // We should be using the UvHandle wrapper everywhere, in which case // all handles should already be in a closing state... DCHECK(uv_is_closing(handle)); // ...but if a raw handle got through, through, do the right thing anyway if (!uv_is_closing(handle)) { uv_close(handle, nullptr); } }; uv_walk(loop, ensure_closing, nullptr); // All remaining handles are in a closing state now. // Pump the event loop so that they can finish closing. for (;;) if (uv_run(loop, UV_RUN_DEFAULT) == 0) break; DCHECK_EQ(0, uv_loop_alive(loop)); } bool g_is_initialized = false; void V8FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; #if !defined(MAS_BUILD) electron::crash_keys::SetCrashKey("electron.v8-fatal.message", message); electron::crash_keys::SetCrashKey("electron.v8-fatal.location", location); #endif volatile int* zero = nullptr; *zero = 0; } bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context, v8::Local<v8::String>) { // If we're running with contextIsolation enabled in the renderer process, // fall back to Blink's logic. v8::Isolate* isolate = context->GetIsolate(); if (node::Environment::GetCurrent(isolate) == nullptr) { if (gin_helper::Locker::IsBrowserProcess()) return false; return blink::V8Initializer::WasmCodeGenerationCheckCallbackInMainThread( context, v8::String::Empty(isolate)); } return node::AllowWasmCodeGenerationCallback(context, v8::String::Empty(isolate)); } void ErrorMessageListener(v8::Local<v8::Message> message, v8::Local<v8::Value> data) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); gin_helper::MicrotasksScope microtasks_scope( isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); node::Environment* env = node::Environment::GetCurrent(isolate); if (env) { // Emit the after() hooks now that the exception has been handled. // Analogous to node/lib/internal/process/execution.js#L176-L180 if (env->async_hooks()->fields()[node::AsyncHooks::kAfter]) { while (env->async_hooks()->fields()[node::AsyncHooks::kStackLength]) { node::AsyncWrap::EmitAfter(env, env->execution_async_id()); env->async_hooks()->pop_async_context(env->execution_async_id()); } } // Ensure that the async id stack is properly cleared so the async // hook stack does not become corrupted. env->async_hooks()->clear_async_id_stack(); } } const std::unordered_set<base::StringPiece, base::StringPieceHash> GetAllowedDebugOptions() { if (electron::fuses::IsNodeCliInspectEnabled()) { // Only allow DebugOptions in non-ELECTRON_RUN_AS_NODE mode return { "--inspect", "--inspect-brk", "--inspect-port", "--debug", "--debug-brk", "--debug-port", "--inspect-brk-node", "--inspect-publish-uid", }; } // If node CLI inspect support is disabled, allow no debug options. return {}; } // Initialize Node.js cli options to pass to Node.js // See https://nodejs.org/api/cli.html#cli_options void SetNodeCliFlags() { const std::unordered_set<base::StringPiece, base::StringPieceHash> allowed = GetAllowedDebugOptions(); const auto argv = base::CommandLine::ForCurrentProcess()->argv(); std::vector<std::string> args; // TODO(codebytere): We need to set the first entry in args to the // process name owing to src/node_options-inl.h#L286-L290 but this is // redundant and so should be refactored upstream. args.reserve(argv.size() + 1); args.emplace_back("electron"); for (const auto& arg : argv) { #if BUILDFLAG(IS_WIN) const auto& option = base::WideToUTF8(arg); #else const auto& option = arg; #endif const auto stripped = base::StringPiece(option).substr(0, option.find('=')); // Only allow in no-op (--) option or DebugOptions if (allowed.count(stripped) != 0 || stripped == "--") args.push_back(option); } std::vector<std::string> errors; const int exit_code = ProcessGlobalArgs(&args, nullptr, &errors, node::kDisallowedInEnvironment); const std::string err_str = "Error parsing Node.js cli flags "; if (exit_code != 0) { LOG(ERROR) << err_str; } else if (!errors.empty()) { LOG(ERROR) << err_str << base::JoinString(errors, " "); } } // Initialize NODE_OPTIONS to pass to Node.js // See https://nodejs.org/api/cli.html#cli_node_options_options void SetNodeOptions(base::Environment* env) { // Options that are unilaterally disallowed const std::set<std::string> disallowed = { "--openssl-config", "--use-bundled-ca", "--use-openssl-ca", "--force-fips", "--enable-fips"}; // Subset of options allowed in packaged apps const std::set<std::string> allowed_in_packaged = {"--max-http-header-size", "--http-parser"}; if (env->HasVar("NODE_OPTIONS")) { if (electron::fuses::IsNodeOptionsEnabled()) { std::string options; env->GetVar("NODE_OPTIONS", &options); std::vector<std::string> parts = base::SplitString( options, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); bool is_packaged_app = electron::api::App::IsPackaged(); for (const auto& part : parts) { // Strip off values passed to individual NODE_OPTIONs std::string option = part.substr(0, part.find('=')); if (is_packaged_app && allowed_in_packaged.find(option) == allowed_in_packaged.end()) { // Explicitly disallow majority of NODE_OPTIONS in packaged apps LOG(ERROR) << "Most NODE_OPTIONs are not supported in packaged apps." << " See documentation for more details."; options.erase(options.find(option), part.length()); } else if (disallowed.find(option) != disallowed.end()) { // Remove NODE_OPTIONS specifically disallowed for use in Node.js // through Electron owing to constraints like BoringSSL. LOG(ERROR) << "The NODE_OPTION " << option << " is not supported in Electron"; options.erase(options.find(option), part.length()); } } // overwrite new NODE_OPTIONS without unsupported variables env->SetVar("NODE_OPTIONS", options); } else { LOG(ERROR) << "NODE_OPTIONS have been disabled in this app"; env->SetVar("NODE_OPTIONS", ""); } } } } // namespace namespace electron { namespace { base::FilePath GetResourcesPath() { #if BUILDFLAG(IS_MAC) return MainApplicationBundlePath().Append("Contents").Append("Resources"); #else auto* command_line = base::CommandLine::ForCurrentProcess(); base::FilePath exec_path(command_line->GetProgram()); base::PathService::Get(base::FILE_EXE, &exec_path); return exec_path.DirName().Append(FILE_PATH_LITERAL("resources")); #endif } } // namespace NodeBindings::NodeBindings(BrowserEnvironment browser_env) : browser_env_(browser_env) { if (browser_env == BrowserEnvironment::kWorker) { uv_loop_init(&worker_loop_); uv_loop_ = &worker_loop_; } else { uv_loop_ = uv_default_loop(); } // Interrupt embed polling when a handle is started. uv_loop_configure(uv_loop_, UV_LOOP_INTERRUPT_ON_IO_CHANGE); } NodeBindings::~NodeBindings() { // Quit the embed thread. embed_closed_ = true; uv_sem_post(&embed_sem_); WakeupEmbedThread(); // Wait for everything to be done. uv_thread_join(&embed_thread_); // Clear uv. uv_sem_destroy(&embed_sem_); dummy_uv_handle_.reset(); // Clean up worker loop if (in_worker_loop()) stop_and_close_uv_loop(uv_loop_); } void NodeBindings::RegisterBuiltinModules() { #define V(modname) _register_##modname(); ELECTRON_BUILTIN_MODULES(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_MODULES(V) #endif #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER) ELECTRON_DESKTOP_CAPTURER_MODULE(V) #endif #if DCHECK_IS_ON() ELECTRON_TESTING_MODULE(V) #endif #undef V } bool NodeBindings::IsInitialized() { return g_is_initialized; } void NodeBindings::Initialize() { TRACE_EVENT0("electron", "NodeBindings::Initialize"); // Open node's error reporting system for browser process. #if BUILDFLAG(IS_LINUX) // Get real command line in renderer process forked by zygote. if (browser_env_ != BrowserEnvironment::kBrowser) ElectronCommandLine::InitializeFromCommandLine(); #endif // Explicitly register electron's builtin modules. RegisterBuiltinModules(); // Parse and set Node.js cli flags. SetNodeCliFlags(); auto env = base::Environment::Create(); SetNodeOptions(env.get()); std::vector<std::string> argv = {"electron"}; std::vector<std::string> exec_argv; std::vector<std::string> errors; uint64_t process_flags = node::ProcessFlags::kEnableStdioInheritance; if (!fuses::IsNodeOptionsEnabled()) process_flags |= node::ProcessFlags::kDisableNodeOptionsEnv; int exit_code = node::InitializeNodeWithArgs( &argv, &exec_argv, &errors, static_cast<node::ProcessFlags::Flags>(process_flags)); for (const std::string& error : errors) fprintf(stderr, "%s: %s\n", argv[0].c_str(), error.c_str()); if (exit_code != 0) exit(exit_code); #if BUILDFLAG(IS_WIN) // uv_init overrides error mode to suppress the default crash dialog, bring // it back if user wants to show it. if (browser_env_ == BrowserEnvironment::kBrowser || env->HasVar("ELECTRON_DEFAULT_ERROR_MODE")) SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX); #endif g_is_initialized = true; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform) { #if BUILDFLAG(IS_WIN) auto& atom_args = ElectronCommandLine::argv(); std::vector<std::string> args(atom_args.size()); std::transform(atom_args.cbegin(), atom_args.cend(), args.begin(), [](auto& a) { return base::WideToUTF8(a); }); #else auto args = ElectronCommandLine::argv(); #endif // Feed node the path to initialization script. std::string process_type; switch (browser_env_) { case BrowserEnvironment::kBrowser: process_type = "browser"; break; case BrowserEnvironment::kRenderer: process_type = "renderer"; break; case BrowserEnvironment::kWorker: process_type = "worker"; break; } v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary global(isolate, context->Global()); // Do not set DOM globals for renderer process. // We must set this before the node bootstrapper which is run inside // CreateEnvironment if (browser_env_ != BrowserEnvironment::kBrowser) global.Set("_noBrowserGlobals", true); if (browser_env_ == BrowserEnvironment::kBrowser) { const std::vector<std::string> search_paths = {"app.asar", "app", "default_app.asar"}; const std::vector<std::string> app_asar_search_paths = {"app.asar"}; context->Global()->SetPrivate( context, v8::Private::ForApi( isolate, gin::ConvertToV8(isolate, "appSearchPaths").As<v8::String>()), gin::ConvertToV8(isolate, electron::fuses::IsOnlyLoadAppFromAsarEnabled() ? app_asar_search_paths : search_paths)); } std::vector<std::string> exec_args; base::FilePath resources_path = GetResourcesPath(); std::string init_script = "electron/js2c/" + process_type + "_init"; args.insert(args.begin() + 1, init_script); if (!isolate_data_) isolate_data_ = node::CreateIsolateData(isolate, uv_loop_, platform); node::Environment* env; uint64_t flags = node::EnvironmentFlags::kDefaultFlags | node::EnvironmentFlags::kHideConsoleWindows | node::EnvironmentFlags::kNoGlobalSearchPaths; if (browser_env_ != BrowserEnvironment::kBrowser) { // Only one ESM loader can be registered per isolate - // in renderer processes this should be blink. We need to tell Node.js // not to register its handler (overriding blinks) in non-browser processes. flags |= node::EnvironmentFlags::kNoRegisterESMLoader | node::EnvironmentFlags::kNoCreateInspector; } if (!electron::fuses::IsNodeCliInspectEnabled()) { // If --inspect and friends are disabled we also shouldn't listen for // SIGUSR1 flags |= node::EnvironmentFlags::kNoStartDebugSignalHandler; } v8::TryCatch try_catch(isolate); env = node::CreateEnvironment( isolate_data_, context, args, exec_args, static_cast<node::EnvironmentFlags::Flags>(flags)); if (try_catch.HasCaught()) { std::string err_msg = "Failed to initialize node environment in process: " + process_type; v8::Local<v8::Message> message = try_catch.Message(); std::string msg; if (!message.IsEmpty() && gin::ConvertFromV8(isolate, message->Get(), &msg)) err_msg += " , with error: " + msg; LOG(ERROR) << err_msg; } DCHECK(env); // Clean up the global _noBrowserGlobals that we unironically injected into // the global scope if (browser_env_ != BrowserEnvironment::kBrowser) { // We need to bootstrap the env in non-browser processes so that // _noBrowserGlobals is read correctly before we remove it global.Delete("_noBrowserGlobals"); } node::IsolateSettings is; // Use a custom fatal error callback to allow us to add // crash message and location to CrashReports. is.fatal_error_callback = V8FatalErrorCallback; // We don't want to abort either in the renderer or browser processes. // We already listen for uncaught exceptions and handle them there. is.should_abort_on_uncaught_exception_callback = [](v8::Isolate*) { return false; }; // Use a custom callback here to allow us to leverage Blink's logic in the // renderer process. is.allow_wasm_code_generation_callback = AllowWasmCodeGenerationCallback; if (browser_env_ == BrowserEnvironment::kBrowser) { // Node.js requires that microtask checkpoints be explicitly invoked. is.policy = v8::MicrotasksPolicy::kExplicit; } else { // Blink expects the microtasks policy to be kScoped, but Node.js expects it // to be kExplicit. In the renderer, there can be many contexts within the // same isolate, so we don't want to change the existing policy here, which // could be either kExplicit or kScoped depending on whether we're executing // from within a Node.js or a Blink entrypoint. Instead, the policy is // toggled to kExplicit when entering Node.js through UvRunOnce. is.policy = context->GetIsolate()->GetMicrotasksPolicy(); // We do not want to use Node.js' message listener as it interferes with // Blink's. is.flags &= ~node::IsolateSettingsFlags::MESSAGE_LISTENER_WITH_ERROR_LEVEL; // Isolate message listeners are additive (you can add multiple), so instead // we add an extra one here to ensure that the async hook stack is properly // cleared when errors are thrown. context->GetIsolate()->AddMessageListenerWithErrorLevel( ErrorMessageListener, v8::Isolate::kMessageError); // We do not want to use the promise rejection callback that Node.js uses, // because it does not send PromiseRejectionEvents to the global script // context. We need to use the one Blink already provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK; // We do not want to use the stack trace callback that Node.js uses, // because it relies on Node.js being aware of the current Context and // that's not always the case. We need to use the one Blink already // provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK; } node::SetIsolateUpForNode(context->GetIsolate(), is); gin_helper::Dictionary process(context->GetIsolate(), env->process_object()); process.SetReadOnly("type", process_type); process.Set("resourcesPath", resources_path); // The path to helper app. base::FilePath helper_exec_path; base::PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path); process.Set("helperExecPath", helper_exec_path); return env; } void NodeBindings::LoadEnvironment(node::Environment* env) { node::LoadEnvironment(env, node::StartExecutionCallback{}); gin_helper::EmitEvent(env->isolate(), env->process_object(), "loaded"); } void NodeBindings::PrepareEmbedThread() { // IOCP does not change for the process until the loop is recreated, // we ensure that there is only a single polling thread satisfying // the concurrency limit set from CreateIoCompletionPort call by // uv_loop_init for the lifetime of this process. // More background can be found at: // https://github.com/microsoft/vscode/issues/142786#issuecomment-1061673400 if (initialized_) return; // Add dummy handle for libuv, otherwise libuv would quit when there is // nothing to do. uv_async_init(uv_loop_, dummy_uv_handle_.get(), nullptr); // Start worker that will interrupt main loop when having uv events. uv_sem_init(&embed_sem_, 0); uv_thread_create(&embed_thread_, EmbedThreadRunner, this); } void NodeBindings::StartPolling() { // Avoid calling UvRunOnce if the loop is already active, // otherwise it can lead to situations were the number of active // threads processing on IOCP is greater than the concurrency limit. if (initialized_) return; initialized_ = true; // The MessageLoop should have been created, remember the one in main thread. task_runner_ = base::ThreadTaskRunnerHandle::Get(); // Run uv loop for once to give the uv__io_poll a chance to add all events. UvRunOnce(); } void NodeBindings::UvRunOnce() { node::Environment* env = uv_env(); // When doing navigation without restarting renderer process, it may happen // that the node environment is destroyed but the message loop is still there. // In this case we should not run uv loop. if (!env) return; v8::HandleScope handle_scope(env->isolate()); // Enter node context while dealing with uv events. v8::Context::Scope context_scope(env->context()); // Node.js expects `kExplicit` microtasks policy and will run microtasks // checkpoints after every call into JavaScript. Since we use a different // policy in the renderer - switch to `kExplicit` and then drop back to the // previous policy value. auto old_policy = env->isolate()->GetMicrotasksPolicy(); DCHECK_EQ(v8::MicrotasksScope::GetCurrentDepth(env->isolate()), 0); env->isolate()->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall"); // Deal with uv events. int r = uv_run(uv_loop_, UV_RUN_NOWAIT); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_END0("devtools.timeline", "FunctionCall"); env->isolate()->SetMicrotasksPolicy(old_policy); if (r == 0) base::RunLoop().QuitWhenIdle(); // Quit from uv. // Tell the worker thread to continue polling. uv_sem_post(&embed_sem_); } void NodeBindings::WakeupMainThread() { DCHECK(task_runner_); task_runner_->PostTask(FROM_HERE, base::BindOnce(&NodeBindings::UvRunOnce, weak_factory_.GetWeakPtr())); } void NodeBindings::WakeupEmbedThread() { uv_async_send(dummy_uv_handle_.get()); } // static void NodeBindings::EmbedThreadRunner(void* arg) { auto* self = static_cast<NodeBindings*>(arg); while (true) { // Wait for the main loop to deal with events. uv_sem_wait(&self->embed_sem_); if (self->embed_closed_) break; // Wait for something to happen in uv loop. // Note that the PollEvents() is implemented by derived classes, so when // this class is being destructed the PollEvents() would not be available // anymore. Because of it we must make sure we only invoke PollEvents() // when this class is alive. self->PollEvents(); if (self->embed_closed_) break; // Deal with event in main thread. self->WakeupMainThread(); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,282
[Bug]: WebSerial - SerialPort doesn't open in Electron 20
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.1 ### What operating system are you using? Windows ### Operating System Version Win 10 Pro 19043 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.11 ### Expected Behavior WebSerial API should open a serial port. ### Actual Behavior The ``getInfo`` method works fine, but ``open`` fails to open the port. ### Testcase Gist URL https://gist.github.com/17afc65be515f3a1aec6256cb69f069d https://github.com/rafaelpimpa/electron-webserial-bug-repro ### Additional Information Error thrown is ``NetworkError: Failed to open serial port.`` I didn't use an Arduino to test, but it should work the same, since it works in v19. Reproduction has the same code from the docs.
https://github.com/electron/electron/issues/35282
https://github.com/electron/electron/pull/35306
cbc1ee5775375b7ec92f8c38bcbb157833b1b8a0
672539187c779cf874dfcecc198bcfbdec85aa97
2022-08-09T13:47:55Z
c++
2022-08-15T15:49:20Z
shell/browser/serial/electron_serial_delegate.cc
// Copyright (c) 2020 Microsoft, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/serial/electron_serial_delegate.h" #include <utility> #include "base/feature_list.h" #include "content/public/browser/web_contents.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/serial/serial_chooser_context.h" #include "shell/browser/serial/serial_chooser_context_factory.h" #include "shell/browser/serial/serial_chooser_controller.h" #include "shell/browser/web_contents_permission_helper.h" namespace electron { SerialChooserContext* GetChooserContext(content::RenderFrameHost* frame) { auto* web_contents = content::WebContents::FromRenderFrameHost(frame); auto* browser_context = web_contents->GetBrowserContext(); return SerialChooserContextFactory::GetForBrowserContext(browser_context); } ElectronSerialDelegate::ElectronSerialDelegate() = default; ElectronSerialDelegate::~ElectronSerialDelegate() = default; std::unique_ptr<content::SerialChooser> ElectronSerialDelegate::RunChooser( content::RenderFrameHost* frame, std::vector<blink::mojom::SerialPortFilterPtr> filters, content::SerialChooser::Callback callback) { SerialChooserController* controller = ControllerForFrame(frame); if (controller) { DeleteControllerForFrame(frame); } AddControllerForFrame(frame, std::move(filters), std::move(callback)); // Return a nullptr because the return value isn't used for anything, eg // there is no mechanism to cancel navigator.serial.requestPort(). The return // value is simply used in Chromium to cleanup the chooser UI once the serial // service is destroyed. return nullptr; } bool ElectronSerialDelegate::CanRequestPortPermission( content::RenderFrameHost* frame) { auto* web_contents = content::WebContents::FromRenderFrameHost(frame); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckSerialAccessPermission( web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin()); } bool ElectronSerialDelegate::HasPortPermission( content::RenderFrameHost* frame, const device::mojom::SerialPortInfo& port) { auto* web_contents = content::WebContents::FromRenderFrameHost(frame); auto* browser_context = web_contents->GetBrowserContext(); auto* chooser_context = SerialChooserContextFactory::GetForBrowserContext(browser_context); return chooser_context->HasPortPermission( web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin(), port, frame); } device::mojom::SerialPortManager* ElectronSerialDelegate::GetPortManager( content::RenderFrameHost* frame) { return GetChooserContext(frame)->GetPortManager(); } void ElectronSerialDelegate::AddObserver(content::RenderFrameHost* frame, Observer* observer) { observer_list_.AddObserver(observer); auto* chooser_context = GetChooserContext(frame); if (!port_observation_.IsObserving()) port_observation_.Observe(chooser_context); } void ElectronSerialDelegate::RemoveObserver(content::RenderFrameHost* frame, Observer* observer) { observer_list_.RemoveObserver(observer); } void ElectronSerialDelegate::RevokePortPermissionWebInitiated( content::RenderFrameHost* frame, const base::UnguessableToken& token) { // TODO(nornagon/jkleinsc): pass this on to the chooser context } const device::mojom::SerialPortInfo* ElectronSerialDelegate::GetPortInfo( content::RenderFrameHost* frame, const base::UnguessableToken& token) { // TODO(nornagon/jkleinsc): pass this on to the chooser context return nullptr; } SerialChooserController* ElectronSerialDelegate::ControllerForFrame( content::RenderFrameHost* render_frame_host) { auto mapping = controller_map_.find(render_frame_host); return mapping == controller_map_.end() ? nullptr : mapping->second.get(); } SerialChooserController* ElectronSerialDelegate::AddControllerForFrame( content::RenderFrameHost* render_frame_host, std::vector<blink::mojom::SerialPortFilterPtr> filters, content::SerialChooser::Callback callback) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto controller = std::make_unique<SerialChooserController>( render_frame_host, std::move(filters), 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 ElectronSerialDelegate::DeleteControllerForFrame( content::RenderFrameHost* render_frame_host) { controller_map_.erase(render_frame_host); } // SerialChooserContext::PortObserver: void ElectronSerialDelegate::OnPortAdded( const device::mojom::SerialPortInfo& port) { for (auto& observer : observer_list_) observer.OnPortAdded(port); } void ElectronSerialDelegate::OnPortRemoved( const device::mojom::SerialPortInfo& port) { for (auto& observer : observer_list_) observer.OnPortRemoved(port); } void ElectronSerialDelegate::OnPortManagerConnectionError() { port_observation_.Reset(); for (auto& observer : observer_list_) observer.OnPortManagerConnectionError(); } void ElectronSerialDelegate::OnSerialChooserContextShutdown() { port_observation_.Reset(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,282
[Bug]: WebSerial - SerialPort doesn't open in Electron 20
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.1 ### What operating system are you using? Windows ### Operating System Version Win 10 Pro 19043 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.11 ### Expected Behavior WebSerial API should open a serial port. ### Actual Behavior The ``getInfo`` method works fine, but ``open`` fails to open the port. ### Testcase Gist URL https://gist.github.com/17afc65be515f3a1aec6256cb69f069d https://github.com/rafaelpimpa/electron-webserial-bug-repro ### Additional Information Error thrown is ``NetworkError: Failed to open serial port.`` I didn't use an Arduino to test, but it should work the same, since it works in v19. Reproduction has the same code from the docs.
https://github.com/electron/electron/issues/35282
https://github.com/electron/electron/pull/35306
cbc1ee5775375b7ec92f8c38bcbb157833b1b8a0
672539187c779cf874dfcecc198bcfbdec85aa97
2022-08-09T13:47:55Z
c++
2022-08-15T15:49:20Z
shell/browser/serial/serial_chooser_context.cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "shell/browser/serial/serial_chooser_context.h" #include <memory> #include <string> #include <utility> #include "base/base64.h" #include "base/containers/contains.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "content/public/browser/device_service.h" #include "content/public/browser/web_contents.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "shell/browser/electron_permission_manager.h" #include "shell/browser/web_contents_permission_helper.h" namespace electron { constexpr char kPortNameKey[] = "name"; constexpr char kTokenKey[] = "token"; #if BUILDFLAG(IS_WIN) const char kDeviceInstanceIdKey[] = "device_instance_id"; #else const char kVendorIdKey[] = "vendor_id"; const char kProductIdKey[] = "product_id"; const char kSerialNumberKey[] = "serial_number"; #if BUILDFLAG(IS_MAC) const char kUsbDriverKey[] = "usb_driver"; #endif // BUILDFLAG(IS_MAC) #endif // BUILDFLAG(IS_WIN) std::string EncodeToken(const base::UnguessableToken& token) { const uint64_t data[2] = {token.GetHighForSerialization(), token.GetLowForSerialization()}; std::string buffer; base::Base64Encode( base::StringPiece(reinterpret_cast<const char*>(&data[0]), sizeof(data)), &buffer); return buffer; } base::UnguessableToken DecodeToken(base::StringPiece input) { std::string buffer; if (!base::Base64Decode(input, &buffer) || buffer.length() != sizeof(uint64_t) * 2) { return base::UnguessableToken(); } const uint64_t* data = reinterpret_cast<const uint64_t*>(buffer.data()); return base::UnguessableToken::Deserialize(data[0], data[1]); } base::Value PortInfoToValue(const device::mojom::SerialPortInfo& port) { base::Value value(base::Value::Type::DICTIONARY); if (port.display_name && !port.display_name->empty()) value.SetStringKey(kPortNameKey, *port.display_name); else value.SetStringKey(kPortNameKey, port.path.LossyDisplayName()); if (!SerialChooserContext::CanStorePersistentEntry(port)) { value.SetStringKey(kTokenKey, EncodeToken(port.token)); return value; } #if BUILDFLAG(IS_WIN) // Windows provides a handy device identifier which we can rely on to be // sufficiently stable for identifying devices across restarts. value.SetStringKey(kDeviceInstanceIdKey, port.device_instance_id); #else DCHECK(port.has_vendor_id); value.SetIntKey(kVendorIdKey, port.vendor_id); DCHECK(port.has_product_id); value.SetIntKey(kProductIdKey, port.product_id); DCHECK(port.serial_number); value.SetStringKey(kSerialNumberKey, *port.serial_number); #if BUILDFLAG(IS_MAC) DCHECK(port.usb_driver_name && !port.usb_driver_name->empty()); value.SetStringKey(kUsbDriverKey, *port.usb_driver_name); #endif // BUILDFLAG(IS_MAC) #endif // BUILDFLAG(IS_WIN) return value; } SerialChooserContext::SerialChooserContext(ElectronBrowserContext* context) : browser_context_(context) {} SerialChooserContext::~SerialChooserContext() { // Notify observers that the chooser context is about to be destroyed. // Observers must remove themselves from the observer lists. for (auto& observer : port_observer_list_) { observer.OnSerialChooserContextShutdown(); DCHECK(!port_observer_list_.HasObserver(&observer)); } } void SerialChooserContext::GrantPortPermission( const url::Origin& origin, const device::mojom::SerialPortInfo& port, content::RenderFrameHost* render_frame_host) { auto* permission_manager = static_cast<ElectronPermissionManager*>( browser_context_->GetPermissionControllerDelegate()); return permission_manager->GrantDevicePermission( static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::SERIAL), origin, PortInfoToValue(port), browser_context_); } bool SerialChooserContext::HasPortPermission( const url::Origin& origin, const device::mojom::SerialPortInfo& port, content::RenderFrameHost* render_frame_host) { auto* permission_manager = static_cast<ElectronPermissionManager*>( browser_context_->GetPermissionControllerDelegate()); return permission_manager->CheckDevicePermission( static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::SERIAL), origin, PortInfoToValue(port), browser_context_); } void SerialChooserContext::RevokePortPermissionWebInitiated( const url::Origin& origin, const base::UnguessableToken& token) { auto it = port_info_.find(token); if (it == port_info_.end()) return; } // static bool SerialChooserContext::CanStorePersistentEntry( const device::mojom::SerialPortInfo& port) { // If there is no display name then the path name will be used instead. The // path name is not guaranteed to be stable. For example, on Linux the name // "ttyUSB0" is reused for any USB serial device. A name like that would be // confusing to show in settings when the device is disconnected. if (!port.display_name || port.display_name->empty()) return false; #if BUILDFLAG(IS_WIN) return !port.device_instance_id.empty(); #else if (!port.has_vendor_id || !port.has_product_id || !port.serial_number || port.serial_number->empty()) { return false; } #if BUILDFLAG(IS_MAC) // The combination of the standard USB vendor ID, product ID and serial // number properties should be enough to uniquely identify a device // however recent versions of macOS include built-in drivers for common // types of USB-to-serial adapters while their manufacturers still // recommend installing their custom drivers. When both are loaded two // IOSerialBSDClient instances are found for each device. Including the // USB driver name allows us to distinguish between the two. if (!port.usb_driver_name || port.usb_driver_name->empty()) return false; #endif // BUILDFLAG(IS_MAC) return true; #endif // BUILDFLAG(IS_WIN) } const device::mojom::SerialPortInfo* SerialChooserContext::GetPortInfo( const base::UnguessableToken& token) { DCHECK(is_initialized_); auto it = port_info_.find(token); return it == port_info_.end() ? nullptr : it->second.get(); } device::mojom::SerialPortManager* SerialChooserContext::GetPortManager() { EnsurePortManagerConnection(); return port_manager_.get(); } void SerialChooserContext::AddPortObserver(PortObserver* observer) { port_observer_list_.AddObserver(observer); } void SerialChooserContext::RemovePortObserver(PortObserver* observer) { port_observer_list_.RemoveObserver(observer); } base::WeakPtr<SerialChooserContext> SerialChooserContext::AsWeakPtr() { return weak_factory_.GetWeakPtr(); } void SerialChooserContext::OnPortAdded(device::mojom::SerialPortInfoPtr port) { for (auto& observer : port_observer_list_) observer.OnPortAdded(*port); } void SerialChooserContext::OnPortRemoved( device::mojom::SerialPortInfoPtr port) { for (auto& observer : port_observer_list_) observer.OnPortRemoved(*port); } void SerialChooserContext::EnsurePortManagerConnection() { if (port_manager_) return; mojo::PendingRemote<device::mojom::SerialPortManager> manager; content::GetDeviceService().BindSerialPortManager( manager.InitWithNewPipeAndPassReceiver()); SetUpPortManagerConnection(std::move(manager)); } void SerialChooserContext::SetUpPortManagerConnection( mojo::PendingRemote<device::mojom::SerialPortManager> manager) { port_manager_.Bind(std::move(manager)); port_manager_.set_disconnect_handler( base::BindOnce(&SerialChooserContext::OnPortManagerConnectionError, base::Unretained(this))); port_manager_->SetClient(client_receiver_.BindNewPipeAndPassRemote()); } void SerialChooserContext::OnPortManagerConnectionError() { port_manager_.reset(); client_receiver_.reset(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,282
[Bug]: WebSerial - SerialPort doesn't open in Electron 20
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.1 ### What operating system are you using? Windows ### Operating System Version Win 10 Pro 19043 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.11 ### Expected Behavior WebSerial API should open a serial port. ### Actual Behavior The ``getInfo`` method works fine, but ``open`` fails to open the port. ### Testcase Gist URL https://gist.github.com/17afc65be515f3a1aec6256cb69f069d https://github.com/rafaelpimpa/electron-webserial-bug-repro ### Additional Information Error thrown is ``NetworkError: Failed to open serial port.`` I didn't use an Arduino to test, but it should work the same, since it works in v19. Reproduction has the same code from the docs.
https://github.com/electron/electron/issues/35282
https://github.com/electron/electron/pull/35306
cbc1ee5775375b7ec92f8c38bcbb157833b1b8a0
672539187c779cf874dfcecc198bcfbdec85aa97
2022-08-09T13:47:55Z
c++
2022-08-15T15:49:20Z
shell/browser/serial/serial_chooser_context.h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_SERIAL_SERIAL_CHOOSER_CONTEXT_H_ #define ELECTRON_SHELL_BROWSER_SERIAL_SERIAL_CHOOSER_CONTEXT_H_ #include <map> #include <set> #include <utility> #include <vector> #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/unguessable_token.h" #include "components/keyed_service/core/keyed_service.h" #include "content/public/browser/serial_delegate.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/serial.mojom-forward.h" #include "shell/browser/electron_browser_context.h" #include "third_party/blink/public/mojom/serial/serial.mojom.h" #include "url/gurl.h" #include "url/origin.h" namespace base { class Value; } namespace electron { extern const char kHidVendorIdKey[]; extern const char kHidProductIdKey[]; #if BUILDFLAG(IS_WIN) extern const char kDeviceInstanceIdKey[]; #else extern const char kVendorIdKey[]; extern const char kProductIdKey[]; extern const char kSerialNumberKey[]; #if BUILDFLAG(IS_MAC) extern const char kUsbDriverKey[]; #endif // BUILDFLAG(IS_MAC) #endif // BUILDFLAG(IS_WIN) class SerialChooserContext : public KeyedService, public device::mojom::SerialPortManagerClient { public: class PortObserver : public content::SerialDelegate::Observer { public: // Called when the SerialChooserContext is shutting down. Observers must // remove themselves before returning. virtual void OnSerialChooserContextShutdown() = 0; }; explicit SerialChooserContext(ElectronBrowserContext* context); ~SerialChooserContext() override; // disable copy SerialChooserContext(const SerialChooserContext&) = delete; SerialChooserContext& operator=(const SerialChooserContext&) = delete; // Serial-specific interface for granting and checking permissions. void GrantPortPermission(const url::Origin& origin, const device::mojom::SerialPortInfo& port, content::RenderFrameHost* render_frame_host); bool HasPortPermission(const url::Origin& origin, const device::mojom::SerialPortInfo& port, content::RenderFrameHost* render_frame_host); static bool CanStorePersistentEntry( const device::mojom::SerialPortInfo& port); device::mojom::SerialPortManager* GetPortManager(); void AddPortObserver(PortObserver* observer); void RemovePortObserver(PortObserver* observer); base::WeakPtr<SerialChooserContext> AsWeakPtr(); bool is_initialized_ = false; // Map from port token to port info. std::map<base::UnguessableToken, device::mojom::SerialPortInfoPtr> port_info_; // SerialPortManagerClient implementation. void OnPortAdded(device::mojom::SerialPortInfoPtr port) override; void OnPortRemoved(device::mojom::SerialPortInfoPtr port) override; void RevokePortPermissionWebInitiated(const url::Origin& origin, const base::UnguessableToken& token); // Only call this if you're sure |port_info_| has been initialized // before-hand. The returned raw pointer is owned by |port_info_| and will be // destroyed when the port is removed. const device::mojom::SerialPortInfo* GetPortInfo( const base::UnguessableToken& token); private: void EnsurePortManagerConnection(); void SetUpPortManagerConnection( mojo::PendingRemote<device::mojom::SerialPortManager> manager); void OnPortManagerConnectionError(); void RevokeObjectPermissionInternal(const url::Origin& origin, const base::Value& object, bool revoked_by_website); mojo::Remote<device::mojom::SerialPortManager> port_manager_; mojo::Receiver<device::mojom::SerialPortManagerClient> client_receiver_{this}; base::ObserverList<PortObserver> port_observer_list_; ElectronBrowserContext* browser_context_; base::WeakPtrFactory<SerialChooserContext> weak_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_SERIAL_SERIAL_CHOOSER_CONTEXT_H_
closed
electron/electron
https://github.com/electron/electron
35,282
[Bug]: WebSerial - SerialPort doesn't open in Electron 20
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.1 ### What operating system are you using? Windows ### Operating System Version Win 10 Pro 19043 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.11 ### Expected Behavior WebSerial API should open a serial port. ### Actual Behavior The ``getInfo`` method works fine, but ``open`` fails to open the port. ### Testcase Gist URL https://gist.github.com/17afc65be515f3a1aec6256cb69f069d https://github.com/rafaelpimpa/electron-webserial-bug-repro ### Additional Information Error thrown is ``NetworkError: Failed to open serial port.`` I didn't use an Arduino to test, but it should work the same, since it works in v19. Reproduction has the same code from the docs.
https://github.com/electron/electron/issues/35282
https://github.com/electron/electron/pull/35306
cbc1ee5775375b7ec92f8c38bcbb157833b1b8a0
672539187c779cf874dfcecc198bcfbdec85aa97
2022-08-09T13:47:55Z
c++
2022-08-15T15:49:20Z
shell/browser/serial/electron_serial_delegate.cc
// Copyright (c) 2020 Microsoft, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/serial/electron_serial_delegate.h" #include <utility> #include "base/feature_list.h" #include "content/public/browser/web_contents.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/serial/serial_chooser_context.h" #include "shell/browser/serial/serial_chooser_context_factory.h" #include "shell/browser/serial/serial_chooser_controller.h" #include "shell/browser/web_contents_permission_helper.h" namespace electron { SerialChooserContext* GetChooserContext(content::RenderFrameHost* frame) { auto* web_contents = content::WebContents::FromRenderFrameHost(frame); auto* browser_context = web_contents->GetBrowserContext(); return SerialChooserContextFactory::GetForBrowserContext(browser_context); } ElectronSerialDelegate::ElectronSerialDelegate() = default; ElectronSerialDelegate::~ElectronSerialDelegate() = default; std::unique_ptr<content::SerialChooser> ElectronSerialDelegate::RunChooser( content::RenderFrameHost* frame, std::vector<blink::mojom::SerialPortFilterPtr> filters, content::SerialChooser::Callback callback) { SerialChooserController* controller = ControllerForFrame(frame); if (controller) { DeleteControllerForFrame(frame); } AddControllerForFrame(frame, std::move(filters), std::move(callback)); // Return a nullptr because the return value isn't used for anything, eg // there is no mechanism to cancel navigator.serial.requestPort(). The return // value is simply used in Chromium to cleanup the chooser UI once the serial // service is destroyed. return nullptr; } bool ElectronSerialDelegate::CanRequestPortPermission( content::RenderFrameHost* frame) { auto* web_contents = content::WebContents::FromRenderFrameHost(frame); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckSerialAccessPermission( web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin()); } bool ElectronSerialDelegate::HasPortPermission( content::RenderFrameHost* frame, const device::mojom::SerialPortInfo& port) { auto* web_contents = content::WebContents::FromRenderFrameHost(frame); auto* browser_context = web_contents->GetBrowserContext(); auto* chooser_context = SerialChooserContextFactory::GetForBrowserContext(browser_context); return chooser_context->HasPortPermission( web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin(), port, frame); } device::mojom::SerialPortManager* ElectronSerialDelegate::GetPortManager( content::RenderFrameHost* frame) { return GetChooserContext(frame)->GetPortManager(); } void ElectronSerialDelegate::AddObserver(content::RenderFrameHost* frame, Observer* observer) { observer_list_.AddObserver(observer); auto* chooser_context = GetChooserContext(frame); if (!port_observation_.IsObserving()) port_observation_.Observe(chooser_context); } void ElectronSerialDelegate::RemoveObserver(content::RenderFrameHost* frame, Observer* observer) { observer_list_.RemoveObserver(observer); } void ElectronSerialDelegate::RevokePortPermissionWebInitiated( content::RenderFrameHost* frame, const base::UnguessableToken& token) { // TODO(nornagon/jkleinsc): pass this on to the chooser context } const device::mojom::SerialPortInfo* ElectronSerialDelegate::GetPortInfo( content::RenderFrameHost* frame, const base::UnguessableToken& token) { // TODO(nornagon/jkleinsc): pass this on to the chooser context return nullptr; } SerialChooserController* ElectronSerialDelegate::ControllerForFrame( content::RenderFrameHost* render_frame_host) { auto mapping = controller_map_.find(render_frame_host); return mapping == controller_map_.end() ? nullptr : mapping->second.get(); } SerialChooserController* ElectronSerialDelegate::AddControllerForFrame( content::RenderFrameHost* render_frame_host, std::vector<blink::mojom::SerialPortFilterPtr> filters, content::SerialChooser::Callback callback) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto controller = std::make_unique<SerialChooserController>( render_frame_host, std::move(filters), 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 ElectronSerialDelegate::DeleteControllerForFrame( content::RenderFrameHost* render_frame_host) { controller_map_.erase(render_frame_host); } // SerialChooserContext::PortObserver: void ElectronSerialDelegate::OnPortAdded( const device::mojom::SerialPortInfo& port) { for (auto& observer : observer_list_) observer.OnPortAdded(port); } void ElectronSerialDelegate::OnPortRemoved( const device::mojom::SerialPortInfo& port) { for (auto& observer : observer_list_) observer.OnPortRemoved(port); } void ElectronSerialDelegate::OnPortManagerConnectionError() { port_observation_.Reset(); for (auto& observer : observer_list_) observer.OnPortManagerConnectionError(); } void ElectronSerialDelegate::OnSerialChooserContextShutdown() { port_observation_.Reset(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,282
[Bug]: WebSerial - SerialPort doesn't open in Electron 20
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.1 ### What operating system are you using? Windows ### Operating System Version Win 10 Pro 19043 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.11 ### Expected Behavior WebSerial API should open a serial port. ### Actual Behavior The ``getInfo`` method works fine, but ``open`` fails to open the port. ### Testcase Gist URL https://gist.github.com/17afc65be515f3a1aec6256cb69f069d https://github.com/rafaelpimpa/electron-webserial-bug-repro ### Additional Information Error thrown is ``NetworkError: Failed to open serial port.`` I didn't use an Arduino to test, but it should work the same, since it works in v19. Reproduction has the same code from the docs.
https://github.com/electron/electron/issues/35282
https://github.com/electron/electron/pull/35306
cbc1ee5775375b7ec92f8c38bcbb157833b1b8a0
672539187c779cf874dfcecc198bcfbdec85aa97
2022-08-09T13:47:55Z
c++
2022-08-15T15:49:20Z
shell/browser/serial/serial_chooser_context.cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "shell/browser/serial/serial_chooser_context.h" #include <memory> #include <string> #include <utility> #include "base/base64.h" #include "base/containers/contains.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "content/public/browser/device_service.h" #include "content/public/browser/web_contents.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "shell/browser/electron_permission_manager.h" #include "shell/browser/web_contents_permission_helper.h" namespace electron { constexpr char kPortNameKey[] = "name"; constexpr char kTokenKey[] = "token"; #if BUILDFLAG(IS_WIN) const char kDeviceInstanceIdKey[] = "device_instance_id"; #else const char kVendorIdKey[] = "vendor_id"; const char kProductIdKey[] = "product_id"; const char kSerialNumberKey[] = "serial_number"; #if BUILDFLAG(IS_MAC) const char kUsbDriverKey[] = "usb_driver"; #endif // BUILDFLAG(IS_MAC) #endif // BUILDFLAG(IS_WIN) std::string EncodeToken(const base::UnguessableToken& token) { const uint64_t data[2] = {token.GetHighForSerialization(), token.GetLowForSerialization()}; std::string buffer; base::Base64Encode( base::StringPiece(reinterpret_cast<const char*>(&data[0]), sizeof(data)), &buffer); return buffer; } base::UnguessableToken DecodeToken(base::StringPiece input) { std::string buffer; if (!base::Base64Decode(input, &buffer) || buffer.length() != sizeof(uint64_t) * 2) { return base::UnguessableToken(); } const uint64_t* data = reinterpret_cast<const uint64_t*>(buffer.data()); return base::UnguessableToken::Deserialize(data[0], data[1]); } base::Value PortInfoToValue(const device::mojom::SerialPortInfo& port) { base::Value value(base::Value::Type::DICTIONARY); if (port.display_name && !port.display_name->empty()) value.SetStringKey(kPortNameKey, *port.display_name); else value.SetStringKey(kPortNameKey, port.path.LossyDisplayName()); if (!SerialChooserContext::CanStorePersistentEntry(port)) { value.SetStringKey(kTokenKey, EncodeToken(port.token)); return value; } #if BUILDFLAG(IS_WIN) // Windows provides a handy device identifier which we can rely on to be // sufficiently stable for identifying devices across restarts. value.SetStringKey(kDeviceInstanceIdKey, port.device_instance_id); #else DCHECK(port.has_vendor_id); value.SetIntKey(kVendorIdKey, port.vendor_id); DCHECK(port.has_product_id); value.SetIntKey(kProductIdKey, port.product_id); DCHECK(port.serial_number); value.SetStringKey(kSerialNumberKey, *port.serial_number); #if BUILDFLAG(IS_MAC) DCHECK(port.usb_driver_name && !port.usb_driver_name->empty()); value.SetStringKey(kUsbDriverKey, *port.usb_driver_name); #endif // BUILDFLAG(IS_MAC) #endif // BUILDFLAG(IS_WIN) return value; } SerialChooserContext::SerialChooserContext(ElectronBrowserContext* context) : browser_context_(context) {} SerialChooserContext::~SerialChooserContext() { // Notify observers that the chooser context is about to be destroyed. // Observers must remove themselves from the observer lists. for (auto& observer : port_observer_list_) { observer.OnSerialChooserContextShutdown(); DCHECK(!port_observer_list_.HasObserver(&observer)); } } void SerialChooserContext::GrantPortPermission( const url::Origin& origin, const device::mojom::SerialPortInfo& port, content::RenderFrameHost* render_frame_host) { auto* permission_manager = static_cast<ElectronPermissionManager*>( browser_context_->GetPermissionControllerDelegate()); return permission_manager->GrantDevicePermission( static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::SERIAL), origin, PortInfoToValue(port), browser_context_); } bool SerialChooserContext::HasPortPermission( const url::Origin& origin, const device::mojom::SerialPortInfo& port, content::RenderFrameHost* render_frame_host) { auto* permission_manager = static_cast<ElectronPermissionManager*>( browser_context_->GetPermissionControllerDelegate()); return permission_manager->CheckDevicePermission( static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::SERIAL), origin, PortInfoToValue(port), browser_context_); } void SerialChooserContext::RevokePortPermissionWebInitiated( const url::Origin& origin, const base::UnguessableToken& token) { auto it = port_info_.find(token); if (it == port_info_.end()) return; } // static bool SerialChooserContext::CanStorePersistentEntry( const device::mojom::SerialPortInfo& port) { // If there is no display name then the path name will be used instead. The // path name is not guaranteed to be stable. For example, on Linux the name // "ttyUSB0" is reused for any USB serial device. A name like that would be // confusing to show in settings when the device is disconnected. if (!port.display_name || port.display_name->empty()) return false; #if BUILDFLAG(IS_WIN) return !port.device_instance_id.empty(); #else if (!port.has_vendor_id || !port.has_product_id || !port.serial_number || port.serial_number->empty()) { return false; } #if BUILDFLAG(IS_MAC) // The combination of the standard USB vendor ID, product ID and serial // number properties should be enough to uniquely identify a device // however recent versions of macOS include built-in drivers for common // types of USB-to-serial adapters while their manufacturers still // recommend installing their custom drivers. When both are loaded two // IOSerialBSDClient instances are found for each device. Including the // USB driver name allows us to distinguish between the two. if (!port.usb_driver_name || port.usb_driver_name->empty()) return false; #endif // BUILDFLAG(IS_MAC) return true; #endif // BUILDFLAG(IS_WIN) } const device::mojom::SerialPortInfo* SerialChooserContext::GetPortInfo( const base::UnguessableToken& token) { DCHECK(is_initialized_); auto it = port_info_.find(token); return it == port_info_.end() ? nullptr : it->second.get(); } device::mojom::SerialPortManager* SerialChooserContext::GetPortManager() { EnsurePortManagerConnection(); return port_manager_.get(); } void SerialChooserContext::AddPortObserver(PortObserver* observer) { port_observer_list_.AddObserver(observer); } void SerialChooserContext::RemovePortObserver(PortObserver* observer) { port_observer_list_.RemoveObserver(observer); } base::WeakPtr<SerialChooserContext> SerialChooserContext::AsWeakPtr() { return weak_factory_.GetWeakPtr(); } void SerialChooserContext::OnPortAdded(device::mojom::SerialPortInfoPtr port) { for (auto& observer : port_observer_list_) observer.OnPortAdded(*port); } void SerialChooserContext::OnPortRemoved( device::mojom::SerialPortInfoPtr port) { for (auto& observer : port_observer_list_) observer.OnPortRemoved(*port); } void SerialChooserContext::EnsurePortManagerConnection() { if (port_manager_) return; mojo::PendingRemote<device::mojom::SerialPortManager> manager; content::GetDeviceService().BindSerialPortManager( manager.InitWithNewPipeAndPassReceiver()); SetUpPortManagerConnection(std::move(manager)); } void SerialChooserContext::SetUpPortManagerConnection( mojo::PendingRemote<device::mojom::SerialPortManager> manager) { port_manager_.Bind(std::move(manager)); port_manager_.set_disconnect_handler( base::BindOnce(&SerialChooserContext::OnPortManagerConnectionError, base::Unretained(this))); port_manager_->SetClient(client_receiver_.BindNewPipeAndPassRemote()); } void SerialChooserContext::OnPortManagerConnectionError() { port_manager_.reset(); client_receiver_.reset(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,282
[Bug]: WebSerial - SerialPort doesn't open in Electron 20
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.1 ### What operating system are you using? Windows ### Operating System Version Win 10 Pro 19043 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.11 ### Expected Behavior WebSerial API should open a serial port. ### Actual Behavior The ``getInfo`` method works fine, but ``open`` fails to open the port. ### Testcase Gist URL https://gist.github.com/17afc65be515f3a1aec6256cb69f069d https://github.com/rafaelpimpa/electron-webserial-bug-repro ### Additional Information Error thrown is ``NetworkError: Failed to open serial port.`` I didn't use an Arduino to test, but it should work the same, since it works in v19. Reproduction has the same code from the docs.
https://github.com/electron/electron/issues/35282
https://github.com/electron/electron/pull/35306
cbc1ee5775375b7ec92f8c38bcbb157833b1b8a0
672539187c779cf874dfcecc198bcfbdec85aa97
2022-08-09T13:47:55Z
c++
2022-08-15T15:49:20Z
shell/browser/serial/serial_chooser_context.h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_SERIAL_SERIAL_CHOOSER_CONTEXT_H_ #define ELECTRON_SHELL_BROWSER_SERIAL_SERIAL_CHOOSER_CONTEXT_H_ #include <map> #include <set> #include <utility> #include <vector> #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/unguessable_token.h" #include "components/keyed_service/core/keyed_service.h" #include "content/public/browser/serial_delegate.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/serial.mojom-forward.h" #include "shell/browser/electron_browser_context.h" #include "third_party/blink/public/mojom/serial/serial.mojom.h" #include "url/gurl.h" #include "url/origin.h" namespace base { class Value; } namespace electron { extern const char kHidVendorIdKey[]; extern const char kHidProductIdKey[]; #if BUILDFLAG(IS_WIN) extern const char kDeviceInstanceIdKey[]; #else extern const char kVendorIdKey[]; extern const char kProductIdKey[]; extern const char kSerialNumberKey[]; #if BUILDFLAG(IS_MAC) extern const char kUsbDriverKey[]; #endif // BUILDFLAG(IS_MAC) #endif // BUILDFLAG(IS_WIN) class SerialChooserContext : public KeyedService, public device::mojom::SerialPortManagerClient { public: class PortObserver : public content::SerialDelegate::Observer { public: // Called when the SerialChooserContext is shutting down. Observers must // remove themselves before returning. virtual void OnSerialChooserContextShutdown() = 0; }; explicit SerialChooserContext(ElectronBrowserContext* context); ~SerialChooserContext() override; // disable copy SerialChooserContext(const SerialChooserContext&) = delete; SerialChooserContext& operator=(const SerialChooserContext&) = delete; // Serial-specific interface for granting and checking permissions. void GrantPortPermission(const url::Origin& origin, const device::mojom::SerialPortInfo& port, content::RenderFrameHost* render_frame_host); bool HasPortPermission(const url::Origin& origin, const device::mojom::SerialPortInfo& port, content::RenderFrameHost* render_frame_host); static bool CanStorePersistentEntry( const device::mojom::SerialPortInfo& port); device::mojom::SerialPortManager* GetPortManager(); void AddPortObserver(PortObserver* observer); void RemovePortObserver(PortObserver* observer); base::WeakPtr<SerialChooserContext> AsWeakPtr(); bool is_initialized_ = false; // Map from port token to port info. std::map<base::UnguessableToken, device::mojom::SerialPortInfoPtr> port_info_; // SerialPortManagerClient implementation. void OnPortAdded(device::mojom::SerialPortInfoPtr port) override; void OnPortRemoved(device::mojom::SerialPortInfoPtr port) override; void RevokePortPermissionWebInitiated(const url::Origin& origin, const base::UnguessableToken& token); // Only call this if you're sure |port_info_| has been initialized // before-hand. The returned raw pointer is owned by |port_info_| and will be // destroyed when the port is removed. const device::mojom::SerialPortInfo* GetPortInfo( const base::UnguessableToken& token); private: void EnsurePortManagerConnection(); void SetUpPortManagerConnection( mojo::PendingRemote<device::mojom::SerialPortManager> manager); void OnPortManagerConnectionError(); void RevokeObjectPermissionInternal(const url::Origin& origin, const base::Value& object, bool revoked_by_website); mojo::Remote<device::mojom::SerialPortManager> port_manager_; mojo::Receiver<device::mojom::SerialPortManagerClient> client_receiver_{this}; base::ObserverList<PortObserver> port_observer_list_; ElectronBrowserContext* browser_context_; base::WeakPtrFactory<SerialChooserContext> weak_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_SERIAL_SERIAL_CHOOSER_CONTEXT_H_
closed
electron/electron
https://github.com/electron/electron
30,760
[Bug]: Frameless window displays frame while opening
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 14.0.0-beta.25 ### What operating system are you using? Windows ### Operating System Version Windows 10 21H1 ### What arch are you using? x64 ### Last Known Working Electron version 14.0.0-beta.3 ### Expected Behavior Opening a frameless window and immediately revealing it (instead of waiting for `ready-to-show` event) shows no content inside of the window. ### Actual Behavior Opening a frameless window and immediately revealing it (instead of waiting for `ready-to-show` event) shows an older style window frame with no content inside. | 14.0.0-beta.3 | 14.0.0-beta.5 | | --- | --- | | ![image](https://user-images.githubusercontent.com/1656324/131413708-cc472e02-21d7-4fc8-9a6b-ca38391b7911.png) | ![image](https://user-images.githubusercontent.com/1656324/131413746-ac2e389f-1528-4f60-886b-25a93ef8e217.png) | https://user-images.githubusercontent.com/1656324/131413659-18c2ea6c-d1c4-489f-8182-ae19cba51bcb.mp4 ### Testcase Gist URL https://gist.github.com/4256f388d41ef0d974645a11ab72b1fe ### Additional Information This may not be a bug, but I felt that displaying the frame while the window is opening was maybe not intentional.
https://github.com/electron/electron/issues/30760
https://github.com/electron/electron/pull/35189
db7c92fd574f9880cc4ce579972f5220ebb3186e
947f1b0abf8ce61612f48cf13e7861b58f22594a
2021-08-30T22:30:41Z
c++
2022-08-16T21:22:47Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch don_t_use_potentially_null_getwebframe_-_view_when_get_blink.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch fix_allow_guest_webcontents_to_enter_fullscreen.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch add_maximized_parameter_to_linuxui_getwindowframeprovider.patch add_electron_deps_to_license_credits_file.patch
closed
electron/electron
https://github.com/electron/electron
30,760
[Bug]: Frameless window displays frame while opening
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 14.0.0-beta.25 ### What operating system are you using? Windows ### Operating System Version Windows 10 21H1 ### What arch are you using? x64 ### Last Known Working Electron version 14.0.0-beta.3 ### Expected Behavior Opening a frameless window and immediately revealing it (instead of waiting for `ready-to-show` event) shows no content inside of the window. ### Actual Behavior Opening a frameless window and immediately revealing it (instead of waiting for `ready-to-show` event) shows an older style window frame with no content inside. | 14.0.0-beta.3 | 14.0.0-beta.5 | | --- | --- | | ![image](https://user-images.githubusercontent.com/1656324/131413708-cc472e02-21d7-4fc8-9a6b-ca38391b7911.png) | ![image](https://user-images.githubusercontent.com/1656324/131413746-ac2e389f-1528-4f60-886b-25a93ef8e217.png) | https://user-images.githubusercontent.com/1656324/131413659-18c2ea6c-d1c4-489f-8182-ae19cba51bcb.mp4 ### Testcase Gist URL https://gist.github.com/4256f388d41ef0d974645a11ab72b1fe ### Additional Information This may not be a bug, but I felt that displaying the frame while the window is opening was maybe not intentional.
https://github.com/electron/electron/issues/30760
https://github.com/electron/electron/pull/35189
db7c92fd574f9880cc4ce579972f5220ebb3186e
947f1b0abf8ce61612f48cf13e7861b58f22594a
2021-08-30T22:30:41Z
c++
2022-08-16T21:22:47Z
patches/chromium/feat_add_set_can_resize_mutator.patch
closed
electron/electron
https://github.com/electron/electron
30,760
[Bug]: Frameless window displays frame while opening
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 14.0.0-beta.25 ### What operating system are you using? Windows ### Operating System Version Windows 10 21H1 ### What arch are you using? x64 ### Last Known Working Electron version 14.0.0-beta.3 ### Expected Behavior Opening a frameless window and immediately revealing it (instead of waiting for `ready-to-show` event) shows no content inside of the window. ### Actual Behavior Opening a frameless window and immediately revealing it (instead of waiting for `ready-to-show` event) shows an older style window frame with no content inside. | 14.0.0-beta.3 | 14.0.0-beta.5 | | --- | --- | | ![image](https://user-images.githubusercontent.com/1656324/131413708-cc472e02-21d7-4fc8-9a6b-ca38391b7911.png) | ![image](https://user-images.githubusercontent.com/1656324/131413746-ac2e389f-1528-4f60-886b-25a93ef8e217.png) | https://user-images.githubusercontent.com/1656324/131413659-18c2ea6c-d1c4-489f-8182-ae19cba51bcb.mp4 ### Testcase Gist URL https://gist.github.com/4256f388d41ef0d974645a11ab72b1fe ### Additional Information This may not be a bug, but I felt that displaying the frame while the window is opening was maybe not intentional.
https://github.com/electron/electron/issues/30760
https://github.com/electron/electron/pull/35189
db7c92fd574f9880cc4ce579972f5220ebb3186e
947f1b0abf8ce61612f48cf13e7861b58f22594a
2021-08-30T22:30:41Z
c++
2022-08-16T21:22:47Z
shell/browser/native_window_views.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/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "shell/common/platform_util.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: NativeWindowViews* window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); 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.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; // Set Wayland application ID. params.wayland_app_id = platform_util::GetXdgAppId(); auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if BUILDFLAG(IS_LINUX) // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); } #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); } #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif #if defined(USE_OZONE_PLATFORM_X11) // On X11, setting Z order before showing the window doesn't take effect, // so we have to call it again. if (IsX11()) widget()->SetZOrderLevel(widget()->GetZOrderLevel()); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); } #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_OZONE) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (CreateGlobalMenuBar() && ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); } #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } void NativeWindowViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { draggable_region_ = DraggableRegionsToSkRegion(regions); } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blurred. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { // App window should claim mouse events that fall within any BrowserViews' // draggable region. for (auto* view : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(view); auto* view_draggable_region = native_view->draggable_region(); if (view_draggable_region && view_draggable_region->contains(location.x(), location.y())) return false; } // App window should claim mouse events that fall within the draggable region. if (draggable_region() && draggable_region()->contains(location.x(), location.y())) return false; // And the events on border for dragging resizable frameless window. if ((!has_frame() || has_client_frame()) && resizable_) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); return frame->ResizingBorderHitTest(location) == HTNOWHERE; } return true; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
30,760
[Bug]: Frameless window displays frame while opening
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 14.0.0-beta.25 ### What operating system are you using? Windows ### Operating System Version Windows 10 21H1 ### What arch are you using? x64 ### Last Known Working Electron version 14.0.0-beta.3 ### Expected Behavior Opening a frameless window and immediately revealing it (instead of waiting for `ready-to-show` event) shows no content inside of the window. ### Actual Behavior Opening a frameless window and immediately revealing it (instead of waiting for `ready-to-show` event) shows an older style window frame with no content inside. | 14.0.0-beta.3 | 14.0.0-beta.5 | | --- | --- | | ![image](https://user-images.githubusercontent.com/1656324/131413708-cc472e02-21d7-4fc8-9a6b-ca38391b7911.png) | ![image](https://user-images.githubusercontent.com/1656324/131413746-ac2e389f-1528-4f60-886b-25a93ef8e217.png) | https://user-images.githubusercontent.com/1656324/131413659-18c2ea6c-d1c4-489f-8182-ae19cba51bcb.mp4 ### Testcase Gist URL https://gist.github.com/4256f388d41ef0d974645a11ab72b1fe ### Additional Information This may not be a bug, but I felt that displaying the frame while the window is opening was maybe not intentional.
https://github.com/electron/electron/issues/30760
https://github.com/electron/electron/pull/35189
db7c92fd574f9880cc4ce579972f5220ebb3186e
947f1b0abf8ce61612f48cf13e7861b58f22594a
2021-08-30T22:30:41Z
c++
2022-08-16T21:22:47Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch don_t_use_potentially_null_getwebframe_-_view_when_get_blink.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch fix_allow_guest_webcontents_to_enter_fullscreen.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch add_maximized_parameter_to_linuxui_getwindowframeprovider.patch add_electron_deps_to_license_credits_file.patch
closed
electron/electron
https://github.com/electron/electron
30,760
[Bug]: Frameless window displays frame while opening
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 14.0.0-beta.25 ### What operating system are you using? Windows ### Operating System Version Windows 10 21H1 ### What arch are you using? x64 ### Last Known Working Electron version 14.0.0-beta.3 ### Expected Behavior Opening a frameless window and immediately revealing it (instead of waiting for `ready-to-show` event) shows no content inside of the window. ### Actual Behavior Opening a frameless window and immediately revealing it (instead of waiting for `ready-to-show` event) shows an older style window frame with no content inside. | 14.0.0-beta.3 | 14.0.0-beta.5 | | --- | --- | | ![image](https://user-images.githubusercontent.com/1656324/131413708-cc472e02-21d7-4fc8-9a6b-ca38391b7911.png) | ![image](https://user-images.githubusercontent.com/1656324/131413746-ac2e389f-1528-4f60-886b-25a93ef8e217.png) | https://user-images.githubusercontent.com/1656324/131413659-18c2ea6c-d1c4-489f-8182-ae19cba51bcb.mp4 ### Testcase Gist URL https://gist.github.com/4256f388d41ef0d974645a11ab72b1fe ### Additional Information This may not be a bug, but I felt that displaying the frame while the window is opening was maybe not intentional.
https://github.com/electron/electron/issues/30760
https://github.com/electron/electron/pull/35189
db7c92fd574f9880cc4ce579972f5220ebb3186e
947f1b0abf8ce61612f48cf13e7861b58f22594a
2021-08-30T22:30:41Z
c++
2022-08-16T21:22:47Z
patches/chromium/feat_add_set_can_resize_mutator.patch
closed
electron/electron
https://github.com/electron/electron
30,760
[Bug]: Frameless window displays frame while opening
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 14.0.0-beta.25 ### What operating system are you using? Windows ### Operating System Version Windows 10 21H1 ### What arch are you using? x64 ### Last Known Working Electron version 14.0.0-beta.3 ### Expected Behavior Opening a frameless window and immediately revealing it (instead of waiting for `ready-to-show` event) shows no content inside of the window. ### Actual Behavior Opening a frameless window and immediately revealing it (instead of waiting for `ready-to-show` event) shows an older style window frame with no content inside. | 14.0.0-beta.3 | 14.0.0-beta.5 | | --- | --- | | ![image](https://user-images.githubusercontent.com/1656324/131413708-cc472e02-21d7-4fc8-9a6b-ca38391b7911.png) | ![image](https://user-images.githubusercontent.com/1656324/131413746-ac2e389f-1528-4f60-886b-25a93ef8e217.png) | https://user-images.githubusercontent.com/1656324/131413659-18c2ea6c-d1c4-489f-8182-ae19cba51bcb.mp4 ### Testcase Gist URL https://gist.github.com/4256f388d41ef0d974645a11ab72b1fe ### Additional Information This may not be a bug, but I felt that displaying the frame while the window is opening was maybe not intentional.
https://github.com/electron/electron/issues/30760
https://github.com/electron/electron/pull/35189
db7c92fd574f9880cc4ce579972f5220ebb3186e
947f1b0abf8ce61612f48cf13e7861b58f22594a
2021-08-30T22:30:41Z
c++
2022-08-16T21:22:47Z
shell/browser/native_window_views.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/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "shell/common/platform_util.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: NativeWindowViews* window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); 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.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; // Set Wayland application ID. params.wayland_app_id = platform_util::GetXdgAppId(); auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if BUILDFLAG(IS_LINUX) // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); } #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); } #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif #if defined(USE_OZONE_PLATFORM_X11) // On X11, setting Z order before showing the window doesn't take effect, // so we have to call it again. if (IsX11()) widget()->SetZOrderLevel(widget()->GetZOrderLevel()); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); } #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_OZONE) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (CreateGlobalMenuBar() && ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); } #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } void NativeWindowViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { draggable_region_ = DraggableRegionsToSkRegion(regions); } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blurred. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { // App window should claim mouse events that fall within any BrowserViews' // draggable region. for (auto* view : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(view); auto* view_draggable_region = native_view->draggable_region(); if (view_draggable_region && view_draggable_region->contains(location.x(), location.y())) return false; } // App window should claim mouse events that fall within the draggable region. if (draggable_region() && draggable_region()->contains(location.x(), location.y())) return false; // And the events on border for dragging resizable frameless window. if ((!has_frame() || has_client_frame()) && resizable_) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); return frame->ResizingBorderHitTest(location) == HTNOWHERE; } return true; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,756
[Bug]: webContents.executeJavaScript and webFrameMain.executeJavaScript are different when a Promise is returned
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro version 21H1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When running the following ``` const { app, BrowserWindow } = require( "electron" ) app.whenReady().then(()=>{ let main = new BrowserWindow({ "height" : 600, "width" : 800 }) main.loadURL( "https://...." ) main.webContents.on( "did-finish-load", ()=>{ let iframe = main.webContents.mainFrame.frames[ 0 ] let injection = "new Promise(( resolve )=>{ resolve('hello') })" let handler = ( result ) => { console.log( result ) } //this code does not evaluate the same: iframe.executeJavaScript( injection ).then( handler ) //returns "{}" main.webContents.executeJavaScript( injection ).then( handler ) ) //returns "hello" }) }) ``` I would expect the following output: ``` hello hello ``` ### Actual Behavior Instead, I get: ``` {} hello ``` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32756
https://github.com/electron/electron/pull/35292
8e4a168a136f8948d019350a089a8a2878509c6a
43182bf030d7de6fab5b6976f073eb125c2ebe12
2022-02-05T00:46:29Z
c++
2022-08-17T04:08:13Z
shell/browser/api/electron_api_web_frame_main.cc
// Copyright (c) 2020 Samuel Maddock <[email protected]>. // 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_frame_main.h" #include <string> #include <unordered_map> #include <utility> #include <vector> #include "base/logging.h" #include "base/no_destructor.h" #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck #include "content/public/browser/render_frame_host.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/object_template_builder.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "shell/browser/api/message_port.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/gin_helper/promise.h" #include "shell/common/node_includes.h" #include "shell/common/v8_value_serializer.h" namespace gin { template <> struct Converter<blink::mojom::PageVisibilityState> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, blink::mojom::PageVisibilityState val) { std::string visibility; switch (val) { case blink::mojom::PageVisibilityState::kVisible: visibility = "visible"; break; case blink::mojom::PageVisibilityState::kHidden: case blink::mojom::PageVisibilityState::kHiddenButPainting: visibility = "hidden"; break; } return gin::ConvertToV8(isolate, visibility); } }; } // namespace gin namespace electron::api { typedef std::unordered_map<int, WebFrameMain*> WebFrameMainIdMap; WebFrameMainIdMap& GetWebFrameMainMap() { static base::NoDestructor<WebFrameMainIdMap> instance; return *instance; } // static WebFrameMain* WebFrameMain::FromFrameTreeNodeId(int frame_tree_node_id) { WebFrameMainIdMap& frame_map = GetWebFrameMainMap(); auto iter = frame_map.find(frame_tree_node_id); auto* web_frame = iter == frame_map.end() ? nullptr : iter->second; return web_frame; } // static WebFrameMain* WebFrameMain::FromRenderFrameHost(content::RenderFrameHost* rfh) { return rfh ? FromFrameTreeNodeId(rfh->GetFrameTreeNodeId()) : nullptr; } gin::WrapperInfo WebFrameMain::kWrapperInfo = {gin::kEmbedderNativeGin}; WebFrameMain::WebFrameMain(content::RenderFrameHost* rfh) : frame_tree_node_id_(rfh->GetFrameTreeNodeId()), render_frame_(rfh) { GetWebFrameMainMap().emplace(frame_tree_node_id_, this); } WebFrameMain::~WebFrameMain() { Destroyed(); } void WebFrameMain::Destroyed() { MarkRenderFrameDisposed(); GetWebFrameMainMap().erase(frame_tree_node_id_); Unpin(); } void WebFrameMain::MarkRenderFrameDisposed() { render_frame_ = nullptr; render_frame_disposed_ = true; TeardownMojoConnection(); } void WebFrameMain::UpdateRenderFrameHost(content::RenderFrameHost* rfh) { // Should only be called when swapping frames. render_frame_disposed_ = false; render_frame_ = rfh; TeardownMojoConnection(); MaybeSetupMojoConnection(); } bool WebFrameMain::CheckRenderFrame() const { if (render_frame_disposed_) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::ErrorThrower(isolate).ThrowError( "Render frame was disposed before WebFrameMain could be accessed"); return false; } return true; } v8::Local<v8::Promise> WebFrameMain::ExecuteJavaScript( gin::Arguments* args, const std::u16string& code) { gin_helper::Promise<base::Value> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // Optional userGesture parameter bool user_gesture; if (!args->PeekNext().IsEmpty()) { if (args->PeekNext()->IsBoolean()) { args->GetNext(&user_gesture); } else { args->ThrowTypeError("userGesture must be a boolean"); return handle; } } else { user_gesture = false; } if (render_frame_disposed_) { promise.RejectWithErrorMessage( "Render frame was disposed before WebFrameMain could be accessed"); return handle; } if (user_gesture) { auto* ftn = content::FrameTreeNode::From(render_frame_); ftn->UpdateUserActivationState( blink::mojom::UserActivationUpdateType::kNotifyActivation, blink::mojom::UserActivationNotificationType::kTest); } render_frame_->ExecuteJavaScriptForTests( code, base::BindOnce([](gin_helper::Promise<base::Value> promise, base::Value value) { promise.Resolve(value); }, std::move(promise))); return handle; } bool WebFrameMain::Reload() { if (!CheckRenderFrame()) return false; return render_frame_->Reload(); } void WebFrameMain::Send(v8::Isolate* isolate, bool internal, const std::string& channel, v8::Local<v8::Value> args) { blink::CloneableMessage message; if (!gin::ConvertFromV8(isolate, args, &message)) { isolate->ThrowException(v8::Exception::Error( gin::StringToV8(isolate, "Failed to serialize arguments"))); return; } if (!CheckRenderFrame()) return; GetRendererApi()->Message(internal, channel, std::move(message), 0 /* sender_id */); } const mojo::Remote<mojom::ElectronRenderer>& WebFrameMain::GetRendererApi() { MaybeSetupMojoConnection(); return renderer_api_; } void WebFrameMain::MaybeSetupMojoConnection() { if (render_frame_disposed_) { // RFH may not be set yet if called between when a new RFH is created and // before it's been swapped with an old RFH. LOG(INFO) << "Attempt to setup WebFrameMain connection while render frame " "is disposed"; return; } if (!renderer_api_) { pending_receiver_ = renderer_api_.BindNewPipeAndPassReceiver(); renderer_api_.set_disconnect_handler(base::BindOnce( &WebFrameMain::OnRendererConnectionError, weak_factory_.GetWeakPtr())); } DCHECK(render_frame_); // Wait for RenderFrame to be created in renderer before accessing remote. if (pending_receiver_ && render_frame_ && render_frame_->IsRenderFrameLive()) { render_frame_->GetRemoteInterfaces()->GetInterface( std::move(pending_receiver_)); } } void WebFrameMain::TeardownMojoConnection() { renderer_api_.reset(); pending_receiver_.reset(); } void WebFrameMain::OnRendererConnectionError() { TeardownMojoConnection(); } void WebFrameMain::PostMessage(v8::Isolate* isolate, const std::string& channel, v8::Local<v8::Value> message_value, absl::optional<v8::Local<v8::Value>> transfer) { blink::TransferableMessage transferable_message; if (!electron::SerializeV8Value(isolate, message_value, &transferable_message)) { // SerializeV8Value sets an exception. return; } std::vector<gin::Handle<MessagePort>> wrapped_ports; if (transfer && !transfer.value()->IsUndefined()) { if (!gin::ConvertFromV8(isolate, *transfer, &wrapped_ports)) { isolate->ThrowException(v8::Exception::Error( gin::StringToV8(isolate, "Invalid value for transfer"))); return; } } bool threw_exception = false; transferable_message.ports = MessagePort::DisentanglePorts(isolate, wrapped_ports, &threw_exception); if (threw_exception) return; if (!CheckRenderFrame()) return; GetRendererApi()->ReceivePostMessage(channel, std::move(transferable_message)); } int WebFrameMain::FrameTreeNodeID() const { return frame_tree_node_id_; } std::string WebFrameMain::Name() const { if (!CheckRenderFrame()) return std::string(); return render_frame_->GetFrameName(); } base::ProcessId WebFrameMain::OSProcessID() const { if (!CheckRenderFrame()) return -1; base::ProcessHandle process_handle = render_frame_->GetProcess()->GetProcess().Handle(); return base::GetProcId(process_handle); } int WebFrameMain::ProcessID() const { if (!CheckRenderFrame()) return -1; return render_frame_->GetProcess()->GetID(); } int WebFrameMain::RoutingID() const { if (!CheckRenderFrame()) return -1; return render_frame_->GetRoutingID(); } GURL WebFrameMain::URL() const { if (!CheckRenderFrame()) return GURL::EmptyGURL(); return render_frame_->GetLastCommittedURL(); } blink::mojom::PageVisibilityState WebFrameMain::VisibilityState() const { if (!CheckRenderFrame()) return blink::mojom::PageVisibilityState::kHidden; return render_frame_->GetVisibilityState(); } content::RenderFrameHost* WebFrameMain::Top() const { if (!CheckRenderFrame()) return nullptr; return render_frame_->GetMainFrame(); } content::RenderFrameHost* WebFrameMain::Parent() const { if (!CheckRenderFrame()) return nullptr; return render_frame_->GetParent(); } std::vector<content::RenderFrameHost*> WebFrameMain::Frames() const { std::vector<content::RenderFrameHost*> frame_hosts; if (!CheckRenderFrame()) return frame_hosts; render_frame_->ForEachRenderFrameHost(base::BindRepeating( [](std::vector<content::RenderFrameHost*>* frame_hosts, content::RenderFrameHost* current_frame, content::RenderFrameHost* rfh) { if (rfh->GetParent() == current_frame) frame_hosts->push_back(rfh); }, &frame_hosts, render_frame_)); return frame_hosts; } std::vector<content::RenderFrameHost*> WebFrameMain::FramesInSubtree() const { std::vector<content::RenderFrameHost*> frame_hosts; if (!CheckRenderFrame()) return frame_hosts; render_frame_->ForEachRenderFrameHost(base::BindRepeating( [](std::vector<content::RenderFrameHost*>* frame_hosts, content::RenderFrameHost* rfh) { frame_hosts->push_back(rfh); }, &frame_hosts)); return frame_hosts; } void WebFrameMain::DOMContentLoaded() { Emit("dom-ready"); } // static gin::Handle<WebFrameMain> WebFrameMain::New(v8::Isolate* isolate) { return gin::Handle<WebFrameMain>(); } // static gin::Handle<WebFrameMain> WebFrameMain::From(v8::Isolate* isolate, content::RenderFrameHost* rfh) { if (rfh == nullptr) return gin::Handle<WebFrameMain>(); auto* web_frame = FromRenderFrameHost(rfh); if (web_frame) return gin::CreateHandle(isolate, web_frame); auto handle = gin::CreateHandle(isolate, new WebFrameMain(rfh)); // Prevent garbage collection of frame until it has been deleted internally. handle->Pin(isolate); return handle; } // static gin::Handle<WebFrameMain> WebFrameMain::FromOrNull( v8::Isolate* isolate, content::RenderFrameHost* rfh) { if (rfh == nullptr) return gin::Handle<WebFrameMain>(); auto* web_frame = FromRenderFrameHost(rfh); if (web_frame) return gin::CreateHandle(isolate, web_frame); return gin::Handle<WebFrameMain>(); } // static v8::Local<v8::ObjectTemplate> WebFrameMain::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("executeJavaScript", &WebFrameMain::ExecuteJavaScript) .SetMethod("reload", &WebFrameMain::Reload) .SetMethod("_send", &WebFrameMain::Send) .SetMethod("_postMessage", &WebFrameMain::PostMessage) .SetProperty("frameTreeNodeId", &WebFrameMain::FrameTreeNodeID) .SetProperty("name", &WebFrameMain::Name) .SetProperty("osProcessId", &WebFrameMain::OSProcessID) .SetProperty("processId", &WebFrameMain::ProcessID) .SetProperty("routingId", &WebFrameMain::RoutingID) .SetProperty("url", &WebFrameMain::URL) .SetProperty("visibilityState", &WebFrameMain::VisibilityState) .SetProperty("top", &WebFrameMain::Top) .SetProperty("parent", &WebFrameMain::Parent) .SetProperty("frames", &WebFrameMain::Frames) .SetProperty("framesInSubtree", &WebFrameMain::FramesInSubtree) .Build(); } const char* WebFrameMain::GetTypeName() { return "WebFrameMain"; } } // namespace electron::api namespace { using electron::api::WebFrameMain; v8::Local<v8::Value> FromID(gin_helper::ErrorThrower thrower, int render_process_id, int render_frame_id) { if (!electron::Browser::Get()->is_ready()) { thrower.ThrowError("WebFrameMain is available only after app ready"); return v8::Null(thrower.isolate()); } auto* rfh = content::RenderFrameHost::FromID(render_process_id, render_frame_id); return WebFrameMain::From(thrower.isolate(), rfh).ToV8(); } v8::Local<v8::Value> FromIDOrNull(gin_helper::ErrorThrower thrower, int render_process_id, int render_frame_id) { if (!electron::Browser::Get()->is_ready()) { thrower.ThrowError("WebFrameMain is available only after app ready"); return v8::Null(thrower.isolate()); } auto* rfh = content::RenderFrameHost::FromID(render_process_id, render_frame_id); return WebFrameMain::FromOrNull(thrower.isolate(), rfh).ToV8(); } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebFrameMain", WebFrameMain::GetConstructor(context)); dict.SetMethod("fromId", &FromID); dict.SetMethod("fromIdOrNull", &FromIDOrNull); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_frame_main, Initialize)
closed
electron/electron
https://github.com/electron/electron
32,756
[Bug]: webContents.executeJavaScript and webFrameMain.executeJavaScript are different when a Promise is returned
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro version 21H1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When running the following ``` const { app, BrowserWindow } = require( "electron" ) app.whenReady().then(()=>{ let main = new BrowserWindow({ "height" : 600, "width" : 800 }) main.loadURL( "https://...." ) main.webContents.on( "did-finish-load", ()=>{ let iframe = main.webContents.mainFrame.frames[ 0 ] let injection = "new Promise(( resolve )=>{ resolve('hello') })" let handler = ( result ) => { console.log( result ) } //this code does not evaluate the same: iframe.executeJavaScript( injection ).then( handler ) //returns "{}" main.webContents.executeJavaScript( injection ).then( handler ) ) //returns "hello" }) }) ``` I would expect the following output: ``` hello hello ``` ### Actual Behavior Instead, I get: ``` {} hello ``` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32756
https://github.com/electron/electron/pull/35292
8e4a168a136f8948d019350a089a8a2878509c6a
43182bf030d7de6fab5b6976f073eb125c2ebe12
2022-02-05T00:46:29Z
c++
2022-08-17T04:08:13Z
spec/api-web-frame-main-spec.ts
import { expect } from 'chai'; import * as http from 'http'; import * as path from 'path'; import * as url from 'url'; import { BrowserWindow, WebFrameMain, webFrameMain, ipcMain } from 'electron/main'; import { closeAllWindows } from './window-helpers'; import { emittedOnce, emittedNTimes } from './events-helpers'; import { AddressInfo } from 'net'; import { ifit, waitUntil } from './spec-helpers'; describe('webFrameMain module', () => { const fixtures = path.resolve(__dirname, 'fixtures'); const subframesPath = path.join(fixtures, 'sub-frames'); const fileUrl = (filename: string) => url.pathToFileURL(path.join(subframesPath, filename)).href; type Server = { server: http.Server, url: string } /** Creates an HTTP server whose handler embeds the given iframe src. */ const createServer = () => new Promise<Server>(resolve => { const server = http.createServer((req, res) => { const params = new URLSearchParams(url.parse(req.url || '').search || ''); if (params.has('frameSrc')) { res.end(`<iframe src="${params.get('frameSrc')}"></iframe>`); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; resolve({ server, url }); }); }); afterEach(closeAllWindows); describe('WebFrame traversal APIs', () => { let w: BrowserWindow; let webFrame: WebFrameMain; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); webFrame = w.webContents.mainFrame; }); it('can access top frame', () => { expect(webFrame.top).to.equal(webFrame); }); it('has no parent on top frame', () => { expect(webFrame.parent).to.be.null(); }); it('can access immediate frame descendents', () => { const { frames } = webFrame; expect(frames).to.have.lengthOf(1); const subframe = frames[0]; expect(subframe).not.to.equal(webFrame); expect(subframe.parent).to.equal(webFrame); }); it('can access deeply nested frames', () => { const subframe = webFrame.frames[0]; expect(subframe).not.to.equal(webFrame); expect(subframe.parent).to.equal(webFrame); const nestedSubframe = subframe.frames[0]; expect(nestedSubframe).not.to.equal(webFrame); expect(nestedSubframe).not.to.equal(subframe); expect(nestedSubframe.parent).to.equal(subframe); }); it('can traverse all frames in root', () => { const urls = webFrame.framesInSubtree.map(frame => frame.url); expect(urls).to.deep.equal([ fileUrl('frame-with-frame-container.html'), fileUrl('frame-with-frame.html'), fileUrl('frame.html') ]); }); it('can traverse all frames in subtree', () => { const urls = webFrame.frames[0].framesInSubtree.map(frame => frame.url); expect(urls).to.deep.equal([ fileUrl('frame-with-frame.html'), fileUrl('frame.html') ]); }); describe('cross-origin', () => { let serverA = null as unknown as Server; let serverB = null as unknown as Server; before(async () => { serverA = await createServer(); serverB = await createServer(); }); after(() => { serverA.server.close(); serverB.server.close(); }); it('can access cross-origin frames', async () => { await w.loadURL(`${serverA.url}?frameSrc=${serverB.url}`); webFrame = w.webContents.mainFrame; expect(webFrame.url.startsWith(serverA.url)).to.be.true(); expect(webFrame.frames[0].url).to.equal(serverB.url); }); }); }); describe('WebFrame.url', () => { it('should report correct address for each subframe', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); const webFrame = w.webContents.mainFrame; expect(webFrame.url).to.equal(fileUrl('frame-with-frame-container.html')); expect(webFrame.frames[0].url).to.equal(fileUrl('frame-with-frame.html')); expect(webFrame.frames[0].frames[0].url).to.equal(fileUrl('frame.html')); }); }); describe('WebFrame IDs', () => { it('has properties for various identifiers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame.html')); const webFrame = w.webContents.mainFrame; expect(webFrame).to.have.ownProperty('url').that.is.a('string'); expect(webFrame).to.have.ownProperty('frameTreeNodeId').that.is.a('number'); expect(webFrame).to.have.ownProperty('name').that.is.a('string'); expect(webFrame).to.have.ownProperty('osProcessId').that.is.a('number'); expect(webFrame).to.have.ownProperty('processId').that.is.a('number'); expect(webFrame).to.have.ownProperty('routingId').that.is.a('number'); }); }); describe('WebFrame.visibilityState', () => { // TODO(MarshallOfSound): Fix flaky test // @flaky-test it.skip('should match window state', async () => { const w = new BrowserWindow({ show: true }); await w.loadURL('about:blank'); const webFrame = w.webContents.mainFrame; expect(webFrame.visibilityState).to.equal('visible'); w.hide(); await expect( waitUntil(() => webFrame.visibilityState === 'hidden') ).to.eventually.be.fulfilled(); }); }); describe('WebFrame.executeJavaScript', () => { it('can inject code into any subframe', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); const webFrame = w.webContents.mainFrame; const getUrl = (frame: WebFrameMain) => frame.executeJavaScript('location.href'); expect(await getUrl(webFrame)).to.equal(fileUrl('frame-with-frame-container.html')); expect(await getUrl(webFrame.frames[0])).to.equal(fileUrl('frame-with-frame.html')); expect(await getUrl(webFrame.frames[0].frames[0])).to.equal(fileUrl('frame.html')); }); }); describe('WebFrame.reload', () => { it('reloads a frame', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame.html')); const webFrame = w.webContents.mainFrame; await webFrame.executeJavaScript('window.TEMP = 1', false); expect(webFrame.reload()).to.be.true(); await emittedOnce(w.webContents, 'dom-ready'); expect(await webFrame.executeJavaScript('window.TEMP', false)).to.be.null(); }); }); describe('WebFrame.send', () => { it('works', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(subframesPath, 'preload.js'), nodeIntegrationInSubFrames: true } }); await w.loadURL('about:blank'); const webFrame = w.webContents.mainFrame; const pongPromise = emittedOnce(ipcMain, 'preload-pong'); webFrame.send('preload-ping'); const [, routingId] = await pongPromise; expect(routingId).to.equal(webFrame.routingId); }); }); describe('RenderFrame lifespan', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); }); // TODO(jkleinsc) fix this flaky test on linux ifit(process.platform !== 'linux')('throws upon accessing properties when disposed', async () => { await w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); const { mainFrame } = w.webContents; w.destroy(); // Wait for WebContents, and thus RenderFrameHost, to be destroyed. await new Promise(resolve => setTimeout(resolve, 0)); expect(() => mainFrame.url).to.throw(); }); it('persists through cross-origin navigation', async () => { const server = await createServer(); // 'localhost' is treated as a separate origin. const crossOriginUrl = server.url.replace('127.0.0.1', 'localhost'); await w.loadURL(server.url); const { mainFrame } = w.webContents; expect(mainFrame.url).to.equal(server.url); await w.loadURL(crossOriginUrl); expect(w.webContents.mainFrame).to.equal(mainFrame); expect(mainFrame.url).to.equal(crossOriginUrl); }); it('recovers from renderer crash on same-origin', async () => { const server = await createServer(); // Keep reference to mainFrame alive throughout crash and recovery. const { mainFrame } = w.webContents; await w.webContents.loadURL(server.url); const crashEvent = emittedOnce(w.webContents, 'render-process-gone'); w.webContents.forcefullyCrashRenderer(); await crashEvent; await w.webContents.loadURL(server.url); // Log just to keep mainFrame in scope. console.log('mainFrame.url', mainFrame.url); }); // Fixed by #34411 it('recovers from renderer crash on cross-origin', async () => { const server = await createServer(); // 'localhost' is treated as a separate origin. const crossOriginUrl = server.url.replace('127.0.0.1', 'localhost'); // Keep reference to mainFrame alive throughout crash and recovery. const { mainFrame } = w.webContents; await w.webContents.loadURL(server.url); const crashEvent = emittedOnce(w.webContents, 'render-process-gone'); w.webContents.forcefullyCrashRenderer(); await crashEvent; // A short wait seems to be required to reproduce the crash. await new Promise(resolve => setTimeout(resolve, 100)); await w.webContents.loadURL(crossOriginUrl); // Log just to keep mainFrame in scope. console.log('mainFrame.url', mainFrame.url); }); }); describe('webFrameMain.fromId', () => { it('returns undefined for unknown IDs', () => { expect(webFrameMain.fromId(0, 0)).to.be.undefined(); }); it('can find each frame from navigation events', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); // frame-with-frame-container.html, frame-with-frame.html, frame.html const didFrameFinishLoad = emittedNTimes(w.webContents, 'did-frame-finish-load', 3); w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); for (const [, isMainFrame, frameProcessId, frameRoutingId] of await didFrameFinishLoad) { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).not.to.be.null(); expect(frame?.processId).to.be.equal(frameProcessId); expect(frame?.routingId).to.be.equal(frameRoutingId); expect(frame?.top === frame).to.be.equal(isMainFrame); } }); }); describe('"frame-created" event', () => { it('emits when the main frame is created', async () => { const w = new BrowserWindow({ show: false }); const promise = emittedOnce(w.webContents, 'frame-created'); w.webContents.loadFile(path.join(subframesPath, 'frame.html')); const [, details] = await promise; expect(details.frame).to.equal(w.webContents.mainFrame); }); it('emits when nested frames are created', async () => { const w = new BrowserWindow({ show: false }); const promise = emittedNTimes(w.webContents, 'frame-created', 2); w.webContents.loadFile(path.join(subframesPath, 'frame-container.html')); const [[, mainDetails], [, nestedDetails]] = await promise; expect(mainDetails.frame).to.equal(w.webContents.mainFrame); expect(nestedDetails.frame).to.equal(w.webContents.mainFrame.frames[0]); }); it('is not emitted upon cross-origin navigation', async () => { const server = await createServer(); // HACK: Use 'localhost' instead of '127.0.0.1' so Chromium treats it as // a separate origin because differing ports aren't enough 🤔 const secondUrl = `http://localhost:${new URL(server.url).port}`; const w = new BrowserWindow({ show: false }); await w.webContents.loadURL(server.url); let frameCreatedEmitted = false; w.webContents.once('frame-created', () => { frameCreatedEmitted = true; }); await w.webContents.loadURL(secondUrl); expect(frameCreatedEmitted).to.be.false(); }); }); describe('"dom-ready" event', () => { it('emits for top-level frame', async () => { const w = new BrowserWindow({ show: false }); const promise = emittedOnce(w.webContents.mainFrame, 'dom-ready'); w.webContents.loadURL('about:blank'); await promise; }); it('emits for sub frame', async () => { const w = new BrowserWindow({ show: false }); const promise = new Promise<void>(resolve => { w.webContents.on('frame-created', (e, { frame }) => { frame.on('dom-ready', () => { if (frame.name === 'frameA') { resolve(); } }); }); }); w.webContents.loadFile(path.join(subframesPath, 'frame-with-frame.html')); await promise; }); }); });
closed
electron/electron
https://github.com/electron/electron
32,164
[Bug]: webFrameMain executeJavaScript doesn't work sometimes
### Preflight Checklist - [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 15.3.0 ### What operating system are you using? macOS ### Operating System Version macOS Monterey ### What arch are you using? x64 ### Last Known Working Electron version 15.3.0 ### Expected Behavior I write some code like this: 1. given a web page with an iframe, iframe and the page url is in **different origin** 2. setup listener in main process(`ipcMain.on`) and wait for message from renderer 3. use preload to inject some code into iframe and mainFrame(the web page) 4. both frames send message via `ipcRenderer` to main process when preload executed 5. after received message from renderer, main process retrieve webFrameMain by `[processId, routing]` provided in event params 6. main process call webFrameMain.executeJavaScript immediately, for every frame that send message to main process What's expected: 1. The code passed by executeJavaScript to be executed in each frame(the web page and iframe) 2. executeJavaScript asynchronously return execution result of passed code. ### Actual Behavior 1. The code didn't executed in iframe sometimes. Just mainFrame work as expected 2. webFrameMain.executeJavaScript.then(res) got res `null` when execute in the iframe. extra info was provided in Additional Information ### Testcase Gist URL [https://gist.github.com/b7714f0812e293339b9a2a08807cf795](https://gist.github.com/b7714f0812e293339b9a2a08807cf795) ### Additional Information 1. if use setTimeout to delay the execution, it **maybe** work in iframe. I tried to delay 10ms、20ms、...200ms and record success rate(test 100times): | delay | success rate | | ---- | --- | | 10ms | about 70% | | 20ms | about 85% | | 30ms | about 90% | | 40ms | about 95% | | 100ms| about 97% | | 200ms | 100% | 2. `webContents.sendToFrame` also has similar issue, renderer process **maybe** not receive message even it can successfully send message to main process 3. If preload send message after iframe 'DOMContentLoaded' event, `executeJavaScript` always success 4. After page and iframe fully loaded, just reload iframe(in console, using location.reload()), executeJavaScript works as expected.
https://github.com/electron/electron/issues/32164
https://github.com/electron/electron/pull/35292
8e4a168a136f8948d019350a089a8a2878509c6a
43182bf030d7de6fab5b6976f073eb125c2ebe12
2021-12-13T08:07:01Z
c++
2022-08-17T04:08:13Z
shell/browser/api/electron_api_web_frame_main.cc
// Copyright (c) 2020 Samuel Maddock <[email protected]>. // 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_frame_main.h" #include <string> #include <unordered_map> #include <utility> #include <vector> #include "base/logging.h" #include "base/no_destructor.h" #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck #include "content/public/browser/render_frame_host.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/object_template_builder.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "shell/browser/api/message_port.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/gin_helper/promise.h" #include "shell/common/node_includes.h" #include "shell/common/v8_value_serializer.h" namespace gin { template <> struct Converter<blink::mojom::PageVisibilityState> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, blink::mojom::PageVisibilityState val) { std::string visibility; switch (val) { case blink::mojom::PageVisibilityState::kVisible: visibility = "visible"; break; case blink::mojom::PageVisibilityState::kHidden: case blink::mojom::PageVisibilityState::kHiddenButPainting: visibility = "hidden"; break; } return gin::ConvertToV8(isolate, visibility); } }; } // namespace gin namespace electron::api { typedef std::unordered_map<int, WebFrameMain*> WebFrameMainIdMap; WebFrameMainIdMap& GetWebFrameMainMap() { static base::NoDestructor<WebFrameMainIdMap> instance; return *instance; } // static WebFrameMain* WebFrameMain::FromFrameTreeNodeId(int frame_tree_node_id) { WebFrameMainIdMap& frame_map = GetWebFrameMainMap(); auto iter = frame_map.find(frame_tree_node_id); auto* web_frame = iter == frame_map.end() ? nullptr : iter->second; return web_frame; } // static WebFrameMain* WebFrameMain::FromRenderFrameHost(content::RenderFrameHost* rfh) { return rfh ? FromFrameTreeNodeId(rfh->GetFrameTreeNodeId()) : nullptr; } gin::WrapperInfo WebFrameMain::kWrapperInfo = {gin::kEmbedderNativeGin}; WebFrameMain::WebFrameMain(content::RenderFrameHost* rfh) : frame_tree_node_id_(rfh->GetFrameTreeNodeId()), render_frame_(rfh) { GetWebFrameMainMap().emplace(frame_tree_node_id_, this); } WebFrameMain::~WebFrameMain() { Destroyed(); } void WebFrameMain::Destroyed() { MarkRenderFrameDisposed(); GetWebFrameMainMap().erase(frame_tree_node_id_); Unpin(); } void WebFrameMain::MarkRenderFrameDisposed() { render_frame_ = nullptr; render_frame_disposed_ = true; TeardownMojoConnection(); } void WebFrameMain::UpdateRenderFrameHost(content::RenderFrameHost* rfh) { // Should only be called when swapping frames. render_frame_disposed_ = false; render_frame_ = rfh; TeardownMojoConnection(); MaybeSetupMojoConnection(); } bool WebFrameMain::CheckRenderFrame() const { if (render_frame_disposed_) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::ErrorThrower(isolate).ThrowError( "Render frame was disposed before WebFrameMain could be accessed"); return false; } return true; } v8::Local<v8::Promise> WebFrameMain::ExecuteJavaScript( gin::Arguments* args, const std::u16string& code) { gin_helper::Promise<base::Value> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // Optional userGesture parameter bool user_gesture; if (!args->PeekNext().IsEmpty()) { if (args->PeekNext()->IsBoolean()) { args->GetNext(&user_gesture); } else { args->ThrowTypeError("userGesture must be a boolean"); return handle; } } else { user_gesture = false; } if (render_frame_disposed_) { promise.RejectWithErrorMessage( "Render frame was disposed before WebFrameMain could be accessed"); return handle; } if (user_gesture) { auto* ftn = content::FrameTreeNode::From(render_frame_); ftn->UpdateUserActivationState( blink::mojom::UserActivationUpdateType::kNotifyActivation, blink::mojom::UserActivationNotificationType::kTest); } render_frame_->ExecuteJavaScriptForTests( code, base::BindOnce([](gin_helper::Promise<base::Value> promise, base::Value value) { promise.Resolve(value); }, std::move(promise))); return handle; } bool WebFrameMain::Reload() { if (!CheckRenderFrame()) return false; return render_frame_->Reload(); } void WebFrameMain::Send(v8::Isolate* isolate, bool internal, const std::string& channel, v8::Local<v8::Value> args) { blink::CloneableMessage message; if (!gin::ConvertFromV8(isolate, args, &message)) { isolate->ThrowException(v8::Exception::Error( gin::StringToV8(isolate, "Failed to serialize arguments"))); return; } if (!CheckRenderFrame()) return; GetRendererApi()->Message(internal, channel, std::move(message), 0 /* sender_id */); } const mojo::Remote<mojom::ElectronRenderer>& WebFrameMain::GetRendererApi() { MaybeSetupMojoConnection(); return renderer_api_; } void WebFrameMain::MaybeSetupMojoConnection() { if (render_frame_disposed_) { // RFH may not be set yet if called between when a new RFH is created and // before it's been swapped with an old RFH. LOG(INFO) << "Attempt to setup WebFrameMain connection while render frame " "is disposed"; return; } if (!renderer_api_) { pending_receiver_ = renderer_api_.BindNewPipeAndPassReceiver(); renderer_api_.set_disconnect_handler(base::BindOnce( &WebFrameMain::OnRendererConnectionError, weak_factory_.GetWeakPtr())); } DCHECK(render_frame_); // Wait for RenderFrame to be created in renderer before accessing remote. if (pending_receiver_ && render_frame_ && render_frame_->IsRenderFrameLive()) { render_frame_->GetRemoteInterfaces()->GetInterface( std::move(pending_receiver_)); } } void WebFrameMain::TeardownMojoConnection() { renderer_api_.reset(); pending_receiver_.reset(); } void WebFrameMain::OnRendererConnectionError() { TeardownMojoConnection(); } void WebFrameMain::PostMessage(v8::Isolate* isolate, const std::string& channel, v8::Local<v8::Value> message_value, absl::optional<v8::Local<v8::Value>> transfer) { blink::TransferableMessage transferable_message; if (!electron::SerializeV8Value(isolate, message_value, &transferable_message)) { // SerializeV8Value sets an exception. return; } std::vector<gin::Handle<MessagePort>> wrapped_ports; if (transfer && !transfer.value()->IsUndefined()) { if (!gin::ConvertFromV8(isolate, *transfer, &wrapped_ports)) { isolate->ThrowException(v8::Exception::Error( gin::StringToV8(isolate, "Invalid value for transfer"))); return; } } bool threw_exception = false; transferable_message.ports = MessagePort::DisentanglePorts(isolate, wrapped_ports, &threw_exception); if (threw_exception) return; if (!CheckRenderFrame()) return; GetRendererApi()->ReceivePostMessage(channel, std::move(transferable_message)); } int WebFrameMain::FrameTreeNodeID() const { return frame_tree_node_id_; } std::string WebFrameMain::Name() const { if (!CheckRenderFrame()) return std::string(); return render_frame_->GetFrameName(); } base::ProcessId WebFrameMain::OSProcessID() const { if (!CheckRenderFrame()) return -1; base::ProcessHandle process_handle = render_frame_->GetProcess()->GetProcess().Handle(); return base::GetProcId(process_handle); } int WebFrameMain::ProcessID() const { if (!CheckRenderFrame()) return -1; return render_frame_->GetProcess()->GetID(); } int WebFrameMain::RoutingID() const { if (!CheckRenderFrame()) return -1; return render_frame_->GetRoutingID(); } GURL WebFrameMain::URL() const { if (!CheckRenderFrame()) return GURL::EmptyGURL(); return render_frame_->GetLastCommittedURL(); } blink::mojom::PageVisibilityState WebFrameMain::VisibilityState() const { if (!CheckRenderFrame()) return blink::mojom::PageVisibilityState::kHidden; return render_frame_->GetVisibilityState(); } content::RenderFrameHost* WebFrameMain::Top() const { if (!CheckRenderFrame()) return nullptr; return render_frame_->GetMainFrame(); } content::RenderFrameHost* WebFrameMain::Parent() const { if (!CheckRenderFrame()) return nullptr; return render_frame_->GetParent(); } std::vector<content::RenderFrameHost*> WebFrameMain::Frames() const { std::vector<content::RenderFrameHost*> frame_hosts; if (!CheckRenderFrame()) return frame_hosts; render_frame_->ForEachRenderFrameHost(base::BindRepeating( [](std::vector<content::RenderFrameHost*>* frame_hosts, content::RenderFrameHost* current_frame, content::RenderFrameHost* rfh) { if (rfh->GetParent() == current_frame) frame_hosts->push_back(rfh); }, &frame_hosts, render_frame_)); return frame_hosts; } std::vector<content::RenderFrameHost*> WebFrameMain::FramesInSubtree() const { std::vector<content::RenderFrameHost*> frame_hosts; if (!CheckRenderFrame()) return frame_hosts; render_frame_->ForEachRenderFrameHost(base::BindRepeating( [](std::vector<content::RenderFrameHost*>* frame_hosts, content::RenderFrameHost* rfh) { frame_hosts->push_back(rfh); }, &frame_hosts)); return frame_hosts; } void WebFrameMain::DOMContentLoaded() { Emit("dom-ready"); } // static gin::Handle<WebFrameMain> WebFrameMain::New(v8::Isolate* isolate) { return gin::Handle<WebFrameMain>(); } // static gin::Handle<WebFrameMain> WebFrameMain::From(v8::Isolate* isolate, content::RenderFrameHost* rfh) { if (rfh == nullptr) return gin::Handle<WebFrameMain>(); auto* web_frame = FromRenderFrameHost(rfh); if (web_frame) return gin::CreateHandle(isolate, web_frame); auto handle = gin::CreateHandle(isolate, new WebFrameMain(rfh)); // Prevent garbage collection of frame until it has been deleted internally. handle->Pin(isolate); return handle; } // static gin::Handle<WebFrameMain> WebFrameMain::FromOrNull( v8::Isolate* isolate, content::RenderFrameHost* rfh) { if (rfh == nullptr) return gin::Handle<WebFrameMain>(); auto* web_frame = FromRenderFrameHost(rfh); if (web_frame) return gin::CreateHandle(isolate, web_frame); return gin::Handle<WebFrameMain>(); } // static v8::Local<v8::ObjectTemplate> WebFrameMain::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("executeJavaScript", &WebFrameMain::ExecuteJavaScript) .SetMethod("reload", &WebFrameMain::Reload) .SetMethod("_send", &WebFrameMain::Send) .SetMethod("_postMessage", &WebFrameMain::PostMessage) .SetProperty("frameTreeNodeId", &WebFrameMain::FrameTreeNodeID) .SetProperty("name", &WebFrameMain::Name) .SetProperty("osProcessId", &WebFrameMain::OSProcessID) .SetProperty("processId", &WebFrameMain::ProcessID) .SetProperty("routingId", &WebFrameMain::RoutingID) .SetProperty("url", &WebFrameMain::URL) .SetProperty("visibilityState", &WebFrameMain::VisibilityState) .SetProperty("top", &WebFrameMain::Top) .SetProperty("parent", &WebFrameMain::Parent) .SetProperty("frames", &WebFrameMain::Frames) .SetProperty("framesInSubtree", &WebFrameMain::FramesInSubtree) .Build(); } const char* WebFrameMain::GetTypeName() { return "WebFrameMain"; } } // namespace electron::api namespace { using electron::api::WebFrameMain; v8::Local<v8::Value> FromID(gin_helper::ErrorThrower thrower, int render_process_id, int render_frame_id) { if (!electron::Browser::Get()->is_ready()) { thrower.ThrowError("WebFrameMain is available only after app ready"); return v8::Null(thrower.isolate()); } auto* rfh = content::RenderFrameHost::FromID(render_process_id, render_frame_id); return WebFrameMain::From(thrower.isolate(), rfh).ToV8(); } v8::Local<v8::Value> FromIDOrNull(gin_helper::ErrorThrower thrower, int render_process_id, int render_frame_id) { if (!electron::Browser::Get()->is_ready()) { thrower.ThrowError("WebFrameMain is available only after app ready"); return v8::Null(thrower.isolate()); } auto* rfh = content::RenderFrameHost::FromID(render_process_id, render_frame_id); return WebFrameMain::FromOrNull(thrower.isolate(), rfh).ToV8(); } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebFrameMain", WebFrameMain::GetConstructor(context)); dict.SetMethod("fromId", &FromID); dict.SetMethod("fromIdOrNull", &FromIDOrNull); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_frame_main, Initialize)
closed
electron/electron
https://github.com/electron/electron
32,164
[Bug]: webFrameMain executeJavaScript doesn't work sometimes
### Preflight Checklist - [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 15.3.0 ### What operating system are you using? macOS ### Operating System Version macOS Monterey ### What arch are you using? x64 ### Last Known Working Electron version 15.3.0 ### Expected Behavior I write some code like this: 1. given a web page with an iframe, iframe and the page url is in **different origin** 2. setup listener in main process(`ipcMain.on`) and wait for message from renderer 3. use preload to inject some code into iframe and mainFrame(the web page) 4. both frames send message via `ipcRenderer` to main process when preload executed 5. after received message from renderer, main process retrieve webFrameMain by `[processId, routing]` provided in event params 6. main process call webFrameMain.executeJavaScript immediately, for every frame that send message to main process What's expected: 1. The code passed by executeJavaScript to be executed in each frame(the web page and iframe) 2. executeJavaScript asynchronously return execution result of passed code. ### Actual Behavior 1. The code didn't executed in iframe sometimes. Just mainFrame work as expected 2. webFrameMain.executeJavaScript.then(res) got res `null` when execute in the iframe. extra info was provided in Additional Information ### Testcase Gist URL [https://gist.github.com/b7714f0812e293339b9a2a08807cf795](https://gist.github.com/b7714f0812e293339b9a2a08807cf795) ### Additional Information 1. if use setTimeout to delay the execution, it **maybe** work in iframe. I tried to delay 10ms、20ms、...200ms and record success rate(test 100times): | delay | success rate | | ---- | --- | | 10ms | about 70% | | 20ms | about 85% | | 30ms | about 90% | | 40ms | about 95% | | 100ms| about 97% | | 200ms | 100% | 2. `webContents.sendToFrame` also has similar issue, renderer process **maybe** not receive message even it can successfully send message to main process 3. If preload send message after iframe 'DOMContentLoaded' event, `executeJavaScript` always success 4. After page and iframe fully loaded, just reload iframe(in console, using location.reload()), executeJavaScript works as expected.
https://github.com/electron/electron/issues/32164
https://github.com/electron/electron/pull/35292
8e4a168a136f8948d019350a089a8a2878509c6a
43182bf030d7de6fab5b6976f073eb125c2ebe12
2021-12-13T08:07:01Z
c++
2022-08-17T04:08:13Z
spec/api-web-frame-main-spec.ts
import { expect } from 'chai'; import * as http from 'http'; import * as path from 'path'; import * as url from 'url'; import { BrowserWindow, WebFrameMain, webFrameMain, ipcMain } from 'electron/main'; import { closeAllWindows } from './window-helpers'; import { emittedOnce, emittedNTimes } from './events-helpers'; import { AddressInfo } from 'net'; import { ifit, waitUntil } from './spec-helpers'; describe('webFrameMain module', () => { const fixtures = path.resolve(__dirname, 'fixtures'); const subframesPath = path.join(fixtures, 'sub-frames'); const fileUrl = (filename: string) => url.pathToFileURL(path.join(subframesPath, filename)).href; type Server = { server: http.Server, url: string } /** Creates an HTTP server whose handler embeds the given iframe src. */ const createServer = () => new Promise<Server>(resolve => { const server = http.createServer((req, res) => { const params = new URLSearchParams(url.parse(req.url || '').search || ''); if (params.has('frameSrc')) { res.end(`<iframe src="${params.get('frameSrc')}"></iframe>`); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; resolve({ server, url }); }); }); afterEach(closeAllWindows); describe('WebFrame traversal APIs', () => { let w: BrowserWindow; let webFrame: WebFrameMain; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); webFrame = w.webContents.mainFrame; }); it('can access top frame', () => { expect(webFrame.top).to.equal(webFrame); }); it('has no parent on top frame', () => { expect(webFrame.parent).to.be.null(); }); it('can access immediate frame descendents', () => { const { frames } = webFrame; expect(frames).to.have.lengthOf(1); const subframe = frames[0]; expect(subframe).not.to.equal(webFrame); expect(subframe.parent).to.equal(webFrame); }); it('can access deeply nested frames', () => { const subframe = webFrame.frames[0]; expect(subframe).not.to.equal(webFrame); expect(subframe.parent).to.equal(webFrame); const nestedSubframe = subframe.frames[0]; expect(nestedSubframe).not.to.equal(webFrame); expect(nestedSubframe).not.to.equal(subframe); expect(nestedSubframe.parent).to.equal(subframe); }); it('can traverse all frames in root', () => { const urls = webFrame.framesInSubtree.map(frame => frame.url); expect(urls).to.deep.equal([ fileUrl('frame-with-frame-container.html'), fileUrl('frame-with-frame.html'), fileUrl('frame.html') ]); }); it('can traverse all frames in subtree', () => { const urls = webFrame.frames[0].framesInSubtree.map(frame => frame.url); expect(urls).to.deep.equal([ fileUrl('frame-with-frame.html'), fileUrl('frame.html') ]); }); describe('cross-origin', () => { let serverA = null as unknown as Server; let serverB = null as unknown as Server; before(async () => { serverA = await createServer(); serverB = await createServer(); }); after(() => { serverA.server.close(); serverB.server.close(); }); it('can access cross-origin frames', async () => { await w.loadURL(`${serverA.url}?frameSrc=${serverB.url}`); webFrame = w.webContents.mainFrame; expect(webFrame.url.startsWith(serverA.url)).to.be.true(); expect(webFrame.frames[0].url).to.equal(serverB.url); }); }); }); describe('WebFrame.url', () => { it('should report correct address for each subframe', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); const webFrame = w.webContents.mainFrame; expect(webFrame.url).to.equal(fileUrl('frame-with-frame-container.html')); expect(webFrame.frames[0].url).to.equal(fileUrl('frame-with-frame.html')); expect(webFrame.frames[0].frames[0].url).to.equal(fileUrl('frame.html')); }); }); describe('WebFrame IDs', () => { it('has properties for various identifiers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame.html')); const webFrame = w.webContents.mainFrame; expect(webFrame).to.have.ownProperty('url').that.is.a('string'); expect(webFrame).to.have.ownProperty('frameTreeNodeId').that.is.a('number'); expect(webFrame).to.have.ownProperty('name').that.is.a('string'); expect(webFrame).to.have.ownProperty('osProcessId').that.is.a('number'); expect(webFrame).to.have.ownProperty('processId').that.is.a('number'); expect(webFrame).to.have.ownProperty('routingId').that.is.a('number'); }); }); describe('WebFrame.visibilityState', () => { // TODO(MarshallOfSound): Fix flaky test // @flaky-test it.skip('should match window state', async () => { const w = new BrowserWindow({ show: true }); await w.loadURL('about:blank'); const webFrame = w.webContents.mainFrame; expect(webFrame.visibilityState).to.equal('visible'); w.hide(); await expect( waitUntil(() => webFrame.visibilityState === 'hidden') ).to.eventually.be.fulfilled(); }); }); describe('WebFrame.executeJavaScript', () => { it('can inject code into any subframe', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); const webFrame = w.webContents.mainFrame; const getUrl = (frame: WebFrameMain) => frame.executeJavaScript('location.href'); expect(await getUrl(webFrame)).to.equal(fileUrl('frame-with-frame-container.html')); expect(await getUrl(webFrame.frames[0])).to.equal(fileUrl('frame-with-frame.html')); expect(await getUrl(webFrame.frames[0].frames[0])).to.equal(fileUrl('frame.html')); }); }); describe('WebFrame.reload', () => { it('reloads a frame', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame.html')); const webFrame = w.webContents.mainFrame; await webFrame.executeJavaScript('window.TEMP = 1', false); expect(webFrame.reload()).to.be.true(); await emittedOnce(w.webContents, 'dom-ready'); expect(await webFrame.executeJavaScript('window.TEMP', false)).to.be.null(); }); }); describe('WebFrame.send', () => { it('works', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(subframesPath, 'preload.js'), nodeIntegrationInSubFrames: true } }); await w.loadURL('about:blank'); const webFrame = w.webContents.mainFrame; const pongPromise = emittedOnce(ipcMain, 'preload-pong'); webFrame.send('preload-ping'); const [, routingId] = await pongPromise; expect(routingId).to.equal(webFrame.routingId); }); }); describe('RenderFrame lifespan', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); }); // TODO(jkleinsc) fix this flaky test on linux ifit(process.platform !== 'linux')('throws upon accessing properties when disposed', async () => { await w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); const { mainFrame } = w.webContents; w.destroy(); // Wait for WebContents, and thus RenderFrameHost, to be destroyed. await new Promise(resolve => setTimeout(resolve, 0)); expect(() => mainFrame.url).to.throw(); }); it('persists through cross-origin navigation', async () => { const server = await createServer(); // 'localhost' is treated as a separate origin. const crossOriginUrl = server.url.replace('127.0.0.1', 'localhost'); await w.loadURL(server.url); const { mainFrame } = w.webContents; expect(mainFrame.url).to.equal(server.url); await w.loadURL(crossOriginUrl); expect(w.webContents.mainFrame).to.equal(mainFrame); expect(mainFrame.url).to.equal(crossOriginUrl); }); it('recovers from renderer crash on same-origin', async () => { const server = await createServer(); // Keep reference to mainFrame alive throughout crash and recovery. const { mainFrame } = w.webContents; await w.webContents.loadURL(server.url); const crashEvent = emittedOnce(w.webContents, 'render-process-gone'); w.webContents.forcefullyCrashRenderer(); await crashEvent; await w.webContents.loadURL(server.url); // Log just to keep mainFrame in scope. console.log('mainFrame.url', mainFrame.url); }); // Fixed by #34411 it('recovers from renderer crash on cross-origin', async () => { const server = await createServer(); // 'localhost' is treated as a separate origin. const crossOriginUrl = server.url.replace('127.0.0.1', 'localhost'); // Keep reference to mainFrame alive throughout crash and recovery. const { mainFrame } = w.webContents; await w.webContents.loadURL(server.url); const crashEvent = emittedOnce(w.webContents, 'render-process-gone'); w.webContents.forcefullyCrashRenderer(); await crashEvent; // A short wait seems to be required to reproduce the crash. await new Promise(resolve => setTimeout(resolve, 100)); await w.webContents.loadURL(crossOriginUrl); // Log just to keep mainFrame in scope. console.log('mainFrame.url', mainFrame.url); }); }); describe('webFrameMain.fromId', () => { it('returns undefined for unknown IDs', () => { expect(webFrameMain.fromId(0, 0)).to.be.undefined(); }); it('can find each frame from navigation events', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); // frame-with-frame-container.html, frame-with-frame.html, frame.html const didFrameFinishLoad = emittedNTimes(w.webContents, 'did-frame-finish-load', 3); w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); for (const [, isMainFrame, frameProcessId, frameRoutingId] of await didFrameFinishLoad) { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).not.to.be.null(); expect(frame?.processId).to.be.equal(frameProcessId); expect(frame?.routingId).to.be.equal(frameRoutingId); expect(frame?.top === frame).to.be.equal(isMainFrame); } }); }); describe('"frame-created" event', () => { it('emits when the main frame is created', async () => { const w = new BrowserWindow({ show: false }); const promise = emittedOnce(w.webContents, 'frame-created'); w.webContents.loadFile(path.join(subframesPath, 'frame.html')); const [, details] = await promise; expect(details.frame).to.equal(w.webContents.mainFrame); }); it('emits when nested frames are created', async () => { const w = new BrowserWindow({ show: false }); const promise = emittedNTimes(w.webContents, 'frame-created', 2); w.webContents.loadFile(path.join(subframesPath, 'frame-container.html')); const [[, mainDetails], [, nestedDetails]] = await promise; expect(mainDetails.frame).to.equal(w.webContents.mainFrame); expect(nestedDetails.frame).to.equal(w.webContents.mainFrame.frames[0]); }); it('is not emitted upon cross-origin navigation', async () => { const server = await createServer(); // HACK: Use 'localhost' instead of '127.0.0.1' so Chromium treats it as // a separate origin because differing ports aren't enough 🤔 const secondUrl = `http://localhost:${new URL(server.url).port}`; const w = new BrowserWindow({ show: false }); await w.webContents.loadURL(server.url); let frameCreatedEmitted = false; w.webContents.once('frame-created', () => { frameCreatedEmitted = true; }); await w.webContents.loadURL(secondUrl); expect(frameCreatedEmitted).to.be.false(); }); }); describe('"dom-ready" event', () => { it('emits for top-level frame', async () => { const w = new BrowserWindow({ show: false }); const promise = emittedOnce(w.webContents.mainFrame, 'dom-ready'); w.webContents.loadURL('about:blank'); await promise; }); it('emits for sub frame', async () => { const w = new BrowserWindow({ show: false }); const promise = new Promise<void>(resolve => { w.webContents.on('frame-created', (e, { frame }) => { frame.on('dom-ready', () => { if (frame.name === 'frameA') { resolve(); } }); }); }); w.webContents.loadFile(path.join(subframesPath, 'frame-with-frame.html')); await promise; }); }); });
closed
electron/electron
https://github.com/electron/electron
32,756
[Bug]: webContents.executeJavaScript and webFrameMain.executeJavaScript are different when a Promise is returned
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro version 21H1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When running the following ``` const { app, BrowserWindow } = require( "electron" ) app.whenReady().then(()=>{ let main = new BrowserWindow({ "height" : 600, "width" : 800 }) main.loadURL( "https://...." ) main.webContents.on( "did-finish-load", ()=>{ let iframe = main.webContents.mainFrame.frames[ 0 ] let injection = "new Promise(( resolve )=>{ resolve('hello') })" let handler = ( result ) => { console.log( result ) } //this code does not evaluate the same: iframe.executeJavaScript( injection ).then( handler ) //returns "{}" main.webContents.executeJavaScript( injection ).then( handler ) ) //returns "hello" }) }) ``` I would expect the following output: ``` hello hello ``` ### Actual Behavior Instead, I get: ``` {} hello ``` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32756
https://github.com/electron/electron/pull/35292
8e4a168a136f8948d019350a089a8a2878509c6a
43182bf030d7de6fab5b6976f073eb125c2ebe12
2022-02-05T00:46:29Z
c++
2022-08-17T04:08:13Z
shell/browser/api/electron_api_web_frame_main.cc
// Copyright (c) 2020 Samuel Maddock <[email protected]>. // 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_frame_main.h" #include <string> #include <unordered_map> #include <utility> #include <vector> #include "base/logging.h" #include "base/no_destructor.h" #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck #include "content/public/browser/render_frame_host.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/object_template_builder.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "shell/browser/api/message_port.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/gin_helper/promise.h" #include "shell/common/node_includes.h" #include "shell/common/v8_value_serializer.h" namespace gin { template <> struct Converter<blink::mojom::PageVisibilityState> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, blink::mojom::PageVisibilityState val) { std::string visibility; switch (val) { case blink::mojom::PageVisibilityState::kVisible: visibility = "visible"; break; case blink::mojom::PageVisibilityState::kHidden: case blink::mojom::PageVisibilityState::kHiddenButPainting: visibility = "hidden"; break; } return gin::ConvertToV8(isolate, visibility); } }; } // namespace gin namespace electron::api { typedef std::unordered_map<int, WebFrameMain*> WebFrameMainIdMap; WebFrameMainIdMap& GetWebFrameMainMap() { static base::NoDestructor<WebFrameMainIdMap> instance; return *instance; } // static WebFrameMain* WebFrameMain::FromFrameTreeNodeId(int frame_tree_node_id) { WebFrameMainIdMap& frame_map = GetWebFrameMainMap(); auto iter = frame_map.find(frame_tree_node_id); auto* web_frame = iter == frame_map.end() ? nullptr : iter->second; return web_frame; } // static WebFrameMain* WebFrameMain::FromRenderFrameHost(content::RenderFrameHost* rfh) { return rfh ? FromFrameTreeNodeId(rfh->GetFrameTreeNodeId()) : nullptr; } gin::WrapperInfo WebFrameMain::kWrapperInfo = {gin::kEmbedderNativeGin}; WebFrameMain::WebFrameMain(content::RenderFrameHost* rfh) : frame_tree_node_id_(rfh->GetFrameTreeNodeId()), render_frame_(rfh) { GetWebFrameMainMap().emplace(frame_tree_node_id_, this); } WebFrameMain::~WebFrameMain() { Destroyed(); } void WebFrameMain::Destroyed() { MarkRenderFrameDisposed(); GetWebFrameMainMap().erase(frame_tree_node_id_); Unpin(); } void WebFrameMain::MarkRenderFrameDisposed() { render_frame_ = nullptr; render_frame_disposed_ = true; TeardownMojoConnection(); } void WebFrameMain::UpdateRenderFrameHost(content::RenderFrameHost* rfh) { // Should only be called when swapping frames. render_frame_disposed_ = false; render_frame_ = rfh; TeardownMojoConnection(); MaybeSetupMojoConnection(); } bool WebFrameMain::CheckRenderFrame() const { if (render_frame_disposed_) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::ErrorThrower(isolate).ThrowError( "Render frame was disposed before WebFrameMain could be accessed"); return false; } return true; } v8::Local<v8::Promise> WebFrameMain::ExecuteJavaScript( gin::Arguments* args, const std::u16string& code) { gin_helper::Promise<base::Value> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // Optional userGesture parameter bool user_gesture; if (!args->PeekNext().IsEmpty()) { if (args->PeekNext()->IsBoolean()) { args->GetNext(&user_gesture); } else { args->ThrowTypeError("userGesture must be a boolean"); return handle; } } else { user_gesture = false; } if (render_frame_disposed_) { promise.RejectWithErrorMessage( "Render frame was disposed before WebFrameMain could be accessed"); return handle; } if (user_gesture) { auto* ftn = content::FrameTreeNode::From(render_frame_); ftn->UpdateUserActivationState( blink::mojom::UserActivationUpdateType::kNotifyActivation, blink::mojom::UserActivationNotificationType::kTest); } render_frame_->ExecuteJavaScriptForTests( code, base::BindOnce([](gin_helper::Promise<base::Value> promise, base::Value value) { promise.Resolve(value); }, std::move(promise))); return handle; } bool WebFrameMain::Reload() { if (!CheckRenderFrame()) return false; return render_frame_->Reload(); } void WebFrameMain::Send(v8::Isolate* isolate, bool internal, const std::string& channel, v8::Local<v8::Value> args) { blink::CloneableMessage message; if (!gin::ConvertFromV8(isolate, args, &message)) { isolate->ThrowException(v8::Exception::Error( gin::StringToV8(isolate, "Failed to serialize arguments"))); return; } if (!CheckRenderFrame()) return; GetRendererApi()->Message(internal, channel, std::move(message), 0 /* sender_id */); } const mojo::Remote<mojom::ElectronRenderer>& WebFrameMain::GetRendererApi() { MaybeSetupMojoConnection(); return renderer_api_; } void WebFrameMain::MaybeSetupMojoConnection() { if (render_frame_disposed_) { // RFH may not be set yet if called between when a new RFH is created and // before it's been swapped with an old RFH. LOG(INFO) << "Attempt to setup WebFrameMain connection while render frame " "is disposed"; return; } if (!renderer_api_) { pending_receiver_ = renderer_api_.BindNewPipeAndPassReceiver(); renderer_api_.set_disconnect_handler(base::BindOnce( &WebFrameMain::OnRendererConnectionError, weak_factory_.GetWeakPtr())); } DCHECK(render_frame_); // Wait for RenderFrame to be created in renderer before accessing remote. if (pending_receiver_ && render_frame_ && render_frame_->IsRenderFrameLive()) { render_frame_->GetRemoteInterfaces()->GetInterface( std::move(pending_receiver_)); } } void WebFrameMain::TeardownMojoConnection() { renderer_api_.reset(); pending_receiver_.reset(); } void WebFrameMain::OnRendererConnectionError() { TeardownMojoConnection(); } void WebFrameMain::PostMessage(v8::Isolate* isolate, const std::string& channel, v8::Local<v8::Value> message_value, absl::optional<v8::Local<v8::Value>> transfer) { blink::TransferableMessage transferable_message; if (!electron::SerializeV8Value(isolate, message_value, &transferable_message)) { // SerializeV8Value sets an exception. return; } std::vector<gin::Handle<MessagePort>> wrapped_ports; if (transfer && !transfer.value()->IsUndefined()) { if (!gin::ConvertFromV8(isolate, *transfer, &wrapped_ports)) { isolate->ThrowException(v8::Exception::Error( gin::StringToV8(isolate, "Invalid value for transfer"))); return; } } bool threw_exception = false; transferable_message.ports = MessagePort::DisentanglePorts(isolate, wrapped_ports, &threw_exception); if (threw_exception) return; if (!CheckRenderFrame()) return; GetRendererApi()->ReceivePostMessage(channel, std::move(transferable_message)); } int WebFrameMain::FrameTreeNodeID() const { return frame_tree_node_id_; } std::string WebFrameMain::Name() const { if (!CheckRenderFrame()) return std::string(); return render_frame_->GetFrameName(); } base::ProcessId WebFrameMain::OSProcessID() const { if (!CheckRenderFrame()) return -1; base::ProcessHandle process_handle = render_frame_->GetProcess()->GetProcess().Handle(); return base::GetProcId(process_handle); } int WebFrameMain::ProcessID() const { if (!CheckRenderFrame()) return -1; return render_frame_->GetProcess()->GetID(); } int WebFrameMain::RoutingID() const { if (!CheckRenderFrame()) return -1; return render_frame_->GetRoutingID(); } GURL WebFrameMain::URL() const { if (!CheckRenderFrame()) return GURL::EmptyGURL(); return render_frame_->GetLastCommittedURL(); } blink::mojom::PageVisibilityState WebFrameMain::VisibilityState() const { if (!CheckRenderFrame()) return blink::mojom::PageVisibilityState::kHidden; return render_frame_->GetVisibilityState(); } content::RenderFrameHost* WebFrameMain::Top() const { if (!CheckRenderFrame()) return nullptr; return render_frame_->GetMainFrame(); } content::RenderFrameHost* WebFrameMain::Parent() const { if (!CheckRenderFrame()) return nullptr; return render_frame_->GetParent(); } std::vector<content::RenderFrameHost*> WebFrameMain::Frames() const { std::vector<content::RenderFrameHost*> frame_hosts; if (!CheckRenderFrame()) return frame_hosts; render_frame_->ForEachRenderFrameHost(base::BindRepeating( [](std::vector<content::RenderFrameHost*>* frame_hosts, content::RenderFrameHost* current_frame, content::RenderFrameHost* rfh) { if (rfh->GetParent() == current_frame) frame_hosts->push_back(rfh); }, &frame_hosts, render_frame_)); return frame_hosts; } std::vector<content::RenderFrameHost*> WebFrameMain::FramesInSubtree() const { std::vector<content::RenderFrameHost*> frame_hosts; if (!CheckRenderFrame()) return frame_hosts; render_frame_->ForEachRenderFrameHost(base::BindRepeating( [](std::vector<content::RenderFrameHost*>* frame_hosts, content::RenderFrameHost* rfh) { frame_hosts->push_back(rfh); }, &frame_hosts)); return frame_hosts; } void WebFrameMain::DOMContentLoaded() { Emit("dom-ready"); } // static gin::Handle<WebFrameMain> WebFrameMain::New(v8::Isolate* isolate) { return gin::Handle<WebFrameMain>(); } // static gin::Handle<WebFrameMain> WebFrameMain::From(v8::Isolate* isolate, content::RenderFrameHost* rfh) { if (rfh == nullptr) return gin::Handle<WebFrameMain>(); auto* web_frame = FromRenderFrameHost(rfh); if (web_frame) return gin::CreateHandle(isolate, web_frame); auto handle = gin::CreateHandle(isolate, new WebFrameMain(rfh)); // Prevent garbage collection of frame until it has been deleted internally. handle->Pin(isolate); return handle; } // static gin::Handle<WebFrameMain> WebFrameMain::FromOrNull( v8::Isolate* isolate, content::RenderFrameHost* rfh) { if (rfh == nullptr) return gin::Handle<WebFrameMain>(); auto* web_frame = FromRenderFrameHost(rfh); if (web_frame) return gin::CreateHandle(isolate, web_frame); return gin::Handle<WebFrameMain>(); } // static v8::Local<v8::ObjectTemplate> WebFrameMain::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("executeJavaScript", &WebFrameMain::ExecuteJavaScript) .SetMethod("reload", &WebFrameMain::Reload) .SetMethod("_send", &WebFrameMain::Send) .SetMethod("_postMessage", &WebFrameMain::PostMessage) .SetProperty("frameTreeNodeId", &WebFrameMain::FrameTreeNodeID) .SetProperty("name", &WebFrameMain::Name) .SetProperty("osProcessId", &WebFrameMain::OSProcessID) .SetProperty("processId", &WebFrameMain::ProcessID) .SetProperty("routingId", &WebFrameMain::RoutingID) .SetProperty("url", &WebFrameMain::URL) .SetProperty("visibilityState", &WebFrameMain::VisibilityState) .SetProperty("top", &WebFrameMain::Top) .SetProperty("parent", &WebFrameMain::Parent) .SetProperty("frames", &WebFrameMain::Frames) .SetProperty("framesInSubtree", &WebFrameMain::FramesInSubtree) .Build(); } const char* WebFrameMain::GetTypeName() { return "WebFrameMain"; } } // namespace electron::api namespace { using electron::api::WebFrameMain; v8::Local<v8::Value> FromID(gin_helper::ErrorThrower thrower, int render_process_id, int render_frame_id) { if (!electron::Browser::Get()->is_ready()) { thrower.ThrowError("WebFrameMain is available only after app ready"); return v8::Null(thrower.isolate()); } auto* rfh = content::RenderFrameHost::FromID(render_process_id, render_frame_id); return WebFrameMain::From(thrower.isolate(), rfh).ToV8(); } v8::Local<v8::Value> FromIDOrNull(gin_helper::ErrorThrower thrower, int render_process_id, int render_frame_id) { if (!electron::Browser::Get()->is_ready()) { thrower.ThrowError("WebFrameMain is available only after app ready"); return v8::Null(thrower.isolate()); } auto* rfh = content::RenderFrameHost::FromID(render_process_id, render_frame_id); return WebFrameMain::FromOrNull(thrower.isolate(), rfh).ToV8(); } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebFrameMain", WebFrameMain::GetConstructor(context)); dict.SetMethod("fromId", &FromID); dict.SetMethod("fromIdOrNull", &FromIDOrNull); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_frame_main, Initialize)
closed
electron/electron
https://github.com/electron/electron
32,756
[Bug]: webContents.executeJavaScript and webFrameMain.executeJavaScript are different when a Promise is returned
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro version 21H1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When running the following ``` const { app, BrowserWindow } = require( "electron" ) app.whenReady().then(()=>{ let main = new BrowserWindow({ "height" : 600, "width" : 800 }) main.loadURL( "https://...." ) main.webContents.on( "did-finish-load", ()=>{ let iframe = main.webContents.mainFrame.frames[ 0 ] let injection = "new Promise(( resolve )=>{ resolve('hello') })" let handler = ( result ) => { console.log( result ) } //this code does not evaluate the same: iframe.executeJavaScript( injection ).then( handler ) //returns "{}" main.webContents.executeJavaScript( injection ).then( handler ) ) //returns "hello" }) }) ``` I would expect the following output: ``` hello hello ``` ### Actual Behavior Instead, I get: ``` {} hello ``` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32756
https://github.com/electron/electron/pull/35292
8e4a168a136f8948d019350a089a8a2878509c6a
43182bf030d7de6fab5b6976f073eb125c2ebe12
2022-02-05T00:46:29Z
c++
2022-08-17T04:08:13Z
spec/api-web-frame-main-spec.ts
import { expect } from 'chai'; import * as http from 'http'; import * as path from 'path'; import * as url from 'url'; import { BrowserWindow, WebFrameMain, webFrameMain, ipcMain } from 'electron/main'; import { closeAllWindows } from './window-helpers'; import { emittedOnce, emittedNTimes } from './events-helpers'; import { AddressInfo } from 'net'; import { ifit, waitUntil } from './spec-helpers'; describe('webFrameMain module', () => { const fixtures = path.resolve(__dirname, 'fixtures'); const subframesPath = path.join(fixtures, 'sub-frames'); const fileUrl = (filename: string) => url.pathToFileURL(path.join(subframesPath, filename)).href; type Server = { server: http.Server, url: string } /** Creates an HTTP server whose handler embeds the given iframe src. */ const createServer = () => new Promise<Server>(resolve => { const server = http.createServer((req, res) => { const params = new URLSearchParams(url.parse(req.url || '').search || ''); if (params.has('frameSrc')) { res.end(`<iframe src="${params.get('frameSrc')}"></iframe>`); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; resolve({ server, url }); }); }); afterEach(closeAllWindows); describe('WebFrame traversal APIs', () => { let w: BrowserWindow; let webFrame: WebFrameMain; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); webFrame = w.webContents.mainFrame; }); it('can access top frame', () => { expect(webFrame.top).to.equal(webFrame); }); it('has no parent on top frame', () => { expect(webFrame.parent).to.be.null(); }); it('can access immediate frame descendents', () => { const { frames } = webFrame; expect(frames).to.have.lengthOf(1); const subframe = frames[0]; expect(subframe).not.to.equal(webFrame); expect(subframe.parent).to.equal(webFrame); }); it('can access deeply nested frames', () => { const subframe = webFrame.frames[0]; expect(subframe).not.to.equal(webFrame); expect(subframe.parent).to.equal(webFrame); const nestedSubframe = subframe.frames[0]; expect(nestedSubframe).not.to.equal(webFrame); expect(nestedSubframe).not.to.equal(subframe); expect(nestedSubframe.parent).to.equal(subframe); }); it('can traverse all frames in root', () => { const urls = webFrame.framesInSubtree.map(frame => frame.url); expect(urls).to.deep.equal([ fileUrl('frame-with-frame-container.html'), fileUrl('frame-with-frame.html'), fileUrl('frame.html') ]); }); it('can traverse all frames in subtree', () => { const urls = webFrame.frames[0].framesInSubtree.map(frame => frame.url); expect(urls).to.deep.equal([ fileUrl('frame-with-frame.html'), fileUrl('frame.html') ]); }); describe('cross-origin', () => { let serverA = null as unknown as Server; let serverB = null as unknown as Server; before(async () => { serverA = await createServer(); serverB = await createServer(); }); after(() => { serverA.server.close(); serverB.server.close(); }); it('can access cross-origin frames', async () => { await w.loadURL(`${serverA.url}?frameSrc=${serverB.url}`); webFrame = w.webContents.mainFrame; expect(webFrame.url.startsWith(serverA.url)).to.be.true(); expect(webFrame.frames[0].url).to.equal(serverB.url); }); }); }); describe('WebFrame.url', () => { it('should report correct address for each subframe', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); const webFrame = w.webContents.mainFrame; expect(webFrame.url).to.equal(fileUrl('frame-with-frame-container.html')); expect(webFrame.frames[0].url).to.equal(fileUrl('frame-with-frame.html')); expect(webFrame.frames[0].frames[0].url).to.equal(fileUrl('frame.html')); }); }); describe('WebFrame IDs', () => { it('has properties for various identifiers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame.html')); const webFrame = w.webContents.mainFrame; expect(webFrame).to.have.ownProperty('url').that.is.a('string'); expect(webFrame).to.have.ownProperty('frameTreeNodeId').that.is.a('number'); expect(webFrame).to.have.ownProperty('name').that.is.a('string'); expect(webFrame).to.have.ownProperty('osProcessId').that.is.a('number'); expect(webFrame).to.have.ownProperty('processId').that.is.a('number'); expect(webFrame).to.have.ownProperty('routingId').that.is.a('number'); }); }); describe('WebFrame.visibilityState', () => { // TODO(MarshallOfSound): Fix flaky test // @flaky-test it.skip('should match window state', async () => { const w = new BrowserWindow({ show: true }); await w.loadURL('about:blank'); const webFrame = w.webContents.mainFrame; expect(webFrame.visibilityState).to.equal('visible'); w.hide(); await expect( waitUntil(() => webFrame.visibilityState === 'hidden') ).to.eventually.be.fulfilled(); }); }); describe('WebFrame.executeJavaScript', () => { it('can inject code into any subframe', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); const webFrame = w.webContents.mainFrame; const getUrl = (frame: WebFrameMain) => frame.executeJavaScript('location.href'); expect(await getUrl(webFrame)).to.equal(fileUrl('frame-with-frame-container.html')); expect(await getUrl(webFrame.frames[0])).to.equal(fileUrl('frame-with-frame.html')); expect(await getUrl(webFrame.frames[0].frames[0])).to.equal(fileUrl('frame.html')); }); }); describe('WebFrame.reload', () => { it('reloads a frame', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame.html')); const webFrame = w.webContents.mainFrame; await webFrame.executeJavaScript('window.TEMP = 1', false); expect(webFrame.reload()).to.be.true(); await emittedOnce(w.webContents, 'dom-ready'); expect(await webFrame.executeJavaScript('window.TEMP', false)).to.be.null(); }); }); describe('WebFrame.send', () => { it('works', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(subframesPath, 'preload.js'), nodeIntegrationInSubFrames: true } }); await w.loadURL('about:blank'); const webFrame = w.webContents.mainFrame; const pongPromise = emittedOnce(ipcMain, 'preload-pong'); webFrame.send('preload-ping'); const [, routingId] = await pongPromise; expect(routingId).to.equal(webFrame.routingId); }); }); describe('RenderFrame lifespan', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); }); // TODO(jkleinsc) fix this flaky test on linux ifit(process.platform !== 'linux')('throws upon accessing properties when disposed', async () => { await w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); const { mainFrame } = w.webContents; w.destroy(); // Wait for WebContents, and thus RenderFrameHost, to be destroyed. await new Promise(resolve => setTimeout(resolve, 0)); expect(() => mainFrame.url).to.throw(); }); it('persists through cross-origin navigation', async () => { const server = await createServer(); // 'localhost' is treated as a separate origin. const crossOriginUrl = server.url.replace('127.0.0.1', 'localhost'); await w.loadURL(server.url); const { mainFrame } = w.webContents; expect(mainFrame.url).to.equal(server.url); await w.loadURL(crossOriginUrl); expect(w.webContents.mainFrame).to.equal(mainFrame); expect(mainFrame.url).to.equal(crossOriginUrl); }); it('recovers from renderer crash on same-origin', async () => { const server = await createServer(); // Keep reference to mainFrame alive throughout crash and recovery. const { mainFrame } = w.webContents; await w.webContents.loadURL(server.url); const crashEvent = emittedOnce(w.webContents, 'render-process-gone'); w.webContents.forcefullyCrashRenderer(); await crashEvent; await w.webContents.loadURL(server.url); // Log just to keep mainFrame in scope. console.log('mainFrame.url', mainFrame.url); }); // Fixed by #34411 it('recovers from renderer crash on cross-origin', async () => { const server = await createServer(); // 'localhost' is treated as a separate origin. const crossOriginUrl = server.url.replace('127.0.0.1', 'localhost'); // Keep reference to mainFrame alive throughout crash and recovery. const { mainFrame } = w.webContents; await w.webContents.loadURL(server.url); const crashEvent = emittedOnce(w.webContents, 'render-process-gone'); w.webContents.forcefullyCrashRenderer(); await crashEvent; // A short wait seems to be required to reproduce the crash. await new Promise(resolve => setTimeout(resolve, 100)); await w.webContents.loadURL(crossOriginUrl); // Log just to keep mainFrame in scope. console.log('mainFrame.url', mainFrame.url); }); }); describe('webFrameMain.fromId', () => { it('returns undefined for unknown IDs', () => { expect(webFrameMain.fromId(0, 0)).to.be.undefined(); }); it('can find each frame from navigation events', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); // frame-with-frame-container.html, frame-with-frame.html, frame.html const didFrameFinishLoad = emittedNTimes(w.webContents, 'did-frame-finish-load', 3); w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); for (const [, isMainFrame, frameProcessId, frameRoutingId] of await didFrameFinishLoad) { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).not.to.be.null(); expect(frame?.processId).to.be.equal(frameProcessId); expect(frame?.routingId).to.be.equal(frameRoutingId); expect(frame?.top === frame).to.be.equal(isMainFrame); } }); }); describe('"frame-created" event', () => { it('emits when the main frame is created', async () => { const w = new BrowserWindow({ show: false }); const promise = emittedOnce(w.webContents, 'frame-created'); w.webContents.loadFile(path.join(subframesPath, 'frame.html')); const [, details] = await promise; expect(details.frame).to.equal(w.webContents.mainFrame); }); it('emits when nested frames are created', async () => { const w = new BrowserWindow({ show: false }); const promise = emittedNTimes(w.webContents, 'frame-created', 2); w.webContents.loadFile(path.join(subframesPath, 'frame-container.html')); const [[, mainDetails], [, nestedDetails]] = await promise; expect(mainDetails.frame).to.equal(w.webContents.mainFrame); expect(nestedDetails.frame).to.equal(w.webContents.mainFrame.frames[0]); }); it('is not emitted upon cross-origin navigation', async () => { const server = await createServer(); // HACK: Use 'localhost' instead of '127.0.0.1' so Chromium treats it as // a separate origin because differing ports aren't enough 🤔 const secondUrl = `http://localhost:${new URL(server.url).port}`; const w = new BrowserWindow({ show: false }); await w.webContents.loadURL(server.url); let frameCreatedEmitted = false; w.webContents.once('frame-created', () => { frameCreatedEmitted = true; }); await w.webContents.loadURL(secondUrl); expect(frameCreatedEmitted).to.be.false(); }); }); describe('"dom-ready" event', () => { it('emits for top-level frame', async () => { const w = new BrowserWindow({ show: false }); const promise = emittedOnce(w.webContents.mainFrame, 'dom-ready'); w.webContents.loadURL('about:blank'); await promise; }); it('emits for sub frame', async () => { const w = new BrowserWindow({ show: false }); const promise = new Promise<void>(resolve => { w.webContents.on('frame-created', (e, { frame }) => { frame.on('dom-ready', () => { if (frame.name === 'frameA') { resolve(); } }); }); }); w.webContents.loadFile(path.join(subframesPath, 'frame-with-frame.html')); await promise; }); }); });
closed
electron/electron
https://github.com/electron/electron
32,164
[Bug]: webFrameMain executeJavaScript doesn't work sometimes
### Preflight Checklist - [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 15.3.0 ### What operating system are you using? macOS ### Operating System Version macOS Monterey ### What arch are you using? x64 ### Last Known Working Electron version 15.3.0 ### Expected Behavior I write some code like this: 1. given a web page with an iframe, iframe and the page url is in **different origin** 2. setup listener in main process(`ipcMain.on`) and wait for message from renderer 3. use preload to inject some code into iframe and mainFrame(the web page) 4. both frames send message via `ipcRenderer` to main process when preload executed 5. after received message from renderer, main process retrieve webFrameMain by `[processId, routing]` provided in event params 6. main process call webFrameMain.executeJavaScript immediately, for every frame that send message to main process What's expected: 1. The code passed by executeJavaScript to be executed in each frame(the web page and iframe) 2. executeJavaScript asynchronously return execution result of passed code. ### Actual Behavior 1. The code didn't executed in iframe sometimes. Just mainFrame work as expected 2. webFrameMain.executeJavaScript.then(res) got res `null` when execute in the iframe. extra info was provided in Additional Information ### Testcase Gist URL [https://gist.github.com/b7714f0812e293339b9a2a08807cf795](https://gist.github.com/b7714f0812e293339b9a2a08807cf795) ### Additional Information 1. if use setTimeout to delay the execution, it **maybe** work in iframe. I tried to delay 10ms、20ms、...200ms and record success rate(test 100times): | delay | success rate | | ---- | --- | | 10ms | about 70% | | 20ms | about 85% | | 30ms | about 90% | | 40ms | about 95% | | 100ms| about 97% | | 200ms | 100% | 2. `webContents.sendToFrame` also has similar issue, renderer process **maybe** not receive message even it can successfully send message to main process 3. If preload send message after iframe 'DOMContentLoaded' event, `executeJavaScript` always success 4. After page and iframe fully loaded, just reload iframe(in console, using location.reload()), executeJavaScript works as expected.
https://github.com/electron/electron/issues/32164
https://github.com/electron/electron/pull/35292
8e4a168a136f8948d019350a089a8a2878509c6a
43182bf030d7de6fab5b6976f073eb125c2ebe12
2021-12-13T08:07:01Z
c++
2022-08-17T04:08:13Z
shell/browser/api/electron_api_web_frame_main.cc
// Copyright (c) 2020 Samuel Maddock <[email protected]>. // 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_frame_main.h" #include <string> #include <unordered_map> #include <utility> #include <vector> #include "base/logging.h" #include "base/no_destructor.h" #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck #include "content/public/browser/render_frame_host.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/object_template_builder.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "shell/browser/api/message_port.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/gin_helper/promise.h" #include "shell/common/node_includes.h" #include "shell/common/v8_value_serializer.h" namespace gin { template <> struct Converter<blink::mojom::PageVisibilityState> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, blink::mojom::PageVisibilityState val) { std::string visibility; switch (val) { case blink::mojom::PageVisibilityState::kVisible: visibility = "visible"; break; case blink::mojom::PageVisibilityState::kHidden: case blink::mojom::PageVisibilityState::kHiddenButPainting: visibility = "hidden"; break; } return gin::ConvertToV8(isolate, visibility); } }; } // namespace gin namespace electron::api { typedef std::unordered_map<int, WebFrameMain*> WebFrameMainIdMap; WebFrameMainIdMap& GetWebFrameMainMap() { static base::NoDestructor<WebFrameMainIdMap> instance; return *instance; } // static WebFrameMain* WebFrameMain::FromFrameTreeNodeId(int frame_tree_node_id) { WebFrameMainIdMap& frame_map = GetWebFrameMainMap(); auto iter = frame_map.find(frame_tree_node_id); auto* web_frame = iter == frame_map.end() ? nullptr : iter->second; return web_frame; } // static WebFrameMain* WebFrameMain::FromRenderFrameHost(content::RenderFrameHost* rfh) { return rfh ? FromFrameTreeNodeId(rfh->GetFrameTreeNodeId()) : nullptr; } gin::WrapperInfo WebFrameMain::kWrapperInfo = {gin::kEmbedderNativeGin}; WebFrameMain::WebFrameMain(content::RenderFrameHost* rfh) : frame_tree_node_id_(rfh->GetFrameTreeNodeId()), render_frame_(rfh) { GetWebFrameMainMap().emplace(frame_tree_node_id_, this); } WebFrameMain::~WebFrameMain() { Destroyed(); } void WebFrameMain::Destroyed() { MarkRenderFrameDisposed(); GetWebFrameMainMap().erase(frame_tree_node_id_); Unpin(); } void WebFrameMain::MarkRenderFrameDisposed() { render_frame_ = nullptr; render_frame_disposed_ = true; TeardownMojoConnection(); } void WebFrameMain::UpdateRenderFrameHost(content::RenderFrameHost* rfh) { // Should only be called when swapping frames. render_frame_disposed_ = false; render_frame_ = rfh; TeardownMojoConnection(); MaybeSetupMojoConnection(); } bool WebFrameMain::CheckRenderFrame() const { if (render_frame_disposed_) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::ErrorThrower(isolate).ThrowError( "Render frame was disposed before WebFrameMain could be accessed"); return false; } return true; } v8::Local<v8::Promise> WebFrameMain::ExecuteJavaScript( gin::Arguments* args, const std::u16string& code) { gin_helper::Promise<base::Value> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // Optional userGesture parameter bool user_gesture; if (!args->PeekNext().IsEmpty()) { if (args->PeekNext()->IsBoolean()) { args->GetNext(&user_gesture); } else { args->ThrowTypeError("userGesture must be a boolean"); return handle; } } else { user_gesture = false; } if (render_frame_disposed_) { promise.RejectWithErrorMessage( "Render frame was disposed before WebFrameMain could be accessed"); return handle; } if (user_gesture) { auto* ftn = content::FrameTreeNode::From(render_frame_); ftn->UpdateUserActivationState( blink::mojom::UserActivationUpdateType::kNotifyActivation, blink::mojom::UserActivationNotificationType::kTest); } render_frame_->ExecuteJavaScriptForTests( code, base::BindOnce([](gin_helper::Promise<base::Value> promise, base::Value value) { promise.Resolve(value); }, std::move(promise))); return handle; } bool WebFrameMain::Reload() { if (!CheckRenderFrame()) return false; return render_frame_->Reload(); } void WebFrameMain::Send(v8::Isolate* isolate, bool internal, const std::string& channel, v8::Local<v8::Value> args) { blink::CloneableMessage message; if (!gin::ConvertFromV8(isolate, args, &message)) { isolate->ThrowException(v8::Exception::Error( gin::StringToV8(isolate, "Failed to serialize arguments"))); return; } if (!CheckRenderFrame()) return; GetRendererApi()->Message(internal, channel, std::move(message), 0 /* sender_id */); } const mojo::Remote<mojom::ElectronRenderer>& WebFrameMain::GetRendererApi() { MaybeSetupMojoConnection(); return renderer_api_; } void WebFrameMain::MaybeSetupMojoConnection() { if (render_frame_disposed_) { // RFH may not be set yet if called between when a new RFH is created and // before it's been swapped with an old RFH. LOG(INFO) << "Attempt to setup WebFrameMain connection while render frame " "is disposed"; return; } if (!renderer_api_) { pending_receiver_ = renderer_api_.BindNewPipeAndPassReceiver(); renderer_api_.set_disconnect_handler(base::BindOnce( &WebFrameMain::OnRendererConnectionError, weak_factory_.GetWeakPtr())); } DCHECK(render_frame_); // Wait for RenderFrame to be created in renderer before accessing remote. if (pending_receiver_ && render_frame_ && render_frame_->IsRenderFrameLive()) { render_frame_->GetRemoteInterfaces()->GetInterface( std::move(pending_receiver_)); } } void WebFrameMain::TeardownMojoConnection() { renderer_api_.reset(); pending_receiver_.reset(); } void WebFrameMain::OnRendererConnectionError() { TeardownMojoConnection(); } void WebFrameMain::PostMessage(v8::Isolate* isolate, const std::string& channel, v8::Local<v8::Value> message_value, absl::optional<v8::Local<v8::Value>> transfer) { blink::TransferableMessage transferable_message; if (!electron::SerializeV8Value(isolate, message_value, &transferable_message)) { // SerializeV8Value sets an exception. return; } std::vector<gin::Handle<MessagePort>> wrapped_ports; if (transfer && !transfer.value()->IsUndefined()) { if (!gin::ConvertFromV8(isolate, *transfer, &wrapped_ports)) { isolate->ThrowException(v8::Exception::Error( gin::StringToV8(isolate, "Invalid value for transfer"))); return; } } bool threw_exception = false; transferable_message.ports = MessagePort::DisentanglePorts(isolate, wrapped_ports, &threw_exception); if (threw_exception) return; if (!CheckRenderFrame()) return; GetRendererApi()->ReceivePostMessage(channel, std::move(transferable_message)); } int WebFrameMain::FrameTreeNodeID() const { return frame_tree_node_id_; } std::string WebFrameMain::Name() const { if (!CheckRenderFrame()) return std::string(); return render_frame_->GetFrameName(); } base::ProcessId WebFrameMain::OSProcessID() const { if (!CheckRenderFrame()) return -1; base::ProcessHandle process_handle = render_frame_->GetProcess()->GetProcess().Handle(); return base::GetProcId(process_handle); } int WebFrameMain::ProcessID() const { if (!CheckRenderFrame()) return -1; return render_frame_->GetProcess()->GetID(); } int WebFrameMain::RoutingID() const { if (!CheckRenderFrame()) return -1; return render_frame_->GetRoutingID(); } GURL WebFrameMain::URL() const { if (!CheckRenderFrame()) return GURL::EmptyGURL(); return render_frame_->GetLastCommittedURL(); } blink::mojom::PageVisibilityState WebFrameMain::VisibilityState() const { if (!CheckRenderFrame()) return blink::mojom::PageVisibilityState::kHidden; return render_frame_->GetVisibilityState(); } content::RenderFrameHost* WebFrameMain::Top() const { if (!CheckRenderFrame()) return nullptr; return render_frame_->GetMainFrame(); } content::RenderFrameHost* WebFrameMain::Parent() const { if (!CheckRenderFrame()) return nullptr; return render_frame_->GetParent(); } std::vector<content::RenderFrameHost*> WebFrameMain::Frames() const { std::vector<content::RenderFrameHost*> frame_hosts; if (!CheckRenderFrame()) return frame_hosts; render_frame_->ForEachRenderFrameHost(base::BindRepeating( [](std::vector<content::RenderFrameHost*>* frame_hosts, content::RenderFrameHost* current_frame, content::RenderFrameHost* rfh) { if (rfh->GetParent() == current_frame) frame_hosts->push_back(rfh); }, &frame_hosts, render_frame_)); return frame_hosts; } std::vector<content::RenderFrameHost*> WebFrameMain::FramesInSubtree() const { std::vector<content::RenderFrameHost*> frame_hosts; if (!CheckRenderFrame()) return frame_hosts; render_frame_->ForEachRenderFrameHost(base::BindRepeating( [](std::vector<content::RenderFrameHost*>* frame_hosts, content::RenderFrameHost* rfh) { frame_hosts->push_back(rfh); }, &frame_hosts)); return frame_hosts; } void WebFrameMain::DOMContentLoaded() { Emit("dom-ready"); } // static gin::Handle<WebFrameMain> WebFrameMain::New(v8::Isolate* isolate) { return gin::Handle<WebFrameMain>(); } // static gin::Handle<WebFrameMain> WebFrameMain::From(v8::Isolate* isolate, content::RenderFrameHost* rfh) { if (rfh == nullptr) return gin::Handle<WebFrameMain>(); auto* web_frame = FromRenderFrameHost(rfh); if (web_frame) return gin::CreateHandle(isolate, web_frame); auto handle = gin::CreateHandle(isolate, new WebFrameMain(rfh)); // Prevent garbage collection of frame until it has been deleted internally. handle->Pin(isolate); return handle; } // static gin::Handle<WebFrameMain> WebFrameMain::FromOrNull( v8::Isolate* isolate, content::RenderFrameHost* rfh) { if (rfh == nullptr) return gin::Handle<WebFrameMain>(); auto* web_frame = FromRenderFrameHost(rfh); if (web_frame) return gin::CreateHandle(isolate, web_frame); return gin::Handle<WebFrameMain>(); } // static v8::Local<v8::ObjectTemplate> WebFrameMain::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("executeJavaScript", &WebFrameMain::ExecuteJavaScript) .SetMethod("reload", &WebFrameMain::Reload) .SetMethod("_send", &WebFrameMain::Send) .SetMethod("_postMessage", &WebFrameMain::PostMessage) .SetProperty("frameTreeNodeId", &WebFrameMain::FrameTreeNodeID) .SetProperty("name", &WebFrameMain::Name) .SetProperty("osProcessId", &WebFrameMain::OSProcessID) .SetProperty("processId", &WebFrameMain::ProcessID) .SetProperty("routingId", &WebFrameMain::RoutingID) .SetProperty("url", &WebFrameMain::URL) .SetProperty("visibilityState", &WebFrameMain::VisibilityState) .SetProperty("top", &WebFrameMain::Top) .SetProperty("parent", &WebFrameMain::Parent) .SetProperty("frames", &WebFrameMain::Frames) .SetProperty("framesInSubtree", &WebFrameMain::FramesInSubtree) .Build(); } const char* WebFrameMain::GetTypeName() { return "WebFrameMain"; } } // namespace electron::api namespace { using electron::api::WebFrameMain; v8::Local<v8::Value> FromID(gin_helper::ErrorThrower thrower, int render_process_id, int render_frame_id) { if (!electron::Browser::Get()->is_ready()) { thrower.ThrowError("WebFrameMain is available only after app ready"); return v8::Null(thrower.isolate()); } auto* rfh = content::RenderFrameHost::FromID(render_process_id, render_frame_id); return WebFrameMain::From(thrower.isolate(), rfh).ToV8(); } v8::Local<v8::Value> FromIDOrNull(gin_helper::ErrorThrower thrower, int render_process_id, int render_frame_id) { if (!electron::Browser::Get()->is_ready()) { thrower.ThrowError("WebFrameMain is available only after app ready"); return v8::Null(thrower.isolate()); } auto* rfh = content::RenderFrameHost::FromID(render_process_id, render_frame_id); return WebFrameMain::FromOrNull(thrower.isolate(), rfh).ToV8(); } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebFrameMain", WebFrameMain::GetConstructor(context)); dict.SetMethod("fromId", &FromID); dict.SetMethod("fromIdOrNull", &FromIDOrNull); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_frame_main, Initialize)
closed
electron/electron
https://github.com/electron/electron
32,164
[Bug]: webFrameMain executeJavaScript doesn't work sometimes
### Preflight Checklist - [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_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 15.3.0 ### What operating system are you using? macOS ### Operating System Version macOS Monterey ### What arch are you using? x64 ### Last Known Working Electron version 15.3.0 ### Expected Behavior I write some code like this: 1. given a web page with an iframe, iframe and the page url is in **different origin** 2. setup listener in main process(`ipcMain.on`) and wait for message from renderer 3. use preload to inject some code into iframe and mainFrame(the web page) 4. both frames send message via `ipcRenderer` to main process when preload executed 5. after received message from renderer, main process retrieve webFrameMain by `[processId, routing]` provided in event params 6. main process call webFrameMain.executeJavaScript immediately, for every frame that send message to main process What's expected: 1. The code passed by executeJavaScript to be executed in each frame(the web page and iframe) 2. executeJavaScript asynchronously return execution result of passed code. ### Actual Behavior 1. The code didn't executed in iframe sometimes. Just mainFrame work as expected 2. webFrameMain.executeJavaScript.then(res) got res `null` when execute in the iframe. extra info was provided in Additional Information ### Testcase Gist URL [https://gist.github.com/b7714f0812e293339b9a2a08807cf795](https://gist.github.com/b7714f0812e293339b9a2a08807cf795) ### Additional Information 1. if use setTimeout to delay the execution, it **maybe** work in iframe. I tried to delay 10ms、20ms、...200ms and record success rate(test 100times): | delay | success rate | | ---- | --- | | 10ms | about 70% | | 20ms | about 85% | | 30ms | about 90% | | 40ms | about 95% | | 100ms| about 97% | | 200ms | 100% | 2. `webContents.sendToFrame` also has similar issue, renderer process **maybe** not receive message even it can successfully send message to main process 3. If preload send message after iframe 'DOMContentLoaded' event, `executeJavaScript` always success 4. After page and iframe fully loaded, just reload iframe(in console, using location.reload()), executeJavaScript works as expected.
https://github.com/electron/electron/issues/32164
https://github.com/electron/electron/pull/35292
8e4a168a136f8948d019350a089a8a2878509c6a
43182bf030d7de6fab5b6976f073eb125c2ebe12
2021-12-13T08:07:01Z
c++
2022-08-17T04:08:13Z
spec/api-web-frame-main-spec.ts
import { expect } from 'chai'; import * as http from 'http'; import * as path from 'path'; import * as url from 'url'; import { BrowserWindow, WebFrameMain, webFrameMain, ipcMain } from 'electron/main'; import { closeAllWindows } from './window-helpers'; import { emittedOnce, emittedNTimes } from './events-helpers'; import { AddressInfo } from 'net'; import { ifit, waitUntil } from './spec-helpers'; describe('webFrameMain module', () => { const fixtures = path.resolve(__dirname, 'fixtures'); const subframesPath = path.join(fixtures, 'sub-frames'); const fileUrl = (filename: string) => url.pathToFileURL(path.join(subframesPath, filename)).href; type Server = { server: http.Server, url: string } /** Creates an HTTP server whose handler embeds the given iframe src. */ const createServer = () => new Promise<Server>(resolve => { const server = http.createServer((req, res) => { const params = new URLSearchParams(url.parse(req.url || '').search || ''); if (params.has('frameSrc')) { res.end(`<iframe src="${params.get('frameSrc')}"></iframe>`); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; resolve({ server, url }); }); }); afterEach(closeAllWindows); describe('WebFrame traversal APIs', () => { let w: BrowserWindow; let webFrame: WebFrameMain; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); webFrame = w.webContents.mainFrame; }); it('can access top frame', () => { expect(webFrame.top).to.equal(webFrame); }); it('has no parent on top frame', () => { expect(webFrame.parent).to.be.null(); }); it('can access immediate frame descendents', () => { const { frames } = webFrame; expect(frames).to.have.lengthOf(1); const subframe = frames[0]; expect(subframe).not.to.equal(webFrame); expect(subframe.parent).to.equal(webFrame); }); it('can access deeply nested frames', () => { const subframe = webFrame.frames[0]; expect(subframe).not.to.equal(webFrame); expect(subframe.parent).to.equal(webFrame); const nestedSubframe = subframe.frames[0]; expect(nestedSubframe).not.to.equal(webFrame); expect(nestedSubframe).not.to.equal(subframe); expect(nestedSubframe.parent).to.equal(subframe); }); it('can traverse all frames in root', () => { const urls = webFrame.framesInSubtree.map(frame => frame.url); expect(urls).to.deep.equal([ fileUrl('frame-with-frame-container.html'), fileUrl('frame-with-frame.html'), fileUrl('frame.html') ]); }); it('can traverse all frames in subtree', () => { const urls = webFrame.frames[0].framesInSubtree.map(frame => frame.url); expect(urls).to.deep.equal([ fileUrl('frame-with-frame.html'), fileUrl('frame.html') ]); }); describe('cross-origin', () => { let serverA = null as unknown as Server; let serverB = null as unknown as Server; before(async () => { serverA = await createServer(); serverB = await createServer(); }); after(() => { serverA.server.close(); serverB.server.close(); }); it('can access cross-origin frames', async () => { await w.loadURL(`${serverA.url}?frameSrc=${serverB.url}`); webFrame = w.webContents.mainFrame; expect(webFrame.url.startsWith(serverA.url)).to.be.true(); expect(webFrame.frames[0].url).to.equal(serverB.url); }); }); }); describe('WebFrame.url', () => { it('should report correct address for each subframe', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); const webFrame = w.webContents.mainFrame; expect(webFrame.url).to.equal(fileUrl('frame-with-frame-container.html')); expect(webFrame.frames[0].url).to.equal(fileUrl('frame-with-frame.html')); expect(webFrame.frames[0].frames[0].url).to.equal(fileUrl('frame.html')); }); }); describe('WebFrame IDs', () => { it('has properties for various identifiers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame.html')); const webFrame = w.webContents.mainFrame; expect(webFrame).to.have.ownProperty('url').that.is.a('string'); expect(webFrame).to.have.ownProperty('frameTreeNodeId').that.is.a('number'); expect(webFrame).to.have.ownProperty('name').that.is.a('string'); expect(webFrame).to.have.ownProperty('osProcessId').that.is.a('number'); expect(webFrame).to.have.ownProperty('processId').that.is.a('number'); expect(webFrame).to.have.ownProperty('routingId').that.is.a('number'); }); }); describe('WebFrame.visibilityState', () => { // TODO(MarshallOfSound): Fix flaky test // @flaky-test it.skip('should match window state', async () => { const w = new BrowserWindow({ show: true }); await w.loadURL('about:blank'); const webFrame = w.webContents.mainFrame; expect(webFrame.visibilityState).to.equal('visible'); w.hide(); await expect( waitUntil(() => webFrame.visibilityState === 'hidden') ).to.eventually.be.fulfilled(); }); }); describe('WebFrame.executeJavaScript', () => { it('can inject code into any subframe', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); const webFrame = w.webContents.mainFrame; const getUrl = (frame: WebFrameMain) => frame.executeJavaScript('location.href'); expect(await getUrl(webFrame)).to.equal(fileUrl('frame-with-frame-container.html')); expect(await getUrl(webFrame.frames[0])).to.equal(fileUrl('frame-with-frame.html')); expect(await getUrl(webFrame.frames[0].frames[0])).to.equal(fileUrl('frame.html')); }); }); describe('WebFrame.reload', () => { it('reloads a frame', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadFile(path.join(subframesPath, 'frame.html')); const webFrame = w.webContents.mainFrame; await webFrame.executeJavaScript('window.TEMP = 1', false); expect(webFrame.reload()).to.be.true(); await emittedOnce(w.webContents, 'dom-ready'); expect(await webFrame.executeJavaScript('window.TEMP', false)).to.be.null(); }); }); describe('WebFrame.send', () => { it('works', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(subframesPath, 'preload.js'), nodeIntegrationInSubFrames: true } }); await w.loadURL('about:blank'); const webFrame = w.webContents.mainFrame; const pongPromise = emittedOnce(ipcMain, 'preload-pong'); webFrame.send('preload-ping'); const [, routingId] = await pongPromise; expect(routingId).to.equal(webFrame.routingId); }); }); describe('RenderFrame lifespan', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); }); // TODO(jkleinsc) fix this flaky test on linux ifit(process.platform !== 'linux')('throws upon accessing properties when disposed', async () => { await w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); const { mainFrame } = w.webContents; w.destroy(); // Wait for WebContents, and thus RenderFrameHost, to be destroyed. await new Promise(resolve => setTimeout(resolve, 0)); expect(() => mainFrame.url).to.throw(); }); it('persists through cross-origin navigation', async () => { const server = await createServer(); // 'localhost' is treated as a separate origin. const crossOriginUrl = server.url.replace('127.0.0.1', 'localhost'); await w.loadURL(server.url); const { mainFrame } = w.webContents; expect(mainFrame.url).to.equal(server.url); await w.loadURL(crossOriginUrl); expect(w.webContents.mainFrame).to.equal(mainFrame); expect(mainFrame.url).to.equal(crossOriginUrl); }); it('recovers from renderer crash on same-origin', async () => { const server = await createServer(); // Keep reference to mainFrame alive throughout crash and recovery. const { mainFrame } = w.webContents; await w.webContents.loadURL(server.url); const crashEvent = emittedOnce(w.webContents, 'render-process-gone'); w.webContents.forcefullyCrashRenderer(); await crashEvent; await w.webContents.loadURL(server.url); // Log just to keep mainFrame in scope. console.log('mainFrame.url', mainFrame.url); }); // Fixed by #34411 it('recovers from renderer crash on cross-origin', async () => { const server = await createServer(); // 'localhost' is treated as a separate origin. const crossOriginUrl = server.url.replace('127.0.0.1', 'localhost'); // Keep reference to mainFrame alive throughout crash and recovery. const { mainFrame } = w.webContents; await w.webContents.loadURL(server.url); const crashEvent = emittedOnce(w.webContents, 'render-process-gone'); w.webContents.forcefullyCrashRenderer(); await crashEvent; // A short wait seems to be required to reproduce the crash. await new Promise(resolve => setTimeout(resolve, 100)); await w.webContents.loadURL(crossOriginUrl); // Log just to keep mainFrame in scope. console.log('mainFrame.url', mainFrame.url); }); }); describe('webFrameMain.fromId', () => { it('returns undefined for unknown IDs', () => { expect(webFrameMain.fromId(0, 0)).to.be.undefined(); }); it('can find each frame from navigation events', async () => { const w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); // frame-with-frame-container.html, frame-with-frame.html, frame.html const didFrameFinishLoad = emittedNTimes(w.webContents, 'did-frame-finish-load', 3); w.loadFile(path.join(subframesPath, 'frame-with-frame-container.html')); for (const [, isMainFrame, frameProcessId, frameRoutingId] of await didFrameFinishLoad) { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).not.to.be.null(); expect(frame?.processId).to.be.equal(frameProcessId); expect(frame?.routingId).to.be.equal(frameRoutingId); expect(frame?.top === frame).to.be.equal(isMainFrame); } }); }); describe('"frame-created" event', () => { it('emits when the main frame is created', async () => { const w = new BrowserWindow({ show: false }); const promise = emittedOnce(w.webContents, 'frame-created'); w.webContents.loadFile(path.join(subframesPath, 'frame.html')); const [, details] = await promise; expect(details.frame).to.equal(w.webContents.mainFrame); }); it('emits when nested frames are created', async () => { const w = new BrowserWindow({ show: false }); const promise = emittedNTimes(w.webContents, 'frame-created', 2); w.webContents.loadFile(path.join(subframesPath, 'frame-container.html')); const [[, mainDetails], [, nestedDetails]] = await promise; expect(mainDetails.frame).to.equal(w.webContents.mainFrame); expect(nestedDetails.frame).to.equal(w.webContents.mainFrame.frames[0]); }); it('is not emitted upon cross-origin navigation', async () => { const server = await createServer(); // HACK: Use 'localhost' instead of '127.0.0.1' so Chromium treats it as // a separate origin because differing ports aren't enough 🤔 const secondUrl = `http://localhost:${new URL(server.url).port}`; const w = new BrowserWindow({ show: false }); await w.webContents.loadURL(server.url); let frameCreatedEmitted = false; w.webContents.once('frame-created', () => { frameCreatedEmitted = true; }); await w.webContents.loadURL(secondUrl); expect(frameCreatedEmitted).to.be.false(); }); }); describe('"dom-ready" event', () => { it('emits for top-level frame', async () => { const w = new BrowserWindow({ show: false }); const promise = emittedOnce(w.webContents.mainFrame, 'dom-ready'); w.webContents.loadURL('about:blank'); await promise; }); it('emits for sub frame', async () => { const w = new BrowserWindow({ show: false }); const promise = new Promise<void>(resolve => { w.webContents.on('frame-created', (e, { frame }) => { frame.on('dom-ready', () => { if (frame.name === 'frameA') { resolve(); } }); }); }); w.webContents.loadFile(path.join(subframesPath, 'frame-with-frame.html')); await promise; }); }); });
closed
electron/electron
https://github.com/electron/electron
34,406
[Bug]: red background on hover to PiP
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.1 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro Version 19044.1706 ### What arch are you using? x64 ### Last Known Working Electron version 18.1.0 ### Expected Behavior when hovering over pip, there is no red background and controls are visible ### Actual Behavior when hovering over pip, there is a red background and no controls are visible ### Testcase Gist URL _No response_ ### Additional Information ![image](https://user-images.githubusercontent.com/11525479/171402617-11d4444d-fe18-4711-b5c5-a0773f9993b1.png)
https://github.com/electron/electron/issues/34406
https://github.com/electron/electron/pull/35034
fc2e6bd0ed86c9e1f26fcf5f973f508474e469ea
9b2b1998b8386aa324ed617ed2cc23df742eb767
2022-06-01T12:18:25Z
c++
2022-08-22T14:38:45Z
chromium_src/BUILD.gn
# Copyright (c) 2018 GitHub, Inc. # Use of this source code is governed by the MIT license that can be # found in the LICENSE file. import("//build/config/ozone.gni") import("//build/config/ui.gni") import("//components/spellcheck/spellcheck_build_features.gni") import("//electron/buildflags/buildflags.gni") import("//printing/buildflags/buildflags.gni") import("//third_party/widevine/cdm/widevine.gni") # Builds some of the chrome sources that Electron depends on. static_library("chrome") { visibility = [ "//electron:electron_lib" ] sources = [ "//chrome/browser/accessibility/accessibility_ui.cc", "//chrome/browser/accessibility/accessibility_ui.h", "//chrome/browser/app_mode/app_mode_utils.cc", "//chrome/browser/app_mode/app_mode_utils.h", "//chrome/browser/browser_features.cc", "//chrome/browser/browser_features.h", "//chrome/browser/browser_process.cc", "//chrome/browser/browser_process.h", "//chrome/browser/devtools/devtools_contents_resizing_strategy.cc", "//chrome/browser/devtools/devtools_contents_resizing_strategy.h", "//chrome/browser/devtools/devtools_embedder_message_dispatcher.cc", "//chrome/browser/devtools/devtools_embedder_message_dispatcher.h", "//chrome/browser/devtools/devtools_eye_dropper.cc", "//chrome/browser/devtools/devtools_eye_dropper.h", "//chrome/browser/devtools/devtools_file_system_indexer.cc", "//chrome/browser/devtools/devtools_file_system_indexer.h", "//chrome/browser/devtools/devtools_settings.h", "//chrome/browser/extensions/global_shortcut_listener.cc", "//chrome/browser/extensions/global_shortcut_listener.h", "//chrome/browser/icon_loader.cc", "//chrome/browser/icon_loader.h", "//chrome/browser/icon_manager.cc", "//chrome/browser/icon_manager.h", "//chrome/browser/net/chrome_mojo_proxy_resolver_factory.cc", "//chrome/browser/net/chrome_mojo_proxy_resolver_factory.h", "//chrome/browser/net/proxy_config_monitor.cc", "//chrome/browser/net/proxy_config_monitor.h", "//chrome/browser/net/proxy_service_factory.cc", "//chrome/browser/net/proxy_service_factory.h", "//chrome/browser/platform_util.cc", "//chrome/browser/platform_util.h", "//chrome/browser/predictors/preconnect_manager.cc", "//chrome/browser/predictors/preconnect_manager.h", "//chrome/browser/predictors/predictors_features.cc", "//chrome/browser/predictors/predictors_features.h", "//chrome/browser/predictors/proxy_lookup_client_impl.cc", "//chrome/browser/predictors/proxy_lookup_client_impl.h", "//chrome/browser/predictors/resolve_host_client_impl.cc", "//chrome/browser/predictors/resolve_host_client_impl.h", "//chrome/browser/process_singleton.h", "//chrome/browser/process_singleton_internal.cc", "//chrome/browser/process_singleton_internal.h", "//chrome/browser/ui/exclusive_access/exclusive_access_bubble_type.cc", "//chrome/browser/ui/exclusive_access/exclusive_access_bubble_type.h", "//chrome/browser/ui/exclusive_access/exclusive_access_controller_base.cc", "//chrome/browser/ui/exclusive_access/exclusive_access_controller_base.h", "//chrome/browser/ui/exclusive_access/exclusive_access_manager.cc", "//chrome/browser/ui/exclusive_access/exclusive_access_manager.h", "//chrome/browser/ui/exclusive_access/fullscreen_controller.cc", "//chrome/browser/ui/exclusive_access/fullscreen_controller.h", "//chrome/browser/ui/exclusive_access/fullscreen_within_tab_helper.cc", "//chrome/browser/ui/exclusive_access/fullscreen_within_tab_helper.h", "//chrome/browser/ui/exclusive_access/keyboard_lock_controller.cc", "//chrome/browser/ui/exclusive_access/keyboard_lock_controller.h", "//chrome/browser/ui/exclusive_access/mouse_lock_controller.cc", "//chrome/browser/ui/exclusive_access/mouse_lock_controller.h", "//chrome/browser/ui/native_window_tracker.h", "//chrome/browser/ui/views/eye_dropper/eye_dropper.cc", "//chrome/browser/ui/views/eye_dropper/eye_dropper.h", "//chrome/browser/ui/views/eye_dropper/eye_dropper_view.cc", "//chrome/browser/ui/views/eye_dropper/eye_dropper_view.h", "//extensions/browser/app_window/size_constraints.cc", "//extensions/browser/app_window/size_constraints.h", ] if (is_posix) { sources += [ "//chrome/browser/process_singleton_posix.cc" ] } if (is_mac) { sources += [ "//chrome/browser/extensions/global_shortcut_listener_mac.h", "//chrome/browser/extensions/global_shortcut_listener_mac.mm", "//chrome/browser/icon_loader_mac.mm", "//chrome/browser/media/webrtc/system_media_capture_permissions_mac.h", "//chrome/browser/media/webrtc/system_media_capture_permissions_mac.mm", "//chrome/browser/media/webrtc/system_media_capture_permissions_stats_mac.h", "//chrome/browser/media/webrtc/system_media_capture_permissions_stats_mac.mm", "//chrome/browser/media/webrtc/window_icon_util_mac.mm", "//chrome/browser/platform_util_mac.mm", "//chrome/browser/process_singleton_mac.mm", "//chrome/browser/ui/views/eye_dropper/eye_dropper_view_mac.h", "//chrome/browser/ui/views/eye_dropper/eye_dropper_view_mac.mm", ] } if (is_win) { sources += [ "//chrome/browser/extensions/global_shortcut_listener_win.cc", "//chrome/browser/extensions/global_shortcut_listener_win.h", "//chrome/browser/icon_loader_win.cc", "//chrome/browser/media/webrtc/window_icon_util_win.cc", "//chrome/browser/process_singleton_win.cc", "//chrome/browser/ui/frame/window_frame_util.h", "//chrome/browser/ui/view_ids.h", "//chrome/browser/win/chrome_process_finder.cc", "//chrome/browser/win/chrome_process_finder.h", "//chrome/browser/win/titlebar_config.h", "//chrome/child/v8_crashpad_support_win.cc", "//chrome/child/v8_crashpad_support_win.h", ] } if (is_linux) { sources += [ "//chrome/browser/media/webrtc/window_icon_util_ozone.cc" ] } if (use_aura) { sources += [ "//chrome/browser/platform_util_aura.cc", "//chrome/browser/ui/aura/native_window_tracker_aura.cc", "//chrome/browser/ui/aura/native_window_tracker_aura.h", "//chrome/browser/ui/views/eye_dropper/eye_dropper_view_aura.cc", ] } public_deps = [ "//chrome/browser:dev_ui_browser_resources", "//chrome/common", "//chrome/common:version_header", "//components/keyed_service/content", "//components/paint_preview/buildflags", "//components/proxy_config", "//components/services/language_detection/public/mojom", "//content/public/browser", "//services/strings", ] deps = [ "//chrome/browser:resource_prefetch_predictor_proto", "//components/optimization_guide/proto:optimization_guide_proto", ] if (is_linux) { sources += [ "//chrome/browser/icon_loader_auralinux.cc" ] if (use_ozone) { deps += [ "//ui/ozone" ] sources += [ "//chrome/browser/extensions/global_shortcut_listener_ozone.cc", "//chrome/browser/extensions/global_shortcut_listener_ozone.h", ] } sources += [ "//chrome/browser/ui/views/status_icons/concat_menu_model.cc", "//chrome/browser/ui/views/status_icons/concat_menu_model.h", "//chrome/browser/ui/views/status_icons/status_icon_linux_dbus.cc", "//chrome/browser/ui/views/status_icons/status_icon_linux_dbus.h", ] public_deps += [ "//components/dbus/menu", "//components/dbus/thread_linux", ] } if (is_win) { sources += [ "//chrome/browser/win/icon_reader_service.cc", "//chrome/browser/win/icon_reader_service.h", ] public_deps += [ "//chrome/services/util_win:lib" ] } if (enable_desktop_capturer) { sources += [ "//chrome/browser/media/webrtc/desktop_media_list.cc", "//chrome/browser/media/webrtc/desktop_media_list.h", "//chrome/browser/media/webrtc/desktop_media_list_base.cc", "//chrome/browser/media/webrtc/desktop_media_list_base.h", "//chrome/browser/media/webrtc/desktop_media_list_observer.h", "//chrome/browser/media/webrtc/native_desktop_media_list.cc", "//chrome/browser/media/webrtc/native_desktop_media_list.h", "//chrome/browser/media/webrtc/window_icon_util.h", ] deps += [ "//ui/snapshot" ] } if (enable_widevine) { sources += [ "//chrome/renderer/media/chrome_key_systems.cc", "//chrome/renderer/media/chrome_key_systems.h", "//chrome/renderer/media/chrome_key_systems_provider.cc", "//chrome/renderer/media/chrome_key_systems_provider.h", ] deps += [ "//components/cdm/renderer" ] } if (enable_basic_printing) { sources += [ "//chrome/browser/bad_message.cc", "//chrome/browser/bad_message.h", "//chrome/browser/printing/print_job.cc", "//chrome/browser/printing/print_job.h", "//chrome/browser/printing/print_job_manager.cc", "//chrome/browser/printing/print_job_manager.h", "//chrome/browser/printing/print_job_worker.cc", "//chrome/browser/printing/print_job_worker.h", "//chrome/browser/printing/print_job_worker_oop.cc", "//chrome/browser/printing/print_job_worker_oop.h", "//chrome/browser/printing/print_view_manager_base.cc", "//chrome/browser/printing/print_view_manager_base.h", "//chrome/browser/printing/printer_query.cc", "//chrome/browser/printing/printer_query.h", "//chrome/browser/printing/printing_service.cc", "//chrome/browser/printing/printing_service.h", "//components/printing/browser/print_to_pdf/pdf_print_utils.cc", "//components/printing/browser/print_to_pdf/pdf_print_utils.h", ] if (enable_oop_printing) { sources += [ "//chrome/browser/printing/print_backend_service_manager.cc", "//chrome/browser/printing/print_backend_service_manager.h", ] } public_deps += [ "//chrome/services/printing:lib", "//components/printing/browser", "//components/printing/renderer", "//components/services/print_compositor", "//components/services/print_compositor/public/cpp", "//components/services/print_compositor/public/mojom", "//printing/backend", ] deps += [ "//components/printing/common", "//printing", ] if (is_win) { sources += [ "//chrome/browser/printing/pdf_to_emf_converter.cc", "//chrome/browser/printing/pdf_to_emf_converter.h", ] } } if (enable_picture_in_picture) { sources += [ "//chrome/browser/picture_in_picture/picture_in_picture_window_manager.cc", "//chrome/browser/picture_in_picture/picture_in_picture_window_manager.h", "//chrome/browser/ui/views/overlay/back_to_tab_image_button.cc", "//chrome/browser/ui/views/overlay/back_to_tab_image_button.h", "//chrome/browser/ui/views/overlay/back_to_tab_label_button.cc", "//chrome/browser/ui/views/overlay/close_image_button.cc", "//chrome/browser/ui/views/overlay/close_image_button.h", "//chrome/browser/ui/views/overlay/constants.h", "//chrome/browser/ui/views/overlay/document_overlay_window_views.cc", "//chrome/browser/ui/views/overlay/document_overlay_window_views.h", "//chrome/browser/ui/views/overlay/hang_up_button.cc", "//chrome/browser/ui/views/overlay/hang_up_button.h", "//chrome/browser/ui/views/overlay/overlay_window_image_button.cc", "//chrome/browser/ui/views/overlay/overlay_window_image_button.h", "//chrome/browser/ui/views/overlay/overlay_window_views.cc", "//chrome/browser/ui/views/overlay/overlay_window_views.h", "//chrome/browser/ui/views/overlay/playback_image_button.cc", "//chrome/browser/ui/views/overlay/playback_image_button.h", "//chrome/browser/ui/views/overlay/resize_handle_button.cc", "//chrome/browser/ui/views/overlay/resize_handle_button.h", "//chrome/browser/ui/views/overlay/skip_ad_label_button.cc", "//chrome/browser/ui/views/overlay/skip_ad_label_button.h", "//chrome/browser/ui/views/overlay/toggle_camera_button.cc", "//chrome/browser/ui/views/overlay/toggle_camera_button.h", "//chrome/browser/ui/views/overlay/toggle_microphone_button.cc", "//chrome/browser/ui/views/overlay/toggle_microphone_button.h", "//chrome/browser/ui/views/overlay/track_image_button.cc", "//chrome/browser/ui/views/overlay/track_image_button.h", "//chrome/browser/ui/views/overlay/video_overlay_window_views.cc", "//chrome/browser/ui/views/overlay/video_overlay_window_views.h", ] deps += [ "//chrome/app/vector_icons", "//components/vector_icons:vector_icons", "//ui/views/controls/webview", ] } if (enable_electron_extensions) { sources += [ "//chrome/browser/extensions/chrome_url_request_util.cc", "//chrome/browser/extensions/chrome_url_request_util.h", "//chrome/browser/plugins/plugin_response_interceptor_url_loader_throttle.cc", "//chrome/browser/plugins/plugin_response_interceptor_url_loader_throttle.h", "//chrome/renderer/extensions/extension_hooks_delegate.cc", "//chrome/renderer/extensions/extension_hooks_delegate.h", "//chrome/renderer/extensions/tabs_hooks_delegate.cc", "//chrome/renderer/extensions/tabs_hooks_delegate.h", ] if (enable_pdf_viewer) { sources += [ "//chrome/browser/pdf/chrome_pdf_stream_delegate.cc", "//chrome/browser/pdf/chrome_pdf_stream_delegate.h", "//chrome/browser/pdf/pdf_extension_util.cc", "//chrome/browser/pdf/pdf_extension_util.h", "//chrome/browser/pdf/pdf_frame_util.cc", "//chrome/browser/pdf/pdf_frame_util.h", "//chrome/browser/plugins/pdf_iframe_navigation_throttle.cc", "//chrome/browser/plugins/pdf_iframe_navigation_throttle.h", ] deps += [ "//components/pdf/browser", "//components/pdf/renderer", ] } } if (!is_mas_build) { sources += [ "//chrome/browser/hang_monitor/hang_crash_dump.h" ] if (is_mac) { sources += [ "//chrome/browser/hang_monitor/hang_crash_dump_mac.cc" ] } else if (is_win) { sources += [ "//chrome/browser/hang_monitor/hang_crash_dump_win.cc" ] } else { sources += [ "//chrome/browser/hang_monitor/hang_crash_dump.cc" ] } } } source_set("plugins") { sources = [] deps = [] frameworks = [] # browser side sources += [ "//chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.cc", "//chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h", "//chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc", "//chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.h", ] # renderer side sources += [ "//chrome/renderer/pepper/chrome_renderer_pepper_host_factory.cc", "//chrome/renderer/pepper/chrome_renderer_pepper_host_factory.h", "//chrome/renderer/pepper/pepper_shared_memory_message_filter.cc", "//chrome/renderer/pepper/pepper_shared_memory_message_filter.h", ] deps += [ "//components/strings", "//media:media_buildflags", "//ppapi/buildflags", "//ppapi/host", "//ppapi/proxy", "//ppapi/proxy:ipc", "//ppapi/shared_impl", "//services/device/public/mojom", "//skia", "//storage/browser", ] } # This source set is just so we don't have to depend on all of //chrome/browser # You may have to add new files here during the upgrade if //chrome/browser/spellchecker # gets more files source_set("chrome_spellchecker") { sources = [] deps = [] libs = [] public_deps = [] if (enable_builtin_spellchecker) { sources += [ "//chrome/browser/spellchecker/spell_check_host_chrome_impl.cc", "//chrome/browser/spellchecker/spell_check_host_chrome_impl.h", "//chrome/browser/spellchecker/spellcheck_custom_dictionary.cc", "//chrome/browser/spellchecker/spellcheck_custom_dictionary.h", "//chrome/browser/spellchecker/spellcheck_factory.cc", "//chrome/browser/spellchecker/spellcheck_factory.h", "//chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc", "//chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h", "//chrome/browser/spellchecker/spellcheck_service.cc", "//chrome/browser/spellchecker/spellcheck_service.h", ] if (!is_mac) { sources += [ "//chrome/browser/spellchecker/spellcheck_language_blocklist_policy_handler.cc", "//chrome/browser/spellchecker/spellcheck_language_blocklist_policy_handler.h", "//chrome/browser/spellchecker/spellcheck_language_policy_handler.cc", "//chrome/browser/spellchecker/spellcheck_language_policy_handler.h", ] } if (has_spellcheck_panel) { sources += [ "//chrome/browser/spellchecker/spell_check_panel_host_impl.cc", "//chrome/browser/spellchecker/spell_check_panel_host_impl.h", ] } if (use_browser_spellchecker) { sources += [ "//chrome/browser/spellchecker/spelling_request.cc", "//chrome/browser/spellchecker/spelling_request.h", ] } deps += [ "//base:base_static", "//components/language/core/browser", "//components/spellcheck:buildflags", "//components/sync", ] public_deps += [ "//chrome/common:constants" ] } public_deps += [ "//components/spellcheck/browser", "//components/spellcheck/common", "//components/spellcheck/renderer", ] }
closed
electron/electron
https://github.com/electron/electron
34,406
[Bug]: red background on hover to PiP
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.1 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro Version 19044.1706 ### What arch are you using? x64 ### Last Known Working Electron version 18.1.0 ### Expected Behavior when hovering over pip, there is no red background and controls are visible ### Actual Behavior when hovering over pip, there is a red background and no controls are visible ### Testcase Gist URL _No response_ ### Additional Information ![image](https://user-images.githubusercontent.com/11525479/171402617-11d4444d-fe18-4711-b5c5-a0773f9993b1.png)
https://github.com/electron/electron/issues/34406
https://github.com/electron/electron/pull/35034
fc2e6bd0ed86c9e1f26fcf5f973f508474e469ea
9b2b1998b8386aa324ed617ed2cc23df742eb767
2022-06-01T12:18:25Z
c++
2022-08-22T14:38:45Z
shell/browser/electron_browser_main_parts.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_main_parts.h" #include <memory> #include <string> #include <utility> #include "base/base_switches.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/metrics/field_trial.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/icon_manager.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "components/os_crypt/key_storage_config_linux.h" #include "components/os_crypt/os_crypt.h" #include "content/browser/browser_main_loop.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/device_service.h" #include "content/public/browser/first_party_sets_handler.h" #include "content/public/browser/web_ui_controller_factory.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/result_codes.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "media/base/localized_strings.h" #include "services/network/public/cpp/features.h" #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" #include "shell/app/electron_main_delegate.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/browser.h" #include "shell/browser/browser_process_impl.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_web_ui_controller_factory.h" #include "shell/browser/feature_list.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" #include "shell/browser/ui/devtools_manager_delegate.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_helper/trackable_object.h" #include "shell/common/logging.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/idle/idle.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_switches.h" #if defined(USE_AURA) #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/views/widget/desktop_aura/desktop_screen.h" #include "ui/wm/core/wm_state.h" #endif #if BUILDFLAG(IS_LINUX) #include "base/environment.h" #include "base/threading/thread_task_runner_handle.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h" #include "electron/electron_gtk_stubs.h" #include "ui/base/cursor/cursor_factory.h" #include "ui/base/ime/linux/linux_input_method_context_factory.h" #include "ui/gfx/color_utils.h" #include "ui/gtk/gtk_compat.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #include "ui/linux/linux_ui.h" #include "ui/linux/linux_ui_factory.h" #include "ui/ozone/public/ozone_platform.h" #endif #if BUILDFLAG(IS_WIN) #include "base/win/dark_mode_support.h" #include "ui/base/l10n/l10n_util_win.h" #include "ui/display/win/dpi.h" #include "ui/gfx/system_fonts_win.h" #include "ui/strings/grit/app_locale_settings.h" #endif #if BUILDFLAG(IS_MAC) #include "services/device/public/cpp/geolocation/geolocation_manager.h" #include "shell/browser/ui/cocoa/views_delegate_mac.h" #else #include "shell/browser/ui/views/electron_views_delegate.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck #endif namespace electron { namespace { template <typename T> void Erase(T* container, typename T::iterator iter) { container->erase(iter); } #if BUILDFLAG(IS_WIN) // gfx::Font callbacks void AdjustUIFont(gfx::win::FontAdjustment* font_adjustment) { l10n_util::NeedOverrideDefaultUIFont(&font_adjustment->font_family_override, &font_adjustment->font_scale); font_adjustment->font_scale *= display::win::GetAccessibilityFontScale(); } int GetMinimumFontSize() { int min_font_size; base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE), &min_font_size); return min_font_size; } #endif std::u16string MediaStringProvider(media::MessageId id) { switch (id) { case media::DEFAULT_AUDIO_DEVICE_NAME: return u"Default"; #if BUILDFLAG(IS_WIN) case media::COMMUNICATIONS_AUDIO_DEVICE_NAME: return u"Communications"; #endif default: return std::u16string(); } } #if BUILDFLAG(IS_LINUX) // GTK does not provide a way to check if current theme is dark, so we compare // the text and background luminosity to get a result. // This trick comes from FireFox. void UpdateDarkThemeSetting() { float bg = color_utils::GetRelativeLuminance(gtk::GetBgColor("GtkLabel")); float fg = color_utils::GetRelativeLuminance(gtk::GetFgColor("GtkLabel")); bool is_dark = fg > bg; // Pass it to NativeUi theme, which is used by the nativeTheme module and most // places in Electron. ui::NativeTheme::GetInstanceForNativeUi()->set_use_dark_colors(is_dark); // Pass it to Web Theme, to make "prefers-color-scheme" media query work. ui::NativeTheme::GetInstanceForWeb()->set_use_dark_colors(is_dark); } #endif } // namespace #if BUILDFLAG(IS_LINUX) class DarkThemeObserver : public ui::NativeThemeObserver { public: DarkThemeObserver() = default; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override { UpdateDarkThemeSetting(); } }; #endif // static ElectronBrowserMainParts* ElectronBrowserMainParts::self_ = nullptr; ElectronBrowserMainParts::ElectronBrowserMainParts() : fake_browser_process_(std::make_unique<BrowserProcessImpl>()), browser_(std::make_unique<Browser>()), node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kBrowser)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) { DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts"; self_ = this; } ElectronBrowserMainParts::~ElectronBrowserMainParts() = default; // static ElectronBrowserMainParts* ElectronBrowserMainParts::Get() { DCHECK(self_); return self_; } bool ElectronBrowserMainParts::SetExitCode(int code) { if (!exit_code_) return false; content::BrowserMainLoop::GetInstance()->SetResultCode(code); *exit_code_ = code; return true; } int ElectronBrowserMainParts::GetExitCode() const { return exit_code_.value_or(content::RESULT_CODE_NORMAL_EXIT); } int ElectronBrowserMainParts::PreEarlyInitialization() { field_trial_list_ = std::make_unique<base::FieldTrialList>(nullptr); #if BUILDFLAG(IS_POSIX) HandleSIGCHLD(); #endif #if BUILDFLAG(IS_LINUX) DetectOzonePlatform(); ui::OzonePlatform::PreEarlyInitialization(); #endif #if BUILDFLAG(IS_MAC) screen_ = std::make_unique<display::ScopedNativeScreen>(); #endif return GetExitCode(); } void ElectronBrowserMainParts::PostEarlyInitialization() { // A workaround was previously needed because there was no ThreadTaskRunner // set. If this check is failing we may need to re-add that workaround DCHECK(base::ThreadTaskRunnerHandle::IsSet()); // The ProxyResolverV8 has setup a complete V8 environment, in order to // avoid conflicts we only initialize our V8 environment after that. js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop()); v8::HandleScope scope(js_env_->isolate()); node_bindings_->Initialize(); // Create the global environment. node::Environment* env = node_bindings_->CreateEnvironment( js_env_->context(), js_env_->platform()); node_env_ = std::make_unique<NodeEnvironment>(env); env->set_trace_sync_io(env->options()->trace_sync_io); // We do not want to crash the main process on unhandled rejections. env->options()->unhandled_rejections = "warn"; // Add Electron extended APIs. electron_bindings_->BindTo(js_env_->isolate(), env->process_object()); // Load everything. node_bindings_->LoadEnvironment(env); // Wrap the uv loop with global env. node_bindings_->set_uv_env(env); // We already initialized the feature list in PreEarlyInitialization(), but // the user JS script would not have had a chance to alter the command-line // switches at that point. Lets reinitialize it here to pick up the // command-line changes. base::FeatureList::ClearInstanceForTesting(); InitializeFeatureList(); // Initialize field trials. InitializeFieldTrials(); // Reinitialize logging now that the app has had a chance to set the app name // and/or user data directory. logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(), /* is_preinit = */ false); // Initialize after user script environment creation. fake_browser_process_->PostEarlyInitialization(); } int ElectronBrowserMainParts::PreCreateThreads() { if (!views::LayoutProvider::Get()) layout_provider_ = std::make_unique<views::LayoutProvider>(); auto* command_line = base::CommandLine::ForCurrentProcess(); std::string locale = command_line->GetSwitchValueASCII(::switches::kLang); #if BUILDFLAG(IS_MAC) // The browser process only wants to support the language Cocoa will use, // so force the app locale to be overridden with that value. This must // happen before the ResourceBundle is loaded if (locale.empty()) l10n_util::OverrideLocaleWithCocoaLocale(); #elif BUILDFLAG(IS_LINUX) // l10n_util::GetApplicationLocaleInternal uses g_get_language_names(), // which keys off of getenv("LC_ALL"). // We must set this env first to make ui::ResourceBundle accept the custom // locale. auto env = base::Environment::Create(); absl::optional<std::string> lc_all; if (!locale.empty()) { std::string str; if (env->GetVar("LC_ALL", &str)) lc_all.emplace(std::move(str)); env->SetVar("LC_ALL", locale.c_str()); } #endif // Load resources bundle according to locale. std::string loaded_locale = LoadResourceBundle(locale); #if defined(USE_AURA) // NB: must be called _after_ locale resource bundle is loaded, // because ui lib makes use of it in X11 if (!display::Screen::GetScreen()) { screen_ = views::CreateDesktopScreen(); } #endif // Initialize the app locale. std::string app_locale = l10n_util::GetApplicationLocale(loaded_locale); ElectronBrowserClient::SetApplicationLocale(app_locale); fake_browser_process_->SetApplicationLocale(app_locale); #if BUILDFLAG(IS_LINUX) // Reset to the original LC_ALL since we should not be changing it. if (!locale.empty()) { if (lc_all) env->SetVar("LC_ALL", *lc_all); else env->UnSetVar("LC_ALL"); } #endif // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); #if BUILDFLAG(IS_MAC) ui::InitIdleMonitor(); #endif fake_browser_process_->PreCreateThreads(); // Notify observers. Browser::Get()->PreCreateThreads(); return 0; } void ElectronBrowserMainParts::PostCreateThreads() { content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread)); } void ElectronBrowserMainParts::PostDestroyThreads() { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_browser_client_.reset(); extensions::ExtensionsBrowserClient::Set(nullptr); #endif #if BUILDFLAG(IS_LINUX) device::BluetoothAdapterFactory::Shutdown(); bluez::DBusBluezManagerWrapperLinux::Shutdown(); #endif fake_browser_process_->PostDestroyThreads(); } void ElectronBrowserMainParts::ToolkitInitialized() { #if BUILDFLAG(IS_LINUX) auto linux_ui = ui::CreateLinuxUi(); // Try loading gtk symbols used by Electron. electron::InitializeElectron_gtk(gtk::GetLibGtk()); if (!electron::IsElectron_gtkInitialized()) { electron::UninitializeElectron_gtk(); } electron::InitializeElectron_gdk_pixbuf(gtk::GetLibGdkPixbuf()); CHECK(electron::IsElectron_gdk_pixbufInitialized()) << "Failed to initialize libgdk_pixbuf-2.0.so.0"; // Chromium does not respect GTK dark theme setting, but they may change // in future and this code might be no longer needed. Check the Chromium // issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=998903 UpdateDarkThemeSetting(); // Update the native theme when GTK theme changes. The GetNativeTheme // here returns a NativeThemeGtk, which monitors GTK settings. dark_theme_observer_ = std::make_unique<DarkThemeObserver>(); linux_ui->GetNativeTheme(nullptr)->AddObserver(dark_theme_observer_.get()); ui::LinuxUi::SetInstance(std::move(linux_ui)); // Cursor theme changes are tracked by LinuxUI (via a CursorThemeManager // implementation). Start observing them once it's initialized. ui::CursorFactory::GetInstance()->ObserveThemeChanges(); #endif #if defined(USE_AURA) wm_state_ = std::make_unique<wm::WMState>(); #endif #if BUILDFLAG(IS_WIN) gfx::win::SetAdjustFontCallback(&AdjustUIFont); gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize); #endif #if BUILDFLAG(IS_MAC) views_delegate_ = std::make_unique<ViewsDelegateMac>(); #else views_delegate_ = std::make_unique<ViewsDelegate>(); #endif } int ElectronBrowserMainParts::PreMainMessageLoopRun() { // Run user's main script before most things get initialized, so we can have // a chance to setup everything. node_bindings_->PrepareEmbedThread(); node_bindings_->StartPolling(); // url::Add*Scheme are not threadsafe, this helps prevent data races. url::LockSchemeRegistries(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_client_ = std::make_unique<ElectronExtensionsClient>(); extensions::ExtensionsClient::Set(extensions_client_.get()); // BrowserContextKeyedAPIServiceFactories require an ExtensionsBrowserClient. extensions_browser_client_ = std::make_unique<ElectronExtensionsBrowserClient>(); extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get()); extensions::EnsureBrowserContextKeyedServiceFactoriesBuilt(); extensions::electron::EnsureBrowserContextKeyedServiceFactoriesBuilt(); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckServiceFactory::GetInstance(); #endif #if BUILDFLAG(IS_WIN) // access ui native theme here to prevent blocking calls later base::win::AllowDarkModeForApp(true); #endif content::WebUIControllerFactory::RegisterFactory( ElectronWebUIControllerFactory::GetInstance()); auto* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kRemoteDebuggingPipe)) { // --remote-debugging-pipe auto on_disconnect = base::BindOnce([]() { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce([]() { Browser::Get()->Quit(); })); }); content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler( std::move(on_disconnect)); } else if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) { // --remote-debugging-port DevToolsManagerDelegate::StartHttpHandler(); } #if !BUILDFLAG(IS_MAC) // The corresponding call in macOS is in ElectronApplicationDelegate. Browser::Get()->WillFinishLaunching(); Browser::Get()->DidFinishLaunching(base::Value::Dict()); #endif // Notify observers that main thread message loop was initialized. Browser::Get()->PreMainMessageLoopRun(); return GetExitCode(); } void ElectronBrowserMainParts::WillRunMainMessageLoop( std::unique_ptr<base::RunLoop>& run_loop) { js_env_->OnMessageLoopCreated(); exit_code_ = content::RESULT_CODE_NORMAL_EXIT; Browser::Get()->SetMainMessageLoopQuitClosure( run_loop->QuitWhenIdleClosure()); } void ElectronBrowserMainParts::PostCreateMainMessageLoop() { #if BUILDFLAG(IS_LINUX) auto shutdown_cb = base::BindOnce(base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); ui::OzonePlatform::GetInstance()->PostCreateMainMessageLoop( std::move(shutdown_cb)); bluez::DBusBluezManagerWrapperLinux::Initialize(); // Set up crypt config. This needs to be done before anything starts the // network service, as the raw encryption key needs to be shared with the // network service for encrypted cookie storage. std::string app_name = electron::Browser::Get()->GetName(); const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); std::unique_ptr<os_crypt::Config> config = std::make_unique<os_crypt::Config>(); // Forward to os_crypt the flag to use a specific password store. config->store = command_line.GetSwitchValueASCII(::switches::kPasswordStore); config->product_name = app_name; config->application_name = app_name; config->main_thread_runner = base::ThreadTaskRunnerHandle::Get(); // c.f. // https://source.chromium.org/chromium/chromium/src/+/master:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1 config->should_use_preference = command_line.HasSwitch(::switches::kEnableEncryptionSelection); base::PathService::Get(DIR_SESSION_DATA, &config->user_data_path); OSCrypt::SetConfig(std::move(config)); #endif #if BUILDFLAG(IS_POSIX) // Exit in response to SIGINT, SIGTERM, etc. InstallShutdownSignalHandlers( base::BindOnce(&Browser::Quit, base::Unretained(Browser::Get())), content::GetUIThreadTaskRunner({})); #endif } void ElectronBrowserMainParts::PostMainMessageLoopRun() { #if BUILDFLAG(IS_MAC) FreeAppDelegate(); #endif // Shutdown the DownloadManager before destroying Node to prevent // DownloadItem callbacks from crashing. for (auto& iter : ElectronBrowserContext::browser_context_map()) { auto* download_manager = iter.second.get()->GetDownloadManager(); if (download_manager) { download_manager->Shutdown(); } } // Destroy node platform after all destructors_ are executed, as they may // invoke Node/V8 APIs inside them. node_env_->env()->set_trace_sync_io(false); js_env_->OnMessageLoopDestroying(); node::Stop(node_env_->env()); node_env_.reset(); auto default_context_key = ElectronBrowserContext::PartitionKey("", false); std::unique_ptr<ElectronBrowserContext> default_context = std::move( ElectronBrowserContext::browser_context_map()[default_context_key]); ElectronBrowserContext::browser_context_map().clear(); default_context.reset(); fake_browser_process_->PostMainMessageLoopRun(); content::DevToolsAgentHost::StopRemoteDebuggingPipeHandler(); #if BUILDFLAG(IS_LINUX) ui::OzonePlatform::GetInstance()->PostMainMessageLoopRun(); #endif } #if !BUILDFLAG(IS_MAC) void ElectronBrowserMainParts::PreCreateMainMessageLoop() { PreCreateMainMessageLoopCommon(); } #endif void ElectronBrowserMainParts::PreCreateMainMessageLoopCommon() { #if BUILDFLAG(IS_MAC) InitializeMainNib(); RegisterURLHandler(); #endif media::SetLocalizedStringProvider(MediaStringProvider); #if BUILDFLAG(IS_WIN) auto* local_state = g_browser_process->local_state(); DCHECK(local_state); bool os_crypt_init = OSCrypt::Init(local_state); DCHECK(os_crypt_init); #endif } device::mojom::GeolocationControl* ElectronBrowserMainParts::GetGeolocationControl() { if (!geolocation_control_) { content::GetDeviceService().BindGeolocationControl( geolocation_control_.BindNewPipeAndPassReceiver()); } return geolocation_control_.get(); } #if BUILDFLAG(IS_MAC) device::GeolocationManager* ElectronBrowserMainParts::GetGeolocationManager() { return geolocation_manager_.get(); } #endif IconManager* ElectronBrowserMainParts::GetIconManager() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!icon_manager_.get()) icon_manager_ = std::make_unique<IconManager>(); return icon_manager_.get(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,406
[Bug]: red background on hover to PiP
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.1 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro Version 19044.1706 ### What arch are you using? x64 ### Last Known Working Electron version 18.1.0 ### Expected Behavior when hovering over pip, there is no red background and controls are visible ### Actual Behavior when hovering over pip, there is a red background and no controls are visible ### Testcase Gist URL _No response_ ### Additional Information ![image](https://user-images.githubusercontent.com/11525479/171402617-11d4444d-fe18-4711-b5c5-a0773f9993b1.png)
https://github.com/electron/electron/issues/34406
https://github.com/electron/electron/pull/35034
fc2e6bd0ed86c9e1f26fcf5f973f508474e469ea
9b2b1998b8386aa324ed617ed2cc23df742eb767
2022-06-01T12:18:25Z
c++
2022-08-22T14:38:45Z
chromium_src/BUILD.gn
# Copyright (c) 2018 GitHub, Inc. # Use of this source code is governed by the MIT license that can be # found in the LICENSE file. import("//build/config/ozone.gni") import("//build/config/ui.gni") import("//components/spellcheck/spellcheck_build_features.gni") import("//electron/buildflags/buildflags.gni") import("//printing/buildflags/buildflags.gni") import("//third_party/widevine/cdm/widevine.gni") # Builds some of the chrome sources that Electron depends on. static_library("chrome") { visibility = [ "//electron:electron_lib" ] sources = [ "//chrome/browser/accessibility/accessibility_ui.cc", "//chrome/browser/accessibility/accessibility_ui.h", "//chrome/browser/app_mode/app_mode_utils.cc", "//chrome/browser/app_mode/app_mode_utils.h", "//chrome/browser/browser_features.cc", "//chrome/browser/browser_features.h", "//chrome/browser/browser_process.cc", "//chrome/browser/browser_process.h", "//chrome/browser/devtools/devtools_contents_resizing_strategy.cc", "//chrome/browser/devtools/devtools_contents_resizing_strategy.h", "//chrome/browser/devtools/devtools_embedder_message_dispatcher.cc", "//chrome/browser/devtools/devtools_embedder_message_dispatcher.h", "//chrome/browser/devtools/devtools_eye_dropper.cc", "//chrome/browser/devtools/devtools_eye_dropper.h", "//chrome/browser/devtools/devtools_file_system_indexer.cc", "//chrome/browser/devtools/devtools_file_system_indexer.h", "//chrome/browser/devtools/devtools_settings.h", "//chrome/browser/extensions/global_shortcut_listener.cc", "//chrome/browser/extensions/global_shortcut_listener.h", "//chrome/browser/icon_loader.cc", "//chrome/browser/icon_loader.h", "//chrome/browser/icon_manager.cc", "//chrome/browser/icon_manager.h", "//chrome/browser/net/chrome_mojo_proxy_resolver_factory.cc", "//chrome/browser/net/chrome_mojo_proxy_resolver_factory.h", "//chrome/browser/net/proxy_config_monitor.cc", "//chrome/browser/net/proxy_config_monitor.h", "//chrome/browser/net/proxy_service_factory.cc", "//chrome/browser/net/proxy_service_factory.h", "//chrome/browser/platform_util.cc", "//chrome/browser/platform_util.h", "//chrome/browser/predictors/preconnect_manager.cc", "//chrome/browser/predictors/preconnect_manager.h", "//chrome/browser/predictors/predictors_features.cc", "//chrome/browser/predictors/predictors_features.h", "//chrome/browser/predictors/proxy_lookup_client_impl.cc", "//chrome/browser/predictors/proxy_lookup_client_impl.h", "//chrome/browser/predictors/resolve_host_client_impl.cc", "//chrome/browser/predictors/resolve_host_client_impl.h", "//chrome/browser/process_singleton.h", "//chrome/browser/process_singleton_internal.cc", "//chrome/browser/process_singleton_internal.h", "//chrome/browser/ui/exclusive_access/exclusive_access_bubble_type.cc", "//chrome/browser/ui/exclusive_access/exclusive_access_bubble_type.h", "//chrome/browser/ui/exclusive_access/exclusive_access_controller_base.cc", "//chrome/browser/ui/exclusive_access/exclusive_access_controller_base.h", "//chrome/browser/ui/exclusive_access/exclusive_access_manager.cc", "//chrome/browser/ui/exclusive_access/exclusive_access_manager.h", "//chrome/browser/ui/exclusive_access/fullscreen_controller.cc", "//chrome/browser/ui/exclusive_access/fullscreen_controller.h", "//chrome/browser/ui/exclusive_access/fullscreen_within_tab_helper.cc", "//chrome/browser/ui/exclusive_access/fullscreen_within_tab_helper.h", "//chrome/browser/ui/exclusive_access/keyboard_lock_controller.cc", "//chrome/browser/ui/exclusive_access/keyboard_lock_controller.h", "//chrome/browser/ui/exclusive_access/mouse_lock_controller.cc", "//chrome/browser/ui/exclusive_access/mouse_lock_controller.h", "//chrome/browser/ui/native_window_tracker.h", "//chrome/browser/ui/views/eye_dropper/eye_dropper.cc", "//chrome/browser/ui/views/eye_dropper/eye_dropper.h", "//chrome/browser/ui/views/eye_dropper/eye_dropper_view.cc", "//chrome/browser/ui/views/eye_dropper/eye_dropper_view.h", "//extensions/browser/app_window/size_constraints.cc", "//extensions/browser/app_window/size_constraints.h", ] if (is_posix) { sources += [ "//chrome/browser/process_singleton_posix.cc" ] } if (is_mac) { sources += [ "//chrome/browser/extensions/global_shortcut_listener_mac.h", "//chrome/browser/extensions/global_shortcut_listener_mac.mm", "//chrome/browser/icon_loader_mac.mm", "//chrome/browser/media/webrtc/system_media_capture_permissions_mac.h", "//chrome/browser/media/webrtc/system_media_capture_permissions_mac.mm", "//chrome/browser/media/webrtc/system_media_capture_permissions_stats_mac.h", "//chrome/browser/media/webrtc/system_media_capture_permissions_stats_mac.mm", "//chrome/browser/media/webrtc/window_icon_util_mac.mm", "//chrome/browser/platform_util_mac.mm", "//chrome/browser/process_singleton_mac.mm", "//chrome/browser/ui/views/eye_dropper/eye_dropper_view_mac.h", "//chrome/browser/ui/views/eye_dropper/eye_dropper_view_mac.mm", ] } if (is_win) { sources += [ "//chrome/browser/extensions/global_shortcut_listener_win.cc", "//chrome/browser/extensions/global_shortcut_listener_win.h", "//chrome/browser/icon_loader_win.cc", "//chrome/browser/media/webrtc/window_icon_util_win.cc", "//chrome/browser/process_singleton_win.cc", "//chrome/browser/ui/frame/window_frame_util.h", "//chrome/browser/ui/view_ids.h", "//chrome/browser/win/chrome_process_finder.cc", "//chrome/browser/win/chrome_process_finder.h", "//chrome/browser/win/titlebar_config.h", "//chrome/child/v8_crashpad_support_win.cc", "//chrome/child/v8_crashpad_support_win.h", ] } if (is_linux) { sources += [ "//chrome/browser/media/webrtc/window_icon_util_ozone.cc" ] } if (use_aura) { sources += [ "//chrome/browser/platform_util_aura.cc", "//chrome/browser/ui/aura/native_window_tracker_aura.cc", "//chrome/browser/ui/aura/native_window_tracker_aura.h", "//chrome/browser/ui/views/eye_dropper/eye_dropper_view_aura.cc", ] } public_deps = [ "//chrome/browser:dev_ui_browser_resources", "//chrome/common", "//chrome/common:version_header", "//components/keyed_service/content", "//components/paint_preview/buildflags", "//components/proxy_config", "//components/services/language_detection/public/mojom", "//content/public/browser", "//services/strings", ] deps = [ "//chrome/browser:resource_prefetch_predictor_proto", "//components/optimization_guide/proto:optimization_guide_proto", ] if (is_linux) { sources += [ "//chrome/browser/icon_loader_auralinux.cc" ] if (use_ozone) { deps += [ "//ui/ozone" ] sources += [ "//chrome/browser/extensions/global_shortcut_listener_ozone.cc", "//chrome/browser/extensions/global_shortcut_listener_ozone.h", ] } sources += [ "//chrome/browser/ui/views/status_icons/concat_menu_model.cc", "//chrome/browser/ui/views/status_icons/concat_menu_model.h", "//chrome/browser/ui/views/status_icons/status_icon_linux_dbus.cc", "//chrome/browser/ui/views/status_icons/status_icon_linux_dbus.h", ] public_deps += [ "//components/dbus/menu", "//components/dbus/thread_linux", ] } if (is_win) { sources += [ "//chrome/browser/win/icon_reader_service.cc", "//chrome/browser/win/icon_reader_service.h", ] public_deps += [ "//chrome/services/util_win:lib" ] } if (enable_desktop_capturer) { sources += [ "//chrome/browser/media/webrtc/desktop_media_list.cc", "//chrome/browser/media/webrtc/desktop_media_list.h", "//chrome/browser/media/webrtc/desktop_media_list_base.cc", "//chrome/browser/media/webrtc/desktop_media_list_base.h", "//chrome/browser/media/webrtc/desktop_media_list_observer.h", "//chrome/browser/media/webrtc/native_desktop_media_list.cc", "//chrome/browser/media/webrtc/native_desktop_media_list.h", "//chrome/browser/media/webrtc/window_icon_util.h", ] deps += [ "//ui/snapshot" ] } if (enable_widevine) { sources += [ "//chrome/renderer/media/chrome_key_systems.cc", "//chrome/renderer/media/chrome_key_systems.h", "//chrome/renderer/media/chrome_key_systems_provider.cc", "//chrome/renderer/media/chrome_key_systems_provider.h", ] deps += [ "//components/cdm/renderer" ] } if (enable_basic_printing) { sources += [ "//chrome/browser/bad_message.cc", "//chrome/browser/bad_message.h", "//chrome/browser/printing/print_job.cc", "//chrome/browser/printing/print_job.h", "//chrome/browser/printing/print_job_manager.cc", "//chrome/browser/printing/print_job_manager.h", "//chrome/browser/printing/print_job_worker.cc", "//chrome/browser/printing/print_job_worker.h", "//chrome/browser/printing/print_job_worker_oop.cc", "//chrome/browser/printing/print_job_worker_oop.h", "//chrome/browser/printing/print_view_manager_base.cc", "//chrome/browser/printing/print_view_manager_base.h", "//chrome/browser/printing/printer_query.cc", "//chrome/browser/printing/printer_query.h", "//chrome/browser/printing/printing_service.cc", "//chrome/browser/printing/printing_service.h", "//components/printing/browser/print_to_pdf/pdf_print_utils.cc", "//components/printing/browser/print_to_pdf/pdf_print_utils.h", ] if (enable_oop_printing) { sources += [ "//chrome/browser/printing/print_backend_service_manager.cc", "//chrome/browser/printing/print_backend_service_manager.h", ] } public_deps += [ "//chrome/services/printing:lib", "//components/printing/browser", "//components/printing/renderer", "//components/services/print_compositor", "//components/services/print_compositor/public/cpp", "//components/services/print_compositor/public/mojom", "//printing/backend", ] deps += [ "//components/printing/common", "//printing", ] if (is_win) { sources += [ "//chrome/browser/printing/pdf_to_emf_converter.cc", "//chrome/browser/printing/pdf_to_emf_converter.h", ] } } if (enable_picture_in_picture) { sources += [ "//chrome/browser/picture_in_picture/picture_in_picture_window_manager.cc", "//chrome/browser/picture_in_picture/picture_in_picture_window_manager.h", "//chrome/browser/ui/views/overlay/back_to_tab_image_button.cc", "//chrome/browser/ui/views/overlay/back_to_tab_image_button.h", "//chrome/browser/ui/views/overlay/back_to_tab_label_button.cc", "//chrome/browser/ui/views/overlay/close_image_button.cc", "//chrome/browser/ui/views/overlay/close_image_button.h", "//chrome/browser/ui/views/overlay/constants.h", "//chrome/browser/ui/views/overlay/document_overlay_window_views.cc", "//chrome/browser/ui/views/overlay/document_overlay_window_views.h", "//chrome/browser/ui/views/overlay/hang_up_button.cc", "//chrome/browser/ui/views/overlay/hang_up_button.h", "//chrome/browser/ui/views/overlay/overlay_window_image_button.cc", "//chrome/browser/ui/views/overlay/overlay_window_image_button.h", "//chrome/browser/ui/views/overlay/overlay_window_views.cc", "//chrome/browser/ui/views/overlay/overlay_window_views.h", "//chrome/browser/ui/views/overlay/playback_image_button.cc", "//chrome/browser/ui/views/overlay/playback_image_button.h", "//chrome/browser/ui/views/overlay/resize_handle_button.cc", "//chrome/browser/ui/views/overlay/resize_handle_button.h", "//chrome/browser/ui/views/overlay/skip_ad_label_button.cc", "//chrome/browser/ui/views/overlay/skip_ad_label_button.h", "//chrome/browser/ui/views/overlay/toggle_camera_button.cc", "//chrome/browser/ui/views/overlay/toggle_camera_button.h", "//chrome/browser/ui/views/overlay/toggle_microphone_button.cc", "//chrome/browser/ui/views/overlay/toggle_microphone_button.h", "//chrome/browser/ui/views/overlay/track_image_button.cc", "//chrome/browser/ui/views/overlay/track_image_button.h", "//chrome/browser/ui/views/overlay/video_overlay_window_views.cc", "//chrome/browser/ui/views/overlay/video_overlay_window_views.h", ] deps += [ "//chrome/app/vector_icons", "//components/vector_icons:vector_icons", "//ui/views/controls/webview", ] } if (enable_electron_extensions) { sources += [ "//chrome/browser/extensions/chrome_url_request_util.cc", "//chrome/browser/extensions/chrome_url_request_util.h", "//chrome/browser/plugins/plugin_response_interceptor_url_loader_throttle.cc", "//chrome/browser/plugins/plugin_response_interceptor_url_loader_throttle.h", "//chrome/renderer/extensions/extension_hooks_delegate.cc", "//chrome/renderer/extensions/extension_hooks_delegate.h", "//chrome/renderer/extensions/tabs_hooks_delegate.cc", "//chrome/renderer/extensions/tabs_hooks_delegate.h", ] if (enable_pdf_viewer) { sources += [ "//chrome/browser/pdf/chrome_pdf_stream_delegate.cc", "//chrome/browser/pdf/chrome_pdf_stream_delegate.h", "//chrome/browser/pdf/pdf_extension_util.cc", "//chrome/browser/pdf/pdf_extension_util.h", "//chrome/browser/pdf/pdf_frame_util.cc", "//chrome/browser/pdf/pdf_frame_util.h", "//chrome/browser/plugins/pdf_iframe_navigation_throttle.cc", "//chrome/browser/plugins/pdf_iframe_navigation_throttle.h", ] deps += [ "//components/pdf/browser", "//components/pdf/renderer", ] } } if (!is_mas_build) { sources += [ "//chrome/browser/hang_monitor/hang_crash_dump.h" ] if (is_mac) { sources += [ "//chrome/browser/hang_monitor/hang_crash_dump_mac.cc" ] } else if (is_win) { sources += [ "//chrome/browser/hang_monitor/hang_crash_dump_win.cc" ] } else { sources += [ "//chrome/browser/hang_monitor/hang_crash_dump.cc" ] } } } source_set("plugins") { sources = [] deps = [] frameworks = [] # browser side sources += [ "//chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.cc", "//chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h", "//chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc", "//chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.h", ] # renderer side sources += [ "//chrome/renderer/pepper/chrome_renderer_pepper_host_factory.cc", "//chrome/renderer/pepper/chrome_renderer_pepper_host_factory.h", "//chrome/renderer/pepper/pepper_shared_memory_message_filter.cc", "//chrome/renderer/pepper/pepper_shared_memory_message_filter.h", ] deps += [ "//components/strings", "//media:media_buildflags", "//ppapi/buildflags", "//ppapi/host", "//ppapi/proxy", "//ppapi/proxy:ipc", "//ppapi/shared_impl", "//services/device/public/mojom", "//skia", "//storage/browser", ] } # This source set is just so we don't have to depend on all of //chrome/browser # You may have to add new files here during the upgrade if //chrome/browser/spellchecker # gets more files source_set("chrome_spellchecker") { sources = [] deps = [] libs = [] public_deps = [] if (enable_builtin_spellchecker) { sources += [ "//chrome/browser/spellchecker/spell_check_host_chrome_impl.cc", "//chrome/browser/spellchecker/spell_check_host_chrome_impl.h", "//chrome/browser/spellchecker/spellcheck_custom_dictionary.cc", "//chrome/browser/spellchecker/spellcheck_custom_dictionary.h", "//chrome/browser/spellchecker/spellcheck_factory.cc", "//chrome/browser/spellchecker/spellcheck_factory.h", "//chrome/browser/spellchecker/spellcheck_hunspell_dictionary.cc", "//chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h", "//chrome/browser/spellchecker/spellcheck_service.cc", "//chrome/browser/spellchecker/spellcheck_service.h", ] if (!is_mac) { sources += [ "//chrome/browser/spellchecker/spellcheck_language_blocklist_policy_handler.cc", "//chrome/browser/spellchecker/spellcheck_language_blocklist_policy_handler.h", "//chrome/browser/spellchecker/spellcheck_language_policy_handler.cc", "//chrome/browser/spellchecker/spellcheck_language_policy_handler.h", ] } if (has_spellcheck_panel) { sources += [ "//chrome/browser/spellchecker/spell_check_panel_host_impl.cc", "//chrome/browser/spellchecker/spell_check_panel_host_impl.h", ] } if (use_browser_spellchecker) { sources += [ "//chrome/browser/spellchecker/spelling_request.cc", "//chrome/browser/spellchecker/spelling_request.h", ] } deps += [ "//base:base_static", "//components/language/core/browser", "//components/spellcheck:buildflags", "//components/sync", ] public_deps += [ "//chrome/common:constants" ] } public_deps += [ "//components/spellcheck/browser", "//components/spellcheck/common", "//components/spellcheck/renderer", ] }
closed
electron/electron
https://github.com/electron/electron
34,406
[Bug]: red background on hover to PiP
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.1 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro Version 19044.1706 ### What arch are you using? x64 ### Last Known Working Electron version 18.1.0 ### Expected Behavior when hovering over pip, there is no red background and controls are visible ### Actual Behavior when hovering over pip, there is a red background and no controls are visible ### Testcase Gist URL _No response_ ### Additional Information ![image](https://user-images.githubusercontent.com/11525479/171402617-11d4444d-fe18-4711-b5c5-a0773f9993b1.png)
https://github.com/electron/electron/issues/34406
https://github.com/electron/electron/pull/35034
fc2e6bd0ed86c9e1f26fcf5f973f508474e469ea
9b2b1998b8386aa324ed617ed2cc23df742eb767
2022-06-01T12:18:25Z
c++
2022-08-22T14:38:45Z
shell/browser/electron_browser_main_parts.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_main_parts.h" #include <memory> #include <string> #include <utility> #include "base/base_switches.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/metrics/field_trial.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/icon_manager.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "components/os_crypt/key_storage_config_linux.h" #include "components/os_crypt/os_crypt.h" #include "content/browser/browser_main_loop.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/device_service.h" #include "content/public/browser/first_party_sets_handler.h" #include "content/public/browser/web_ui_controller_factory.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/result_codes.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "media/base/localized_strings.h" #include "services/network/public/cpp/features.h" #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" #include "shell/app/electron_main_delegate.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/browser.h" #include "shell/browser/browser_process_impl.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_web_ui_controller_factory.h" #include "shell/browser/feature_list.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" #include "shell/browser/ui/devtools_manager_delegate.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_helper/trackable_object.h" #include "shell/common/logging.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/idle/idle.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_switches.h" #if defined(USE_AURA) #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/views/widget/desktop_aura/desktop_screen.h" #include "ui/wm/core/wm_state.h" #endif #if BUILDFLAG(IS_LINUX) #include "base/environment.h" #include "base/threading/thread_task_runner_handle.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h" #include "electron/electron_gtk_stubs.h" #include "ui/base/cursor/cursor_factory.h" #include "ui/base/ime/linux/linux_input_method_context_factory.h" #include "ui/gfx/color_utils.h" #include "ui/gtk/gtk_compat.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #include "ui/linux/linux_ui.h" #include "ui/linux/linux_ui_factory.h" #include "ui/ozone/public/ozone_platform.h" #endif #if BUILDFLAG(IS_WIN) #include "base/win/dark_mode_support.h" #include "ui/base/l10n/l10n_util_win.h" #include "ui/display/win/dpi.h" #include "ui/gfx/system_fonts_win.h" #include "ui/strings/grit/app_locale_settings.h" #endif #if BUILDFLAG(IS_MAC) #include "services/device/public/cpp/geolocation/geolocation_manager.h" #include "shell/browser/ui/cocoa/views_delegate_mac.h" #else #include "shell/browser/ui/views/electron_views_delegate.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck #endif namespace electron { namespace { template <typename T> void Erase(T* container, typename T::iterator iter) { container->erase(iter); } #if BUILDFLAG(IS_WIN) // gfx::Font callbacks void AdjustUIFont(gfx::win::FontAdjustment* font_adjustment) { l10n_util::NeedOverrideDefaultUIFont(&font_adjustment->font_family_override, &font_adjustment->font_scale); font_adjustment->font_scale *= display::win::GetAccessibilityFontScale(); } int GetMinimumFontSize() { int min_font_size; base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE), &min_font_size); return min_font_size; } #endif std::u16string MediaStringProvider(media::MessageId id) { switch (id) { case media::DEFAULT_AUDIO_DEVICE_NAME: return u"Default"; #if BUILDFLAG(IS_WIN) case media::COMMUNICATIONS_AUDIO_DEVICE_NAME: return u"Communications"; #endif default: return std::u16string(); } } #if BUILDFLAG(IS_LINUX) // GTK does not provide a way to check if current theme is dark, so we compare // the text and background luminosity to get a result. // This trick comes from FireFox. void UpdateDarkThemeSetting() { float bg = color_utils::GetRelativeLuminance(gtk::GetBgColor("GtkLabel")); float fg = color_utils::GetRelativeLuminance(gtk::GetFgColor("GtkLabel")); bool is_dark = fg > bg; // Pass it to NativeUi theme, which is used by the nativeTheme module and most // places in Electron. ui::NativeTheme::GetInstanceForNativeUi()->set_use_dark_colors(is_dark); // Pass it to Web Theme, to make "prefers-color-scheme" media query work. ui::NativeTheme::GetInstanceForWeb()->set_use_dark_colors(is_dark); } #endif } // namespace #if BUILDFLAG(IS_LINUX) class DarkThemeObserver : public ui::NativeThemeObserver { public: DarkThemeObserver() = default; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override { UpdateDarkThemeSetting(); } }; #endif // static ElectronBrowserMainParts* ElectronBrowserMainParts::self_ = nullptr; ElectronBrowserMainParts::ElectronBrowserMainParts() : fake_browser_process_(std::make_unique<BrowserProcessImpl>()), browser_(std::make_unique<Browser>()), node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kBrowser)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) { DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts"; self_ = this; } ElectronBrowserMainParts::~ElectronBrowserMainParts() = default; // static ElectronBrowserMainParts* ElectronBrowserMainParts::Get() { DCHECK(self_); return self_; } bool ElectronBrowserMainParts::SetExitCode(int code) { if (!exit_code_) return false; content::BrowserMainLoop::GetInstance()->SetResultCode(code); *exit_code_ = code; return true; } int ElectronBrowserMainParts::GetExitCode() const { return exit_code_.value_or(content::RESULT_CODE_NORMAL_EXIT); } int ElectronBrowserMainParts::PreEarlyInitialization() { field_trial_list_ = std::make_unique<base::FieldTrialList>(nullptr); #if BUILDFLAG(IS_POSIX) HandleSIGCHLD(); #endif #if BUILDFLAG(IS_LINUX) DetectOzonePlatform(); ui::OzonePlatform::PreEarlyInitialization(); #endif #if BUILDFLAG(IS_MAC) screen_ = std::make_unique<display::ScopedNativeScreen>(); #endif return GetExitCode(); } void ElectronBrowserMainParts::PostEarlyInitialization() { // A workaround was previously needed because there was no ThreadTaskRunner // set. If this check is failing we may need to re-add that workaround DCHECK(base::ThreadTaskRunnerHandle::IsSet()); // The ProxyResolverV8 has setup a complete V8 environment, in order to // avoid conflicts we only initialize our V8 environment after that. js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop()); v8::HandleScope scope(js_env_->isolate()); node_bindings_->Initialize(); // Create the global environment. node::Environment* env = node_bindings_->CreateEnvironment( js_env_->context(), js_env_->platform()); node_env_ = std::make_unique<NodeEnvironment>(env); env->set_trace_sync_io(env->options()->trace_sync_io); // We do not want to crash the main process on unhandled rejections. env->options()->unhandled_rejections = "warn"; // Add Electron extended APIs. electron_bindings_->BindTo(js_env_->isolate(), env->process_object()); // Load everything. node_bindings_->LoadEnvironment(env); // Wrap the uv loop with global env. node_bindings_->set_uv_env(env); // We already initialized the feature list in PreEarlyInitialization(), but // the user JS script would not have had a chance to alter the command-line // switches at that point. Lets reinitialize it here to pick up the // command-line changes. base::FeatureList::ClearInstanceForTesting(); InitializeFeatureList(); // Initialize field trials. InitializeFieldTrials(); // Reinitialize logging now that the app has had a chance to set the app name // and/or user data directory. logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(), /* is_preinit = */ false); // Initialize after user script environment creation. fake_browser_process_->PostEarlyInitialization(); } int ElectronBrowserMainParts::PreCreateThreads() { if (!views::LayoutProvider::Get()) layout_provider_ = std::make_unique<views::LayoutProvider>(); auto* command_line = base::CommandLine::ForCurrentProcess(); std::string locale = command_line->GetSwitchValueASCII(::switches::kLang); #if BUILDFLAG(IS_MAC) // The browser process only wants to support the language Cocoa will use, // so force the app locale to be overridden with that value. This must // happen before the ResourceBundle is loaded if (locale.empty()) l10n_util::OverrideLocaleWithCocoaLocale(); #elif BUILDFLAG(IS_LINUX) // l10n_util::GetApplicationLocaleInternal uses g_get_language_names(), // which keys off of getenv("LC_ALL"). // We must set this env first to make ui::ResourceBundle accept the custom // locale. auto env = base::Environment::Create(); absl::optional<std::string> lc_all; if (!locale.empty()) { std::string str; if (env->GetVar("LC_ALL", &str)) lc_all.emplace(std::move(str)); env->SetVar("LC_ALL", locale.c_str()); } #endif // Load resources bundle according to locale. std::string loaded_locale = LoadResourceBundle(locale); #if defined(USE_AURA) // NB: must be called _after_ locale resource bundle is loaded, // because ui lib makes use of it in X11 if (!display::Screen::GetScreen()) { screen_ = views::CreateDesktopScreen(); } #endif // Initialize the app locale. std::string app_locale = l10n_util::GetApplicationLocale(loaded_locale); ElectronBrowserClient::SetApplicationLocale(app_locale); fake_browser_process_->SetApplicationLocale(app_locale); #if BUILDFLAG(IS_LINUX) // Reset to the original LC_ALL since we should not be changing it. if (!locale.empty()) { if (lc_all) env->SetVar("LC_ALL", *lc_all); else env->UnSetVar("LC_ALL"); } #endif // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); #if BUILDFLAG(IS_MAC) ui::InitIdleMonitor(); #endif fake_browser_process_->PreCreateThreads(); // Notify observers. Browser::Get()->PreCreateThreads(); return 0; } void ElectronBrowserMainParts::PostCreateThreads() { content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread)); } void ElectronBrowserMainParts::PostDestroyThreads() { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_browser_client_.reset(); extensions::ExtensionsBrowserClient::Set(nullptr); #endif #if BUILDFLAG(IS_LINUX) device::BluetoothAdapterFactory::Shutdown(); bluez::DBusBluezManagerWrapperLinux::Shutdown(); #endif fake_browser_process_->PostDestroyThreads(); } void ElectronBrowserMainParts::ToolkitInitialized() { #if BUILDFLAG(IS_LINUX) auto linux_ui = ui::CreateLinuxUi(); // Try loading gtk symbols used by Electron. electron::InitializeElectron_gtk(gtk::GetLibGtk()); if (!electron::IsElectron_gtkInitialized()) { electron::UninitializeElectron_gtk(); } electron::InitializeElectron_gdk_pixbuf(gtk::GetLibGdkPixbuf()); CHECK(electron::IsElectron_gdk_pixbufInitialized()) << "Failed to initialize libgdk_pixbuf-2.0.so.0"; // Chromium does not respect GTK dark theme setting, but they may change // in future and this code might be no longer needed. Check the Chromium // issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=998903 UpdateDarkThemeSetting(); // Update the native theme when GTK theme changes. The GetNativeTheme // here returns a NativeThemeGtk, which monitors GTK settings. dark_theme_observer_ = std::make_unique<DarkThemeObserver>(); linux_ui->GetNativeTheme(nullptr)->AddObserver(dark_theme_observer_.get()); ui::LinuxUi::SetInstance(std::move(linux_ui)); // Cursor theme changes are tracked by LinuxUI (via a CursorThemeManager // implementation). Start observing them once it's initialized. ui::CursorFactory::GetInstance()->ObserveThemeChanges(); #endif #if defined(USE_AURA) wm_state_ = std::make_unique<wm::WMState>(); #endif #if BUILDFLAG(IS_WIN) gfx::win::SetAdjustFontCallback(&AdjustUIFont); gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize); #endif #if BUILDFLAG(IS_MAC) views_delegate_ = std::make_unique<ViewsDelegateMac>(); #else views_delegate_ = std::make_unique<ViewsDelegate>(); #endif } int ElectronBrowserMainParts::PreMainMessageLoopRun() { // Run user's main script before most things get initialized, so we can have // a chance to setup everything. node_bindings_->PrepareEmbedThread(); node_bindings_->StartPolling(); // url::Add*Scheme are not threadsafe, this helps prevent data races. url::LockSchemeRegistries(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_client_ = std::make_unique<ElectronExtensionsClient>(); extensions::ExtensionsClient::Set(extensions_client_.get()); // BrowserContextKeyedAPIServiceFactories require an ExtensionsBrowserClient. extensions_browser_client_ = std::make_unique<ElectronExtensionsBrowserClient>(); extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get()); extensions::EnsureBrowserContextKeyedServiceFactoriesBuilt(); extensions::electron::EnsureBrowserContextKeyedServiceFactoriesBuilt(); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckServiceFactory::GetInstance(); #endif #if BUILDFLAG(IS_WIN) // access ui native theme here to prevent blocking calls later base::win::AllowDarkModeForApp(true); #endif content::WebUIControllerFactory::RegisterFactory( ElectronWebUIControllerFactory::GetInstance()); auto* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kRemoteDebuggingPipe)) { // --remote-debugging-pipe auto on_disconnect = base::BindOnce([]() { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce([]() { Browser::Get()->Quit(); })); }); content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler( std::move(on_disconnect)); } else if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) { // --remote-debugging-port DevToolsManagerDelegate::StartHttpHandler(); } #if !BUILDFLAG(IS_MAC) // The corresponding call in macOS is in ElectronApplicationDelegate. Browser::Get()->WillFinishLaunching(); Browser::Get()->DidFinishLaunching(base::Value::Dict()); #endif // Notify observers that main thread message loop was initialized. Browser::Get()->PreMainMessageLoopRun(); return GetExitCode(); } void ElectronBrowserMainParts::WillRunMainMessageLoop( std::unique_ptr<base::RunLoop>& run_loop) { js_env_->OnMessageLoopCreated(); exit_code_ = content::RESULT_CODE_NORMAL_EXIT; Browser::Get()->SetMainMessageLoopQuitClosure( run_loop->QuitWhenIdleClosure()); } void ElectronBrowserMainParts::PostCreateMainMessageLoop() { #if BUILDFLAG(IS_LINUX) auto shutdown_cb = base::BindOnce(base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); ui::OzonePlatform::GetInstance()->PostCreateMainMessageLoop( std::move(shutdown_cb)); bluez::DBusBluezManagerWrapperLinux::Initialize(); // Set up crypt config. This needs to be done before anything starts the // network service, as the raw encryption key needs to be shared with the // network service for encrypted cookie storage. std::string app_name = electron::Browser::Get()->GetName(); const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); std::unique_ptr<os_crypt::Config> config = std::make_unique<os_crypt::Config>(); // Forward to os_crypt the flag to use a specific password store. config->store = command_line.GetSwitchValueASCII(::switches::kPasswordStore); config->product_name = app_name; config->application_name = app_name; config->main_thread_runner = base::ThreadTaskRunnerHandle::Get(); // c.f. // https://source.chromium.org/chromium/chromium/src/+/master:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1 config->should_use_preference = command_line.HasSwitch(::switches::kEnableEncryptionSelection); base::PathService::Get(DIR_SESSION_DATA, &config->user_data_path); OSCrypt::SetConfig(std::move(config)); #endif #if BUILDFLAG(IS_POSIX) // Exit in response to SIGINT, SIGTERM, etc. InstallShutdownSignalHandlers( base::BindOnce(&Browser::Quit, base::Unretained(Browser::Get())), content::GetUIThreadTaskRunner({})); #endif } void ElectronBrowserMainParts::PostMainMessageLoopRun() { #if BUILDFLAG(IS_MAC) FreeAppDelegate(); #endif // Shutdown the DownloadManager before destroying Node to prevent // DownloadItem callbacks from crashing. for (auto& iter : ElectronBrowserContext::browser_context_map()) { auto* download_manager = iter.second.get()->GetDownloadManager(); if (download_manager) { download_manager->Shutdown(); } } // Destroy node platform after all destructors_ are executed, as they may // invoke Node/V8 APIs inside them. node_env_->env()->set_trace_sync_io(false); js_env_->OnMessageLoopDestroying(); node::Stop(node_env_->env()); node_env_.reset(); auto default_context_key = ElectronBrowserContext::PartitionKey("", false); std::unique_ptr<ElectronBrowserContext> default_context = std::move( ElectronBrowserContext::browser_context_map()[default_context_key]); ElectronBrowserContext::browser_context_map().clear(); default_context.reset(); fake_browser_process_->PostMainMessageLoopRun(); content::DevToolsAgentHost::StopRemoteDebuggingPipeHandler(); #if BUILDFLAG(IS_LINUX) ui::OzonePlatform::GetInstance()->PostMainMessageLoopRun(); #endif } #if !BUILDFLAG(IS_MAC) void ElectronBrowserMainParts::PreCreateMainMessageLoop() { PreCreateMainMessageLoopCommon(); } #endif void ElectronBrowserMainParts::PreCreateMainMessageLoopCommon() { #if BUILDFLAG(IS_MAC) InitializeMainNib(); RegisterURLHandler(); #endif media::SetLocalizedStringProvider(MediaStringProvider); #if BUILDFLAG(IS_WIN) auto* local_state = g_browser_process->local_state(); DCHECK(local_state); bool os_crypt_init = OSCrypt::Init(local_state); DCHECK(os_crypt_init); #endif } device::mojom::GeolocationControl* ElectronBrowserMainParts::GetGeolocationControl() { if (!geolocation_control_) { content::GetDeviceService().BindGeolocationControl( geolocation_control_.BindNewPipeAndPassReceiver()); } return geolocation_control_.get(); } #if BUILDFLAG(IS_MAC) device::GeolocationManager* ElectronBrowserMainParts::GetGeolocationManager() { return geolocation_manager_.get(); } #endif IconManager* ElectronBrowserMainParts::GetIconManager() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!icon_manager_.get()) icon_manager_ = std::make_unique<IconManager>(); return icon_manager_.get(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,223
[Bug]: 'restore' event not emitted after minimize and maximize application
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.1 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 21H1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Event 'restore' should notify to application ### Actual Behavior After clicking maximize application, the event 'restore' does not notify after minimize ` BrowserWindow.on( 'restore', () => { // nothing happend }); ` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/35223
https://github.com/electron/electron/pull/35342
0ff6508f5bffd84829749c97c7346fc2fc776563
3ce35f224efa3a6e9bfc9b642816961b8691491b
2022-08-04T11:04:47Z
c++
2022-08-23T01:32:42Z
shell/browser/native_window_views_win.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 <dwmapi.h> #include <shellapi.h> #include <wrl/client.h> #include "base/win/atl.h" // Must be before UIAutomationCore.h #include "content/public/browser/browser_accessibility_state.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/common/electron_constants.h" #include "ui/display/display.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/resize_utils.h" #include "ui/views/widget/native_widget_private.h" // Must be included after other Windows headers. #include <UIAutomationClient.h> #include <UIAutomationCoreApi.h> namespace electron { namespace { // Convert Win32 WM_APPCOMMANDS to strings. const char* AppCommandToString(int command_id) { switch (command_id) { case APPCOMMAND_BROWSER_BACKWARD: return kBrowserBackward; case APPCOMMAND_BROWSER_FORWARD: return kBrowserForward; case APPCOMMAND_BROWSER_REFRESH: return "browser-refresh"; case APPCOMMAND_BROWSER_STOP: return "browser-stop"; case APPCOMMAND_BROWSER_SEARCH: return "browser-search"; case APPCOMMAND_BROWSER_FAVORITES: return "browser-favorites"; case APPCOMMAND_BROWSER_HOME: return "browser-home"; case APPCOMMAND_VOLUME_MUTE: return "volume-mute"; case APPCOMMAND_VOLUME_DOWN: return "volume-down"; case APPCOMMAND_VOLUME_UP: return "volume-up"; case APPCOMMAND_MEDIA_NEXTTRACK: return "media-nexttrack"; case APPCOMMAND_MEDIA_PREVIOUSTRACK: return "media-previoustrack"; case APPCOMMAND_MEDIA_STOP: return "media-stop"; case APPCOMMAND_MEDIA_PLAY_PAUSE: return "media-play-pause"; case APPCOMMAND_LAUNCH_MAIL: return "launch-mail"; case APPCOMMAND_LAUNCH_MEDIA_SELECT: return "launch-media-select"; case APPCOMMAND_LAUNCH_APP1: return "launch-app1"; case APPCOMMAND_LAUNCH_APP2: return "launch-app2"; case APPCOMMAND_BASS_DOWN: return "bass-down"; case APPCOMMAND_BASS_BOOST: return "bass-boost"; case APPCOMMAND_BASS_UP: return "bass-up"; case APPCOMMAND_TREBLE_DOWN: return "treble-down"; case APPCOMMAND_TREBLE_UP: return "treble-up"; case APPCOMMAND_MICROPHONE_VOLUME_MUTE: return "microphone-volume-mute"; case APPCOMMAND_MICROPHONE_VOLUME_DOWN: return "microphone-volume-down"; case APPCOMMAND_MICROPHONE_VOLUME_UP: return "microphone-volume-up"; case APPCOMMAND_HELP: return "help"; case APPCOMMAND_FIND: return "find"; case APPCOMMAND_NEW: return "new"; case APPCOMMAND_OPEN: return "open"; case APPCOMMAND_CLOSE: return "close"; case APPCOMMAND_SAVE: return "save"; case APPCOMMAND_PRINT: return "print"; case APPCOMMAND_UNDO: return "undo"; case APPCOMMAND_REDO: return "redo"; case APPCOMMAND_COPY: return "copy"; case APPCOMMAND_CUT: return "cut"; case APPCOMMAND_PASTE: return "paste"; case APPCOMMAND_REPLY_TO_MAIL: return "reply-to-mail"; case APPCOMMAND_FORWARD_MAIL: return "forward-mail"; case APPCOMMAND_SEND_MAIL: return "send-mail"; case APPCOMMAND_SPELL_CHECK: return "spell-check"; case APPCOMMAND_MIC_ON_OFF_TOGGLE: return "mic-on-off-toggle"; case APPCOMMAND_CORRECTION_LIST: return "correction-list"; case APPCOMMAND_MEDIA_PLAY: return "media-play"; case APPCOMMAND_MEDIA_PAUSE: return "media-pause"; case APPCOMMAND_MEDIA_RECORD: return "media-record"; case APPCOMMAND_MEDIA_FAST_FORWARD: return "media-fast-forward"; case APPCOMMAND_MEDIA_REWIND: return "media-rewind"; case APPCOMMAND_MEDIA_CHANNEL_UP: return "media-channel-up"; case APPCOMMAND_MEDIA_CHANNEL_DOWN: return "media-channel-down"; case APPCOMMAND_DELETE: return "delete"; case APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE: return "dictate-or-command-control-toggle"; default: return "unknown"; } } // Copied from ui/views/win/hwnd_message_handler.cc gfx::ResizeEdge GetWindowResizeEdge(WPARAM param) { switch (param) { case WMSZ_BOTTOM: return gfx::ResizeEdge::kBottom; case WMSZ_TOP: return gfx::ResizeEdge::kTop; case WMSZ_LEFT: return gfx::ResizeEdge::kLeft; case WMSZ_RIGHT: return gfx::ResizeEdge::kRight; case WMSZ_TOPLEFT: return gfx::ResizeEdge::kTopLeft; case WMSZ_TOPRIGHT: return gfx::ResizeEdge::kTopRight; case WMSZ_BOTTOMLEFT: return gfx::ResizeEdge::kBottomLeft; case WMSZ_BOTTOMRIGHT: return gfx::ResizeEdge::kBottomRight; default: return gfx::ResizeEdge::kBottomRight; } } bool IsScreenReaderActive() { UINT screenReader = 0; SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0); return screenReader && UiaClientsAreListening(); } } // namespace std::set<NativeWindowViews*> NativeWindowViews::forwarding_windows_; HHOOK NativeWindowViews::mouse_hook_ = NULL; void NativeWindowViews::Maximize() { // Only use Maximize() when window is NOT transparent style if (!transparent()) { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } else { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); SetBounds(display.work_area(), false); NotifyWindowMaximize(); } } bool NativeWindowViews::ExecuteWindowsCommand(int command_id) { std::string command = AppCommandToString(command_id); NotifyWindowExecuteAppCommand(command); return false; } bool NativeWindowViews::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { NotifyWindowMessage(message, w_param, l_param); // Avoid side effects when calling SetWindowPlacement. if (is_setting_window_placement_) { // Let Chromium handle the WM_NCCALCSIZE message otherwise the window size // would be wrong. // See https://github.com/electron/electron/issues/22393 for more. if (message == WM_NCCALCSIZE) return false; // Otherwise handle the message with default proc, *result = DefWindowProc(GetAcceleratedWidget(), message, w_param, l_param); // and tell Chromium to ignore this message. return true; } switch (message) { // Screen readers send WM_GETOBJECT in order to get the accessibility // object, so take this opportunity to push Chromium into accessible // mode if it isn't already, always say we didn't handle the message // because we still want Chromium to handle returning the actual // accessibility object. case WM_GETOBJECT: { if (checked_for_a11y_support_) return false; const DWORD obj_id = static_cast<DWORD>(l_param); if (obj_id != static_cast<DWORD>(OBJID_CLIENT)) { return false; } if (!IsScreenReaderActive()) { return false; } checked_for_a11y_support_ = true; auto* const axState = content::BrowserAccessibilityState::GetInstance(); if (axState && !axState->IsAccessibleBrowser()) { axState->OnScreenReaderDetected(); Browser::Get()->OnAccessibilitySupportChanged(); } return false; } case WM_GETMINMAXINFO: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); // We do this to work around a Windows bug, where the minimized Window // would report that the closest display to it is not the one that it was // previously on (but the leftmost one instead). We restore the position // of the window during the restore operation, this way chromium can // use the proper display to calculate the scale factor to use. if (!last_normal_placement_bounds_.IsEmpty() && (IsVisible() || IsMinimized()) && GetWindowPlacement(GetAcceleratedWidget(), &wp)) { wp.rcNormalPosition = last_normal_placement_bounds_.ToRECT(); // When calling SetWindowPlacement, Chromium would do window messages // handling. But since we are already in PreHandleMSG this would cause // crash in Chromium under some cases. // // We work around the crash by prevent Chromium from handling window // messages until the SetWindowPlacement call is done. // // See https://github.com/electron/electron/issues/21614 for more. is_setting_window_placement_ = true; SetWindowPlacement(GetAcceleratedWidget(), &wp); is_setting_window_placement_ = false; last_normal_placement_bounds_ = gfx::Rect(); } return false; } case WM_COMMAND: // Handle thumbar button click message. if (HIWORD(w_param) == THBN_CLICKED) return taskbar_host_.HandleThumbarButtonEvent(LOWORD(w_param)); return false; case WM_SIZING: { is_resizing_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillResize(dpi_bounds, GetWindowResizeEdge(w_param), &prevent_default); if (prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); pending_bounds_change_.reset(); return true; // Tells Windows that the Sizing is handled. } return false; } case WM_SIZE: { // Handle window state change. HandleSizeEvent(w_param, l_param); return false; } case WM_EXITSIZEMOVE: { if (is_resizing_) { NotifyWindowResized(); is_resizing_ = false; } if (is_moving_) { NotifyWindowMoved(); is_moving_ = false; } // If the user dragged or moved the window during one or more // calls to window.setBounds(), we want to apply the most recent // one once they are done with the move or resize operation. if (pending_bounds_change_.has_value()) { SetBounds(pending_bounds_change_.value(), false /* animate */); pending_bounds_change_.reset(); } return false; } case WM_MOVING: { is_moving_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillMove(dpi_bounds, &prevent_default); if (!movable_ || prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); pending_bounds_change_.reset(); return true; // Tells Windows that the Move is handled. If not true, // frameless windows can be moved using // -webkit-app-region: drag elements. } return false; } case WM_ENDSESSION: { if (w_param) { NotifyWindowEndSession(); } return false; } case WM_PARENTNOTIFY: { if (LOWORD(w_param) == WM_CREATE) { // Because of reasons regarding legacy drivers and stuff, a window that // matches the client area is created and used internally by Chromium. // This is used when forwarding mouse messages. We only cache the first // occurrence (the webview window) because dev tools also cause this // message to be sent. if (!legacy_window_) { legacy_window_ = reinterpret_cast<HWND>(l_param); } } return false; } case WM_CONTEXTMENU: { bool prevent_default = false; NotifyWindowSystemContextMenu(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param), &prevent_default); return prevent_default; } case WM_SYSCOMMAND: { // Mask is needed to account for double clicking title bar to maximize WPARAM max_mask = 0xFFF0; if (transparent() && ((w_param & max_mask) == SC_MAXIMIZE)) { return true; } return false; } case WM_INITMENU: { // This is handling the scenario where the menu might get triggered by the // user doing "alt + space" resulting in system maximization and restore // being used on transparent windows when that does not work. if (transparent()) { HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); EnableMenuItem(menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); EnableMenuItem(menu, SC_RESTORE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); return true; } return false; } default: { return false; } } } void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) { // Here we handle the WM_SIZE event in order to figure out what is the current // window state and notify the user accordingly. switch (w_param) { case SIZE_MAXIMIZED: case SIZE_MINIMIZED: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); if (GetWindowPlacement(GetAcceleratedWidget(), &wp)) { last_normal_placement_bounds_ = gfx::Rect(wp.rcNormalPosition); } // Note that SIZE_MAXIMIZED and SIZE_MINIMIZED might be emitted for // multiple times for one resize because of the SetWindowPlacement call. if (w_param == SIZE_MAXIMIZED && last_window_state_ != ui::SHOW_STATE_MAXIMIZED) { last_window_state_ = ui::SHOW_STATE_MAXIMIZED; NotifyWindowMaximize(); ResetWindowControls(); } else if (w_param == SIZE_MINIMIZED && last_window_state_ != ui::SHOW_STATE_MINIMIZED) { last_window_state_ = ui::SHOW_STATE_MINIMIZED; NotifyWindowMinimize(); } break; } case SIZE_RESTORED: { switch (last_window_state_) { case ui::SHOW_STATE_MAXIMIZED: last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowUnmaximize(); break; case ui::SHOW_STATE_MINIMIZED: if (IsFullscreen()) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowRestore(); } break; default: break; } ResetWindowControls(); break; } } } void NativeWindowViews::ResetWindowControls() { // If a given window was minimized and has since been // unminimized (restored/maximized), ensure the WCO buttons // are reset to their default unpressed state. auto* ncv = widget()->non_client_view(); if (IsWindowControlsOverlayEnabled() && ncv) { auto* frame_view = static_cast<WinFrameView*>(ncv->frame_view()); frame_view->caption_button_container()->ResetWindowControls(); } } void NativeWindowViews::SetForwardMouseMessages(bool forward) { if (forward && !forwarding_mouse_messages_) { forwarding_mouse_messages_ = true; forwarding_windows_.insert(this); // Subclassing is used to fix some issues when forwarding mouse messages; // see comments in |SubclassProc|. SetWindowSubclass(legacy_window_, SubclassProc, 1, reinterpret_cast<DWORD_PTR>(this)); if (!mouse_hook_) { mouse_hook_ = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0); } } else if (!forward && forwarding_mouse_messages_) { forwarding_mouse_messages_ = false; forwarding_windows_.erase(this); RemoveWindowSubclass(legacy_window_, SubclassProc, 1); if (forwarding_windows_.empty()) { UnhookWindowsHookEx(mouse_hook_); mouse_hook_ = NULL; } } } LRESULT CALLBACK NativeWindowViews::SubclassProc(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id, DWORD_PTR ref_data) { auto* window = reinterpret_cast<NativeWindowViews*>(ref_data); switch (msg) { case WM_MOUSELEAVE: { // When input is forwarded to underlying windows, this message is posted. // If not handled, it interferes with Chromium logic, causing for example // mouseleave events to fire. If those events are used to exit forward // mode, excessive flickering on for example hover items in underlying // windows can occur due to rapidly entering and leaving forwarding mode. // By consuming and ignoring the message, we're essentially telling // Chromium that we have not left the window despite somebody else getting // the messages. As to why this is caught for the legacy window and not // the actual browser window is simply that the legacy window somehow // makes use of these events; posting to the main window didn't work. if (window->forwarding_mouse_messages_) { return 0; } break; } } return DefSubclassProc(hwnd, msg, w_param, l_param); } LRESULT CALLBACK NativeWindowViews::MouseHookProc(int n_code, WPARAM w_param, LPARAM l_param) { if (n_code < 0) { return CallNextHookEx(NULL, n_code, w_param, l_param); } // Post a WM_MOUSEMOVE message for those windows whose client area contains // the cursor since they are in a state where they would otherwise ignore all // mouse input. if (w_param == WM_MOUSEMOVE) { for (auto* window : forwarding_windows_) { // At first I considered enumerating windows to check whether the cursor // was directly above the window, but since nothing bad seems to happen // if we post the message even if some other window occludes it I have // just left it as is. RECT client_rect; GetClientRect(window->legacy_window_, &client_rect); POINT p = reinterpret_cast<MSLLHOOKSTRUCT*>(l_param)->pt; ScreenToClient(window->legacy_window_, &p); if (PtInRect(&client_rect, p)) { WPARAM w = 0; // No virtual keys pressed for our purposes LPARAM l = MAKELPARAM(p.x, p.y); PostMessage(window->legacy_window_, WM_MOUSEMOVE, w, l); } } } return CallNextHookEx(NULL, n_code, w_param, l_param); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
28,570
[Bug]: BrowserWindow `restore` event fires late (non-maximized) or not at all (maximized)
### Preflight Checklist I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 12.0.2 ### What operating system are you using? Windows ### Operating System Version Windows 10; 20H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I expect that the restore event fires when restoring a previously maximized window ### Actual Behavior restore event doesn't fire. It only fires for normal state windows ### Testcase Gist URL _No response_ 1. start app 2. maximize window 3. minimize window 4. restore window 5. see that "restored" isn't logged to the console, but is if you skipped step 2 main.js: ``` const {app, BrowserWindow } = require('electron') function createWindow () { const mainWindow = new BrowserWindow(); mainWindow.on("restore", () => { console.log("restored"); }); } app.whenReady().then(() => { createWindow() app.on('activate', function () { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() }) ```
https://github.com/electron/electron/issues/28570
https://github.com/electron/electron/pull/35342
0ff6508f5bffd84829749c97c7346fc2fc776563
3ce35f224efa3a6e9bfc9b642816961b8691491b
2021-04-07T21:03:37Z
c++
2022-08-23T01:32:42Z
shell/browser/native_window_views_win.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 <dwmapi.h> #include <shellapi.h> #include <wrl/client.h> #include "base/win/atl.h" // Must be before UIAutomationCore.h #include "content/public/browser/browser_accessibility_state.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/common/electron_constants.h" #include "ui/display/display.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/resize_utils.h" #include "ui/views/widget/native_widget_private.h" // Must be included after other Windows headers. #include <UIAutomationClient.h> #include <UIAutomationCoreApi.h> namespace electron { namespace { // Convert Win32 WM_APPCOMMANDS to strings. const char* AppCommandToString(int command_id) { switch (command_id) { case APPCOMMAND_BROWSER_BACKWARD: return kBrowserBackward; case APPCOMMAND_BROWSER_FORWARD: return kBrowserForward; case APPCOMMAND_BROWSER_REFRESH: return "browser-refresh"; case APPCOMMAND_BROWSER_STOP: return "browser-stop"; case APPCOMMAND_BROWSER_SEARCH: return "browser-search"; case APPCOMMAND_BROWSER_FAVORITES: return "browser-favorites"; case APPCOMMAND_BROWSER_HOME: return "browser-home"; case APPCOMMAND_VOLUME_MUTE: return "volume-mute"; case APPCOMMAND_VOLUME_DOWN: return "volume-down"; case APPCOMMAND_VOLUME_UP: return "volume-up"; case APPCOMMAND_MEDIA_NEXTTRACK: return "media-nexttrack"; case APPCOMMAND_MEDIA_PREVIOUSTRACK: return "media-previoustrack"; case APPCOMMAND_MEDIA_STOP: return "media-stop"; case APPCOMMAND_MEDIA_PLAY_PAUSE: return "media-play-pause"; case APPCOMMAND_LAUNCH_MAIL: return "launch-mail"; case APPCOMMAND_LAUNCH_MEDIA_SELECT: return "launch-media-select"; case APPCOMMAND_LAUNCH_APP1: return "launch-app1"; case APPCOMMAND_LAUNCH_APP2: return "launch-app2"; case APPCOMMAND_BASS_DOWN: return "bass-down"; case APPCOMMAND_BASS_BOOST: return "bass-boost"; case APPCOMMAND_BASS_UP: return "bass-up"; case APPCOMMAND_TREBLE_DOWN: return "treble-down"; case APPCOMMAND_TREBLE_UP: return "treble-up"; case APPCOMMAND_MICROPHONE_VOLUME_MUTE: return "microphone-volume-mute"; case APPCOMMAND_MICROPHONE_VOLUME_DOWN: return "microphone-volume-down"; case APPCOMMAND_MICROPHONE_VOLUME_UP: return "microphone-volume-up"; case APPCOMMAND_HELP: return "help"; case APPCOMMAND_FIND: return "find"; case APPCOMMAND_NEW: return "new"; case APPCOMMAND_OPEN: return "open"; case APPCOMMAND_CLOSE: return "close"; case APPCOMMAND_SAVE: return "save"; case APPCOMMAND_PRINT: return "print"; case APPCOMMAND_UNDO: return "undo"; case APPCOMMAND_REDO: return "redo"; case APPCOMMAND_COPY: return "copy"; case APPCOMMAND_CUT: return "cut"; case APPCOMMAND_PASTE: return "paste"; case APPCOMMAND_REPLY_TO_MAIL: return "reply-to-mail"; case APPCOMMAND_FORWARD_MAIL: return "forward-mail"; case APPCOMMAND_SEND_MAIL: return "send-mail"; case APPCOMMAND_SPELL_CHECK: return "spell-check"; case APPCOMMAND_MIC_ON_OFF_TOGGLE: return "mic-on-off-toggle"; case APPCOMMAND_CORRECTION_LIST: return "correction-list"; case APPCOMMAND_MEDIA_PLAY: return "media-play"; case APPCOMMAND_MEDIA_PAUSE: return "media-pause"; case APPCOMMAND_MEDIA_RECORD: return "media-record"; case APPCOMMAND_MEDIA_FAST_FORWARD: return "media-fast-forward"; case APPCOMMAND_MEDIA_REWIND: return "media-rewind"; case APPCOMMAND_MEDIA_CHANNEL_UP: return "media-channel-up"; case APPCOMMAND_MEDIA_CHANNEL_DOWN: return "media-channel-down"; case APPCOMMAND_DELETE: return "delete"; case APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE: return "dictate-or-command-control-toggle"; default: return "unknown"; } } // Copied from ui/views/win/hwnd_message_handler.cc gfx::ResizeEdge GetWindowResizeEdge(WPARAM param) { switch (param) { case WMSZ_BOTTOM: return gfx::ResizeEdge::kBottom; case WMSZ_TOP: return gfx::ResizeEdge::kTop; case WMSZ_LEFT: return gfx::ResizeEdge::kLeft; case WMSZ_RIGHT: return gfx::ResizeEdge::kRight; case WMSZ_TOPLEFT: return gfx::ResizeEdge::kTopLeft; case WMSZ_TOPRIGHT: return gfx::ResizeEdge::kTopRight; case WMSZ_BOTTOMLEFT: return gfx::ResizeEdge::kBottomLeft; case WMSZ_BOTTOMRIGHT: return gfx::ResizeEdge::kBottomRight; default: return gfx::ResizeEdge::kBottomRight; } } bool IsScreenReaderActive() { UINT screenReader = 0; SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0); return screenReader && UiaClientsAreListening(); } } // namespace std::set<NativeWindowViews*> NativeWindowViews::forwarding_windows_; HHOOK NativeWindowViews::mouse_hook_ = NULL; void NativeWindowViews::Maximize() { // Only use Maximize() when window is NOT transparent style if (!transparent()) { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } else { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); SetBounds(display.work_area(), false); NotifyWindowMaximize(); } } bool NativeWindowViews::ExecuteWindowsCommand(int command_id) { std::string command = AppCommandToString(command_id); NotifyWindowExecuteAppCommand(command); return false; } bool NativeWindowViews::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { NotifyWindowMessage(message, w_param, l_param); // Avoid side effects when calling SetWindowPlacement. if (is_setting_window_placement_) { // Let Chromium handle the WM_NCCALCSIZE message otherwise the window size // would be wrong. // See https://github.com/electron/electron/issues/22393 for more. if (message == WM_NCCALCSIZE) return false; // Otherwise handle the message with default proc, *result = DefWindowProc(GetAcceleratedWidget(), message, w_param, l_param); // and tell Chromium to ignore this message. return true; } switch (message) { // Screen readers send WM_GETOBJECT in order to get the accessibility // object, so take this opportunity to push Chromium into accessible // mode if it isn't already, always say we didn't handle the message // because we still want Chromium to handle returning the actual // accessibility object. case WM_GETOBJECT: { if (checked_for_a11y_support_) return false; const DWORD obj_id = static_cast<DWORD>(l_param); if (obj_id != static_cast<DWORD>(OBJID_CLIENT)) { return false; } if (!IsScreenReaderActive()) { return false; } checked_for_a11y_support_ = true; auto* const axState = content::BrowserAccessibilityState::GetInstance(); if (axState && !axState->IsAccessibleBrowser()) { axState->OnScreenReaderDetected(); Browser::Get()->OnAccessibilitySupportChanged(); } return false; } case WM_GETMINMAXINFO: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); // We do this to work around a Windows bug, where the minimized Window // would report that the closest display to it is not the one that it was // previously on (but the leftmost one instead). We restore the position // of the window during the restore operation, this way chromium can // use the proper display to calculate the scale factor to use. if (!last_normal_placement_bounds_.IsEmpty() && (IsVisible() || IsMinimized()) && GetWindowPlacement(GetAcceleratedWidget(), &wp)) { wp.rcNormalPosition = last_normal_placement_bounds_.ToRECT(); // When calling SetWindowPlacement, Chromium would do window messages // handling. But since we are already in PreHandleMSG this would cause // crash in Chromium under some cases. // // We work around the crash by prevent Chromium from handling window // messages until the SetWindowPlacement call is done. // // See https://github.com/electron/electron/issues/21614 for more. is_setting_window_placement_ = true; SetWindowPlacement(GetAcceleratedWidget(), &wp); is_setting_window_placement_ = false; last_normal_placement_bounds_ = gfx::Rect(); } return false; } case WM_COMMAND: // Handle thumbar button click message. if (HIWORD(w_param) == THBN_CLICKED) return taskbar_host_.HandleThumbarButtonEvent(LOWORD(w_param)); return false; case WM_SIZING: { is_resizing_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillResize(dpi_bounds, GetWindowResizeEdge(w_param), &prevent_default); if (prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); pending_bounds_change_.reset(); return true; // Tells Windows that the Sizing is handled. } return false; } case WM_SIZE: { // Handle window state change. HandleSizeEvent(w_param, l_param); return false; } case WM_EXITSIZEMOVE: { if (is_resizing_) { NotifyWindowResized(); is_resizing_ = false; } if (is_moving_) { NotifyWindowMoved(); is_moving_ = false; } // If the user dragged or moved the window during one or more // calls to window.setBounds(), we want to apply the most recent // one once they are done with the move or resize operation. if (pending_bounds_change_.has_value()) { SetBounds(pending_bounds_change_.value(), false /* animate */); pending_bounds_change_.reset(); } return false; } case WM_MOVING: { is_moving_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillMove(dpi_bounds, &prevent_default); if (!movable_ || prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); pending_bounds_change_.reset(); return true; // Tells Windows that the Move is handled. If not true, // frameless windows can be moved using // -webkit-app-region: drag elements. } return false; } case WM_ENDSESSION: { if (w_param) { NotifyWindowEndSession(); } return false; } case WM_PARENTNOTIFY: { if (LOWORD(w_param) == WM_CREATE) { // Because of reasons regarding legacy drivers and stuff, a window that // matches the client area is created and used internally by Chromium. // This is used when forwarding mouse messages. We only cache the first // occurrence (the webview window) because dev tools also cause this // message to be sent. if (!legacy_window_) { legacy_window_ = reinterpret_cast<HWND>(l_param); } } return false; } case WM_CONTEXTMENU: { bool prevent_default = false; NotifyWindowSystemContextMenu(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param), &prevent_default); return prevent_default; } case WM_SYSCOMMAND: { // Mask is needed to account for double clicking title bar to maximize WPARAM max_mask = 0xFFF0; if (transparent() && ((w_param & max_mask) == SC_MAXIMIZE)) { return true; } return false; } case WM_INITMENU: { // This is handling the scenario where the menu might get triggered by the // user doing "alt + space" resulting in system maximization and restore // being used on transparent windows when that does not work. if (transparent()) { HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); EnableMenuItem(menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); EnableMenuItem(menu, SC_RESTORE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); return true; } return false; } default: { return false; } } } void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) { // Here we handle the WM_SIZE event in order to figure out what is the current // window state and notify the user accordingly. switch (w_param) { case SIZE_MAXIMIZED: case SIZE_MINIMIZED: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); if (GetWindowPlacement(GetAcceleratedWidget(), &wp)) { last_normal_placement_bounds_ = gfx::Rect(wp.rcNormalPosition); } // Note that SIZE_MAXIMIZED and SIZE_MINIMIZED might be emitted for // multiple times for one resize because of the SetWindowPlacement call. if (w_param == SIZE_MAXIMIZED && last_window_state_ != ui::SHOW_STATE_MAXIMIZED) { last_window_state_ = ui::SHOW_STATE_MAXIMIZED; NotifyWindowMaximize(); ResetWindowControls(); } else if (w_param == SIZE_MINIMIZED && last_window_state_ != ui::SHOW_STATE_MINIMIZED) { last_window_state_ = ui::SHOW_STATE_MINIMIZED; NotifyWindowMinimize(); } break; } case SIZE_RESTORED: { switch (last_window_state_) { case ui::SHOW_STATE_MAXIMIZED: last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowUnmaximize(); break; case ui::SHOW_STATE_MINIMIZED: if (IsFullscreen()) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowRestore(); } break; default: break; } ResetWindowControls(); break; } } } void NativeWindowViews::ResetWindowControls() { // If a given window was minimized and has since been // unminimized (restored/maximized), ensure the WCO buttons // are reset to their default unpressed state. auto* ncv = widget()->non_client_view(); if (IsWindowControlsOverlayEnabled() && ncv) { auto* frame_view = static_cast<WinFrameView*>(ncv->frame_view()); frame_view->caption_button_container()->ResetWindowControls(); } } void NativeWindowViews::SetForwardMouseMessages(bool forward) { if (forward && !forwarding_mouse_messages_) { forwarding_mouse_messages_ = true; forwarding_windows_.insert(this); // Subclassing is used to fix some issues when forwarding mouse messages; // see comments in |SubclassProc|. SetWindowSubclass(legacy_window_, SubclassProc, 1, reinterpret_cast<DWORD_PTR>(this)); if (!mouse_hook_) { mouse_hook_ = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0); } } else if (!forward && forwarding_mouse_messages_) { forwarding_mouse_messages_ = false; forwarding_windows_.erase(this); RemoveWindowSubclass(legacy_window_, SubclassProc, 1); if (forwarding_windows_.empty()) { UnhookWindowsHookEx(mouse_hook_); mouse_hook_ = NULL; } } } LRESULT CALLBACK NativeWindowViews::SubclassProc(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id, DWORD_PTR ref_data) { auto* window = reinterpret_cast<NativeWindowViews*>(ref_data); switch (msg) { case WM_MOUSELEAVE: { // When input is forwarded to underlying windows, this message is posted. // If not handled, it interferes with Chromium logic, causing for example // mouseleave events to fire. If those events are used to exit forward // mode, excessive flickering on for example hover items in underlying // windows can occur due to rapidly entering and leaving forwarding mode. // By consuming and ignoring the message, we're essentially telling // Chromium that we have not left the window despite somebody else getting // the messages. As to why this is caught for the legacy window and not // the actual browser window is simply that the legacy window somehow // makes use of these events; posting to the main window didn't work. if (window->forwarding_mouse_messages_) { return 0; } break; } } return DefSubclassProc(hwnd, msg, w_param, l_param); } LRESULT CALLBACK NativeWindowViews::MouseHookProc(int n_code, WPARAM w_param, LPARAM l_param) { if (n_code < 0) { return CallNextHookEx(NULL, n_code, w_param, l_param); } // Post a WM_MOUSEMOVE message for those windows whose client area contains // the cursor since they are in a state where they would otherwise ignore all // mouse input. if (w_param == WM_MOUSEMOVE) { for (auto* window : forwarding_windows_) { // At first I considered enumerating windows to check whether the cursor // was directly above the window, but since nothing bad seems to happen // if we post the message even if some other window occludes it I have // just left it as is. RECT client_rect; GetClientRect(window->legacy_window_, &client_rect); POINT p = reinterpret_cast<MSLLHOOKSTRUCT*>(l_param)->pt; ScreenToClient(window->legacy_window_, &p); if (PtInRect(&client_rect, p)) { WPARAM w = 0; // No virtual keys pressed for our purposes LPARAM l = MAKELPARAM(p.x, p.y); PostMessage(window->legacy_window_, WM_MOUSEMOVE, w, l); } } } return CallNextHookEx(NULL, n_code, w_param, l_param); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,223
[Bug]: 'restore' event not emitted after minimize and maximize application
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.1 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 21H1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Event 'restore' should notify to application ### Actual Behavior After clicking maximize application, the event 'restore' does not notify after minimize ` BrowserWindow.on( 'restore', () => { // nothing happend }); ` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/35223
https://github.com/electron/electron/pull/35342
0ff6508f5bffd84829749c97c7346fc2fc776563
3ce35f224efa3a6e9bfc9b642816961b8691491b
2022-08-04T11:04:47Z
c++
2022-08-23T01:32:42Z
shell/browser/native_window_views_win.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 <dwmapi.h> #include <shellapi.h> #include <wrl/client.h> #include "base/win/atl.h" // Must be before UIAutomationCore.h #include "content/public/browser/browser_accessibility_state.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/common/electron_constants.h" #include "ui/display/display.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/resize_utils.h" #include "ui/views/widget/native_widget_private.h" // Must be included after other Windows headers. #include <UIAutomationClient.h> #include <UIAutomationCoreApi.h> namespace electron { namespace { // Convert Win32 WM_APPCOMMANDS to strings. const char* AppCommandToString(int command_id) { switch (command_id) { case APPCOMMAND_BROWSER_BACKWARD: return kBrowserBackward; case APPCOMMAND_BROWSER_FORWARD: return kBrowserForward; case APPCOMMAND_BROWSER_REFRESH: return "browser-refresh"; case APPCOMMAND_BROWSER_STOP: return "browser-stop"; case APPCOMMAND_BROWSER_SEARCH: return "browser-search"; case APPCOMMAND_BROWSER_FAVORITES: return "browser-favorites"; case APPCOMMAND_BROWSER_HOME: return "browser-home"; case APPCOMMAND_VOLUME_MUTE: return "volume-mute"; case APPCOMMAND_VOLUME_DOWN: return "volume-down"; case APPCOMMAND_VOLUME_UP: return "volume-up"; case APPCOMMAND_MEDIA_NEXTTRACK: return "media-nexttrack"; case APPCOMMAND_MEDIA_PREVIOUSTRACK: return "media-previoustrack"; case APPCOMMAND_MEDIA_STOP: return "media-stop"; case APPCOMMAND_MEDIA_PLAY_PAUSE: return "media-play-pause"; case APPCOMMAND_LAUNCH_MAIL: return "launch-mail"; case APPCOMMAND_LAUNCH_MEDIA_SELECT: return "launch-media-select"; case APPCOMMAND_LAUNCH_APP1: return "launch-app1"; case APPCOMMAND_LAUNCH_APP2: return "launch-app2"; case APPCOMMAND_BASS_DOWN: return "bass-down"; case APPCOMMAND_BASS_BOOST: return "bass-boost"; case APPCOMMAND_BASS_UP: return "bass-up"; case APPCOMMAND_TREBLE_DOWN: return "treble-down"; case APPCOMMAND_TREBLE_UP: return "treble-up"; case APPCOMMAND_MICROPHONE_VOLUME_MUTE: return "microphone-volume-mute"; case APPCOMMAND_MICROPHONE_VOLUME_DOWN: return "microphone-volume-down"; case APPCOMMAND_MICROPHONE_VOLUME_UP: return "microphone-volume-up"; case APPCOMMAND_HELP: return "help"; case APPCOMMAND_FIND: return "find"; case APPCOMMAND_NEW: return "new"; case APPCOMMAND_OPEN: return "open"; case APPCOMMAND_CLOSE: return "close"; case APPCOMMAND_SAVE: return "save"; case APPCOMMAND_PRINT: return "print"; case APPCOMMAND_UNDO: return "undo"; case APPCOMMAND_REDO: return "redo"; case APPCOMMAND_COPY: return "copy"; case APPCOMMAND_CUT: return "cut"; case APPCOMMAND_PASTE: return "paste"; case APPCOMMAND_REPLY_TO_MAIL: return "reply-to-mail"; case APPCOMMAND_FORWARD_MAIL: return "forward-mail"; case APPCOMMAND_SEND_MAIL: return "send-mail"; case APPCOMMAND_SPELL_CHECK: return "spell-check"; case APPCOMMAND_MIC_ON_OFF_TOGGLE: return "mic-on-off-toggle"; case APPCOMMAND_CORRECTION_LIST: return "correction-list"; case APPCOMMAND_MEDIA_PLAY: return "media-play"; case APPCOMMAND_MEDIA_PAUSE: return "media-pause"; case APPCOMMAND_MEDIA_RECORD: return "media-record"; case APPCOMMAND_MEDIA_FAST_FORWARD: return "media-fast-forward"; case APPCOMMAND_MEDIA_REWIND: return "media-rewind"; case APPCOMMAND_MEDIA_CHANNEL_UP: return "media-channel-up"; case APPCOMMAND_MEDIA_CHANNEL_DOWN: return "media-channel-down"; case APPCOMMAND_DELETE: return "delete"; case APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE: return "dictate-or-command-control-toggle"; default: return "unknown"; } } // Copied from ui/views/win/hwnd_message_handler.cc gfx::ResizeEdge GetWindowResizeEdge(WPARAM param) { switch (param) { case WMSZ_BOTTOM: return gfx::ResizeEdge::kBottom; case WMSZ_TOP: return gfx::ResizeEdge::kTop; case WMSZ_LEFT: return gfx::ResizeEdge::kLeft; case WMSZ_RIGHT: return gfx::ResizeEdge::kRight; case WMSZ_TOPLEFT: return gfx::ResizeEdge::kTopLeft; case WMSZ_TOPRIGHT: return gfx::ResizeEdge::kTopRight; case WMSZ_BOTTOMLEFT: return gfx::ResizeEdge::kBottomLeft; case WMSZ_BOTTOMRIGHT: return gfx::ResizeEdge::kBottomRight; default: return gfx::ResizeEdge::kBottomRight; } } bool IsScreenReaderActive() { UINT screenReader = 0; SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0); return screenReader && UiaClientsAreListening(); } } // namespace std::set<NativeWindowViews*> NativeWindowViews::forwarding_windows_; HHOOK NativeWindowViews::mouse_hook_ = NULL; void NativeWindowViews::Maximize() { // Only use Maximize() when window is NOT transparent style if (!transparent()) { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } else { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); SetBounds(display.work_area(), false); NotifyWindowMaximize(); } } bool NativeWindowViews::ExecuteWindowsCommand(int command_id) { std::string command = AppCommandToString(command_id); NotifyWindowExecuteAppCommand(command); return false; } bool NativeWindowViews::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { NotifyWindowMessage(message, w_param, l_param); // Avoid side effects when calling SetWindowPlacement. if (is_setting_window_placement_) { // Let Chromium handle the WM_NCCALCSIZE message otherwise the window size // would be wrong. // See https://github.com/electron/electron/issues/22393 for more. if (message == WM_NCCALCSIZE) return false; // Otherwise handle the message with default proc, *result = DefWindowProc(GetAcceleratedWidget(), message, w_param, l_param); // and tell Chromium to ignore this message. return true; } switch (message) { // Screen readers send WM_GETOBJECT in order to get the accessibility // object, so take this opportunity to push Chromium into accessible // mode if it isn't already, always say we didn't handle the message // because we still want Chromium to handle returning the actual // accessibility object. case WM_GETOBJECT: { if (checked_for_a11y_support_) return false; const DWORD obj_id = static_cast<DWORD>(l_param); if (obj_id != static_cast<DWORD>(OBJID_CLIENT)) { return false; } if (!IsScreenReaderActive()) { return false; } checked_for_a11y_support_ = true; auto* const axState = content::BrowserAccessibilityState::GetInstance(); if (axState && !axState->IsAccessibleBrowser()) { axState->OnScreenReaderDetected(); Browser::Get()->OnAccessibilitySupportChanged(); } return false; } case WM_GETMINMAXINFO: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); // We do this to work around a Windows bug, where the minimized Window // would report that the closest display to it is not the one that it was // previously on (but the leftmost one instead). We restore the position // of the window during the restore operation, this way chromium can // use the proper display to calculate the scale factor to use. if (!last_normal_placement_bounds_.IsEmpty() && (IsVisible() || IsMinimized()) && GetWindowPlacement(GetAcceleratedWidget(), &wp)) { wp.rcNormalPosition = last_normal_placement_bounds_.ToRECT(); // When calling SetWindowPlacement, Chromium would do window messages // handling. But since we are already in PreHandleMSG this would cause // crash in Chromium under some cases. // // We work around the crash by prevent Chromium from handling window // messages until the SetWindowPlacement call is done. // // See https://github.com/electron/electron/issues/21614 for more. is_setting_window_placement_ = true; SetWindowPlacement(GetAcceleratedWidget(), &wp); is_setting_window_placement_ = false; last_normal_placement_bounds_ = gfx::Rect(); } return false; } case WM_COMMAND: // Handle thumbar button click message. if (HIWORD(w_param) == THBN_CLICKED) return taskbar_host_.HandleThumbarButtonEvent(LOWORD(w_param)); return false; case WM_SIZING: { is_resizing_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillResize(dpi_bounds, GetWindowResizeEdge(w_param), &prevent_default); if (prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); pending_bounds_change_.reset(); return true; // Tells Windows that the Sizing is handled. } return false; } case WM_SIZE: { // Handle window state change. HandleSizeEvent(w_param, l_param); return false; } case WM_EXITSIZEMOVE: { if (is_resizing_) { NotifyWindowResized(); is_resizing_ = false; } if (is_moving_) { NotifyWindowMoved(); is_moving_ = false; } // If the user dragged or moved the window during one or more // calls to window.setBounds(), we want to apply the most recent // one once they are done with the move or resize operation. if (pending_bounds_change_.has_value()) { SetBounds(pending_bounds_change_.value(), false /* animate */); pending_bounds_change_.reset(); } return false; } case WM_MOVING: { is_moving_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillMove(dpi_bounds, &prevent_default); if (!movable_ || prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); pending_bounds_change_.reset(); return true; // Tells Windows that the Move is handled. If not true, // frameless windows can be moved using // -webkit-app-region: drag elements. } return false; } case WM_ENDSESSION: { if (w_param) { NotifyWindowEndSession(); } return false; } case WM_PARENTNOTIFY: { if (LOWORD(w_param) == WM_CREATE) { // Because of reasons regarding legacy drivers and stuff, a window that // matches the client area is created and used internally by Chromium. // This is used when forwarding mouse messages. We only cache the first // occurrence (the webview window) because dev tools also cause this // message to be sent. if (!legacy_window_) { legacy_window_ = reinterpret_cast<HWND>(l_param); } } return false; } case WM_CONTEXTMENU: { bool prevent_default = false; NotifyWindowSystemContextMenu(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param), &prevent_default); return prevent_default; } case WM_SYSCOMMAND: { // Mask is needed to account for double clicking title bar to maximize WPARAM max_mask = 0xFFF0; if (transparent() && ((w_param & max_mask) == SC_MAXIMIZE)) { return true; } return false; } case WM_INITMENU: { // This is handling the scenario where the menu might get triggered by the // user doing "alt + space" resulting in system maximization and restore // being used on transparent windows when that does not work. if (transparent()) { HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); EnableMenuItem(menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); EnableMenuItem(menu, SC_RESTORE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); return true; } return false; } default: { return false; } } } void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) { // Here we handle the WM_SIZE event in order to figure out what is the current // window state and notify the user accordingly. switch (w_param) { case SIZE_MAXIMIZED: case SIZE_MINIMIZED: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); if (GetWindowPlacement(GetAcceleratedWidget(), &wp)) { last_normal_placement_bounds_ = gfx::Rect(wp.rcNormalPosition); } // Note that SIZE_MAXIMIZED and SIZE_MINIMIZED might be emitted for // multiple times for one resize because of the SetWindowPlacement call. if (w_param == SIZE_MAXIMIZED && last_window_state_ != ui::SHOW_STATE_MAXIMIZED) { last_window_state_ = ui::SHOW_STATE_MAXIMIZED; NotifyWindowMaximize(); ResetWindowControls(); } else if (w_param == SIZE_MINIMIZED && last_window_state_ != ui::SHOW_STATE_MINIMIZED) { last_window_state_ = ui::SHOW_STATE_MINIMIZED; NotifyWindowMinimize(); } break; } case SIZE_RESTORED: { switch (last_window_state_) { case ui::SHOW_STATE_MAXIMIZED: last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowUnmaximize(); break; case ui::SHOW_STATE_MINIMIZED: if (IsFullscreen()) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowRestore(); } break; default: break; } ResetWindowControls(); break; } } } void NativeWindowViews::ResetWindowControls() { // If a given window was minimized and has since been // unminimized (restored/maximized), ensure the WCO buttons // are reset to their default unpressed state. auto* ncv = widget()->non_client_view(); if (IsWindowControlsOverlayEnabled() && ncv) { auto* frame_view = static_cast<WinFrameView*>(ncv->frame_view()); frame_view->caption_button_container()->ResetWindowControls(); } } void NativeWindowViews::SetForwardMouseMessages(bool forward) { if (forward && !forwarding_mouse_messages_) { forwarding_mouse_messages_ = true; forwarding_windows_.insert(this); // Subclassing is used to fix some issues when forwarding mouse messages; // see comments in |SubclassProc|. SetWindowSubclass(legacy_window_, SubclassProc, 1, reinterpret_cast<DWORD_PTR>(this)); if (!mouse_hook_) { mouse_hook_ = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0); } } else if (!forward && forwarding_mouse_messages_) { forwarding_mouse_messages_ = false; forwarding_windows_.erase(this); RemoveWindowSubclass(legacy_window_, SubclassProc, 1); if (forwarding_windows_.empty()) { UnhookWindowsHookEx(mouse_hook_); mouse_hook_ = NULL; } } } LRESULT CALLBACK NativeWindowViews::SubclassProc(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id, DWORD_PTR ref_data) { auto* window = reinterpret_cast<NativeWindowViews*>(ref_data); switch (msg) { case WM_MOUSELEAVE: { // When input is forwarded to underlying windows, this message is posted. // If not handled, it interferes with Chromium logic, causing for example // mouseleave events to fire. If those events are used to exit forward // mode, excessive flickering on for example hover items in underlying // windows can occur due to rapidly entering and leaving forwarding mode. // By consuming and ignoring the message, we're essentially telling // Chromium that we have not left the window despite somebody else getting // the messages. As to why this is caught for the legacy window and not // the actual browser window is simply that the legacy window somehow // makes use of these events; posting to the main window didn't work. if (window->forwarding_mouse_messages_) { return 0; } break; } } return DefSubclassProc(hwnd, msg, w_param, l_param); } LRESULT CALLBACK NativeWindowViews::MouseHookProc(int n_code, WPARAM w_param, LPARAM l_param) { if (n_code < 0) { return CallNextHookEx(NULL, n_code, w_param, l_param); } // Post a WM_MOUSEMOVE message for those windows whose client area contains // the cursor since they are in a state where they would otherwise ignore all // mouse input. if (w_param == WM_MOUSEMOVE) { for (auto* window : forwarding_windows_) { // At first I considered enumerating windows to check whether the cursor // was directly above the window, but since nothing bad seems to happen // if we post the message even if some other window occludes it I have // just left it as is. RECT client_rect; GetClientRect(window->legacy_window_, &client_rect); POINT p = reinterpret_cast<MSLLHOOKSTRUCT*>(l_param)->pt; ScreenToClient(window->legacy_window_, &p); if (PtInRect(&client_rect, p)) { WPARAM w = 0; // No virtual keys pressed for our purposes LPARAM l = MAKELPARAM(p.x, p.y); PostMessage(window->legacy_window_, WM_MOUSEMOVE, w, l); } } } return CallNextHookEx(NULL, n_code, w_param, l_param); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
28,570
[Bug]: BrowserWindow `restore` event fires late (non-maximized) or not at all (maximized)
### Preflight Checklist I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 12.0.2 ### What operating system are you using? Windows ### Operating System Version Windows 10; 20H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I expect that the restore event fires when restoring a previously maximized window ### Actual Behavior restore event doesn't fire. It only fires for normal state windows ### Testcase Gist URL _No response_ 1. start app 2. maximize window 3. minimize window 4. restore window 5. see that "restored" isn't logged to the console, but is if you skipped step 2 main.js: ``` const {app, BrowserWindow } = require('electron') function createWindow () { const mainWindow = new BrowserWindow(); mainWindow.on("restore", () => { console.log("restored"); }); } app.whenReady().then(() => { createWindow() app.on('activate', function () { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() }) ```
https://github.com/electron/electron/issues/28570
https://github.com/electron/electron/pull/35342
0ff6508f5bffd84829749c97c7346fc2fc776563
3ce35f224efa3a6e9bfc9b642816961b8691491b
2021-04-07T21:03:37Z
c++
2022-08-23T01:32:42Z
shell/browser/native_window_views_win.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 <dwmapi.h> #include <shellapi.h> #include <wrl/client.h> #include "base/win/atl.h" // Must be before UIAutomationCore.h #include "content/public/browser/browser_accessibility_state.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/common/electron_constants.h" #include "ui/display/display.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/resize_utils.h" #include "ui/views/widget/native_widget_private.h" // Must be included after other Windows headers. #include <UIAutomationClient.h> #include <UIAutomationCoreApi.h> namespace electron { namespace { // Convert Win32 WM_APPCOMMANDS to strings. const char* AppCommandToString(int command_id) { switch (command_id) { case APPCOMMAND_BROWSER_BACKWARD: return kBrowserBackward; case APPCOMMAND_BROWSER_FORWARD: return kBrowserForward; case APPCOMMAND_BROWSER_REFRESH: return "browser-refresh"; case APPCOMMAND_BROWSER_STOP: return "browser-stop"; case APPCOMMAND_BROWSER_SEARCH: return "browser-search"; case APPCOMMAND_BROWSER_FAVORITES: return "browser-favorites"; case APPCOMMAND_BROWSER_HOME: return "browser-home"; case APPCOMMAND_VOLUME_MUTE: return "volume-mute"; case APPCOMMAND_VOLUME_DOWN: return "volume-down"; case APPCOMMAND_VOLUME_UP: return "volume-up"; case APPCOMMAND_MEDIA_NEXTTRACK: return "media-nexttrack"; case APPCOMMAND_MEDIA_PREVIOUSTRACK: return "media-previoustrack"; case APPCOMMAND_MEDIA_STOP: return "media-stop"; case APPCOMMAND_MEDIA_PLAY_PAUSE: return "media-play-pause"; case APPCOMMAND_LAUNCH_MAIL: return "launch-mail"; case APPCOMMAND_LAUNCH_MEDIA_SELECT: return "launch-media-select"; case APPCOMMAND_LAUNCH_APP1: return "launch-app1"; case APPCOMMAND_LAUNCH_APP2: return "launch-app2"; case APPCOMMAND_BASS_DOWN: return "bass-down"; case APPCOMMAND_BASS_BOOST: return "bass-boost"; case APPCOMMAND_BASS_UP: return "bass-up"; case APPCOMMAND_TREBLE_DOWN: return "treble-down"; case APPCOMMAND_TREBLE_UP: return "treble-up"; case APPCOMMAND_MICROPHONE_VOLUME_MUTE: return "microphone-volume-mute"; case APPCOMMAND_MICROPHONE_VOLUME_DOWN: return "microphone-volume-down"; case APPCOMMAND_MICROPHONE_VOLUME_UP: return "microphone-volume-up"; case APPCOMMAND_HELP: return "help"; case APPCOMMAND_FIND: return "find"; case APPCOMMAND_NEW: return "new"; case APPCOMMAND_OPEN: return "open"; case APPCOMMAND_CLOSE: return "close"; case APPCOMMAND_SAVE: return "save"; case APPCOMMAND_PRINT: return "print"; case APPCOMMAND_UNDO: return "undo"; case APPCOMMAND_REDO: return "redo"; case APPCOMMAND_COPY: return "copy"; case APPCOMMAND_CUT: return "cut"; case APPCOMMAND_PASTE: return "paste"; case APPCOMMAND_REPLY_TO_MAIL: return "reply-to-mail"; case APPCOMMAND_FORWARD_MAIL: return "forward-mail"; case APPCOMMAND_SEND_MAIL: return "send-mail"; case APPCOMMAND_SPELL_CHECK: return "spell-check"; case APPCOMMAND_MIC_ON_OFF_TOGGLE: return "mic-on-off-toggle"; case APPCOMMAND_CORRECTION_LIST: return "correction-list"; case APPCOMMAND_MEDIA_PLAY: return "media-play"; case APPCOMMAND_MEDIA_PAUSE: return "media-pause"; case APPCOMMAND_MEDIA_RECORD: return "media-record"; case APPCOMMAND_MEDIA_FAST_FORWARD: return "media-fast-forward"; case APPCOMMAND_MEDIA_REWIND: return "media-rewind"; case APPCOMMAND_MEDIA_CHANNEL_UP: return "media-channel-up"; case APPCOMMAND_MEDIA_CHANNEL_DOWN: return "media-channel-down"; case APPCOMMAND_DELETE: return "delete"; case APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE: return "dictate-or-command-control-toggle"; default: return "unknown"; } } // Copied from ui/views/win/hwnd_message_handler.cc gfx::ResizeEdge GetWindowResizeEdge(WPARAM param) { switch (param) { case WMSZ_BOTTOM: return gfx::ResizeEdge::kBottom; case WMSZ_TOP: return gfx::ResizeEdge::kTop; case WMSZ_LEFT: return gfx::ResizeEdge::kLeft; case WMSZ_RIGHT: return gfx::ResizeEdge::kRight; case WMSZ_TOPLEFT: return gfx::ResizeEdge::kTopLeft; case WMSZ_TOPRIGHT: return gfx::ResizeEdge::kTopRight; case WMSZ_BOTTOMLEFT: return gfx::ResizeEdge::kBottomLeft; case WMSZ_BOTTOMRIGHT: return gfx::ResizeEdge::kBottomRight; default: return gfx::ResizeEdge::kBottomRight; } } bool IsScreenReaderActive() { UINT screenReader = 0; SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0); return screenReader && UiaClientsAreListening(); } } // namespace std::set<NativeWindowViews*> NativeWindowViews::forwarding_windows_; HHOOK NativeWindowViews::mouse_hook_ = NULL; void NativeWindowViews::Maximize() { // Only use Maximize() when window is NOT transparent style if (!transparent()) { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } else { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); SetBounds(display.work_area(), false); NotifyWindowMaximize(); } } bool NativeWindowViews::ExecuteWindowsCommand(int command_id) { std::string command = AppCommandToString(command_id); NotifyWindowExecuteAppCommand(command); return false; } bool NativeWindowViews::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { NotifyWindowMessage(message, w_param, l_param); // Avoid side effects when calling SetWindowPlacement. if (is_setting_window_placement_) { // Let Chromium handle the WM_NCCALCSIZE message otherwise the window size // would be wrong. // See https://github.com/electron/electron/issues/22393 for more. if (message == WM_NCCALCSIZE) return false; // Otherwise handle the message with default proc, *result = DefWindowProc(GetAcceleratedWidget(), message, w_param, l_param); // and tell Chromium to ignore this message. return true; } switch (message) { // Screen readers send WM_GETOBJECT in order to get the accessibility // object, so take this opportunity to push Chromium into accessible // mode if it isn't already, always say we didn't handle the message // because we still want Chromium to handle returning the actual // accessibility object. case WM_GETOBJECT: { if (checked_for_a11y_support_) return false; const DWORD obj_id = static_cast<DWORD>(l_param); if (obj_id != static_cast<DWORD>(OBJID_CLIENT)) { return false; } if (!IsScreenReaderActive()) { return false; } checked_for_a11y_support_ = true; auto* const axState = content::BrowserAccessibilityState::GetInstance(); if (axState && !axState->IsAccessibleBrowser()) { axState->OnScreenReaderDetected(); Browser::Get()->OnAccessibilitySupportChanged(); } return false; } case WM_GETMINMAXINFO: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); // We do this to work around a Windows bug, where the minimized Window // would report that the closest display to it is not the one that it was // previously on (but the leftmost one instead). We restore the position // of the window during the restore operation, this way chromium can // use the proper display to calculate the scale factor to use. if (!last_normal_placement_bounds_.IsEmpty() && (IsVisible() || IsMinimized()) && GetWindowPlacement(GetAcceleratedWidget(), &wp)) { wp.rcNormalPosition = last_normal_placement_bounds_.ToRECT(); // When calling SetWindowPlacement, Chromium would do window messages // handling. But since we are already in PreHandleMSG this would cause // crash in Chromium under some cases. // // We work around the crash by prevent Chromium from handling window // messages until the SetWindowPlacement call is done. // // See https://github.com/electron/electron/issues/21614 for more. is_setting_window_placement_ = true; SetWindowPlacement(GetAcceleratedWidget(), &wp); is_setting_window_placement_ = false; last_normal_placement_bounds_ = gfx::Rect(); } return false; } case WM_COMMAND: // Handle thumbar button click message. if (HIWORD(w_param) == THBN_CLICKED) return taskbar_host_.HandleThumbarButtonEvent(LOWORD(w_param)); return false; case WM_SIZING: { is_resizing_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillResize(dpi_bounds, GetWindowResizeEdge(w_param), &prevent_default); if (prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); pending_bounds_change_.reset(); return true; // Tells Windows that the Sizing is handled. } return false; } case WM_SIZE: { // Handle window state change. HandleSizeEvent(w_param, l_param); return false; } case WM_EXITSIZEMOVE: { if (is_resizing_) { NotifyWindowResized(); is_resizing_ = false; } if (is_moving_) { NotifyWindowMoved(); is_moving_ = false; } // If the user dragged or moved the window during one or more // calls to window.setBounds(), we want to apply the most recent // one once they are done with the move or resize operation. if (pending_bounds_change_.has_value()) { SetBounds(pending_bounds_change_.value(), false /* animate */); pending_bounds_change_.reset(); } return false; } case WM_MOVING: { is_moving_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillMove(dpi_bounds, &prevent_default); if (!movable_ || prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); pending_bounds_change_.reset(); return true; // Tells Windows that the Move is handled. If not true, // frameless windows can be moved using // -webkit-app-region: drag elements. } return false; } case WM_ENDSESSION: { if (w_param) { NotifyWindowEndSession(); } return false; } case WM_PARENTNOTIFY: { if (LOWORD(w_param) == WM_CREATE) { // Because of reasons regarding legacy drivers and stuff, a window that // matches the client area is created and used internally by Chromium. // This is used when forwarding mouse messages. We only cache the first // occurrence (the webview window) because dev tools also cause this // message to be sent. if (!legacy_window_) { legacy_window_ = reinterpret_cast<HWND>(l_param); } } return false; } case WM_CONTEXTMENU: { bool prevent_default = false; NotifyWindowSystemContextMenu(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param), &prevent_default); return prevent_default; } case WM_SYSCOMMAND: { // Mask is needed to account for double clicking title bar to maximize WPARAM max_mask = 0xFFF0; if (transparent() && ((w_param & max_mask) == SC_MAXIMIZE)) { return true; } return false; } case WM_INITMENU: { // This is handling the scenario where the menu might get triggered by the // user doing "alt + space" resulting in system maximization and restore // being used on transparent windows when that does not work. if (transparent()) { HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); EnableMenuItem(menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); EnableMenuItem(menu, SC_RESTORE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); return true; } return false; } default: { return false; } } } void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) { // Here we handle the WM_SIZE event in order to figure out what is the current // window state and notify the user accordingly. switch (w_param) { case SIZE_MAXIMIZED: case SIZE_MINIMIZED: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); if (GetWindowPlacement(GetAcceleratedWidget(), &wp)) { last_normal_placement_bounds_ = gfx::Rect(wp.rcNormalPosition); } // Note that SIZE_MAXIMIZED and SIZE_MINIMIZED might be emitted for // multiple times for one resize because of the SetWindowPlacement call. if (w_param == SIZE_MAXIMIZED && last_window_state_ != ui::SHOW_STATE_MAXIMIZED) { last_window_state_ = ui::SHOW_STATE_MAXIMIZED; NotifyWindowMaximize(); ResetWindowControls(); } else if (w_param == SIZE_MINIMIZED && last_window_state_ != ui::SHOW_STATE_MINIMIZED) { last_window_state_ = ui::SHOW_STATE_MINIMIZED; NotifyWindowMinimize(); } break; } case SIZE_RESTORED: { switch (last_window_state_) { case ui::SHOW_STATE_MAXIMIZED: last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowUnmaximize(); break; case ui::SHOW_STATE_MINIMIZED: if (IsFullscreen()) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowRestore(); } break; default: break; } ResetWindowControls(); break; } } } void NativeWindowViews::ResetWindowControls() { // If a given window was minimized and has since been // unminimized (restored/maximized), ensure the WCO buttons // are reset to their default unpressed state. auto* ncv = widget()->non_client_view(); if (IsWindowControlsOverlayEnabled() && ncv) { auto* frame_view = static_cast<WinFrameView*>(ncv->frame_view()); frame_view->caption_button_container()->ResetWindowControls(); } } void NativeWindowViews::SetForwardMouseMessages(bool forward) { if (forward && !forwarding_mouse_messages_) { forwarding_mouse_messages_ = true; forwarding_windows_.insert(this); // Subclassing is used to fix some issues when forwarding mouse messages; // see comments in |SubclassProc|. SetWindowSubclass(legacy_window_, SubclassProc, 1, reinterpret_cast<DWORD_PTR>(this)); if (!mouse_hook_) { mouse_hook_ = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0); } } else if (!forward && forwarding_mouse_messages_) { forwarding_mouse_messages_ = false; forwarding_windows_.erase(this); RemoveWindowSubclass(legacy_window_, SubclassProc, 1); if (forwarding_windows_.empty()) { UnhookWindowsHookEx(mouse_hook_); mouse_hook_ = NULL; } } } LRESULT CALLBACK NativeWindowViews::SubclassProc(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id, DWORD_PTR ref_data) { auto* window = reinterpret_cast<NativeWindowViews*>(ref_data); switch (msg) { case WM_MOUSELEAVE: { // When input is forwarded to underlying windows, this message is posted. // If not handled, it interferes with Chromium logic, causing for example // mouseleave events to fire. If those events are used to exit forward // mode, excessive flickering on for example hover items in underlying // windows can occur due to rapidly entering and leaving forwarding mode. // By consuming and ignoring the message, we're essentially telling // Chromium that we have not left the window despite somebody else getting // the messages. As to why this is caught for the legacy window and not // the actual browser window is simply that the legacy window somehow // makes use of these events; posting to the main window didn't work. if (window->forwarding_mouse_messages_) { return 0; } break; } } return DefSubclassProc(hwnd, msg, w_param, l_param); } LRESULT CALLBACK NativeWindowViews::MouseHookProc(int n_code, WPARAM w_param, LPARAM l_param) { if (n_code < 0) { return CallNextHookEx(NULL, n_code, w_param, l_param); } // Post a WM_MOUSEMOVE message for those windows whose client area contains // the cursor since they are in a state where they would otherwise ignore all // mouse input. if (w_param == WM_MOUSEMOVE) { for (auto* window : forwarding_windows_) { // At first I considered enumerating windows to check whether the cursor // was directly above the window, but since nothing bad seems to happen // if we post the message even if some other window occludes it I have // just left it as is. RECT client_rect; GetClientRect(window->legacy_window_, &client_rect); POINT p = reinterpret_cast<MSLLHOOKSTRUCT*>(l_param)->pt; ScreenToClient(window->legacy_window_, &p); if (PtInRect(&client_rect, p)) { WPARAM w = 0; // No virtual keys pressed for our purposes LPARAM l = MAKELPARAM(p.x, p.y); PostMessage(window->legacy_window_, WM_MOUSEMOVE, w, l); } } } return CallNextHookEx(NULL, n_code, w_param, l_param); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
31,018
[Bug]: ContextIsolation changes page behavior and breaks protonmail login
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version any 15.x.y-beta, including beta.7 ### What operating system are you using? Other Linux ### Operating System Version Fedora 34 ### What arch are you using? x64 ### Last Known Working Electron version 14.0.1 ### Expected Behavior Logins of Protonmail inside webviews should work and decrypt messages after login or show a message that the password was incorrect, regardless of the webpreferences of the webview. ### Actual Behavior On Electron 14 it works as expected, you can login and it all works. The same is true for Electron 15, but ONLY if you have enabled contextIsolation. I can't do that for my project as I need to overwrite existing window properties, and since the contextBridge doesn't allow this I have contextIsolation disabled. This isn't a big issue, as I only run a specific set of preloads inside the webview, but for some odd reason the protonmail login gives this vague error of "invalid character", that I can ONLY reproduce with contextIsolation disabled using the 15 betas. It does not happen in Chromium, it does not happen when enabling contextIsolation and it did not happen in Electron 14 and earlier, where you could just sign in. ### Testcase Gist URL https://gist.github.com/Jelmerro/65c3cabe4ac91461f382f6b15361b7b5 ### Additional Information _No response_
https://github.com/electron/electron/issues/31018
https://github.com/electron/electron/pull/35415
7e8607fd7a3dac522fce600a3e5fd03bda64efff
22ff2b6b933a52f7cfa85556aa8aaea7544b9d3f
2021-09-18T20:17:33Z
c++
2022-08-25T06:55:07Z
patches/node/.patches
refactor_alter_child_process_fork_to_use_execute_script_with.patch feat_initialize_asar_support.patch expose_get_builtin_module_function.patch build_add_gn_build_files.patch fix_add_default_values_for_variables_in_common_gypi.patch fix_expose_tracing_agent_and_use_tracing_tracingcontroller_instead.patch pass_all_globals_through_require.patch build_modify_js2c_py_to_allow_injection_of_original-fs_and_custom_embedder_js.patch refactor_allow_embedder_overriding_of_internal_fs_calls.patch chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch chore_add_context_to_context_aware_module_prevention.patch chore_read_nobrowserglobals_from_global_not_process.patch fix_handle_boringssl_and_openssl_incompatibilities.patch src_allow_embedders_to_provide_a_custom_pageallocator_to.patch fix_crypto_tests_to_run_with_bssl.patch fix_account_for_debugger_agent_race_condition.patch repl_fix_crash_when_sharedarraybuffer_disabled.patch fix_readbarrier_undefined_symbol_error_on_woa_arm64.patch chore_fix_-wimplicit-fallthrough.patch fix_crash_caused_by_gethostnamew_on_windows_7.patch fix_suppress_clang_-wdeprecated-declarations_in_libuv.patch fix_serdes_test.patch darwin_remove_eprototype_error_workaround_3405.patch darwin_translate_eprototype_to_econnreset_3413.patch darwin_bump_minimum_supported_version_to_10_15_3406.patch fix_failing_node_js_test_on_outdated.patch be_compatible_with_cppgc.patch feat_add_knostartdebugsignalhandler_to_environment_to_prevent.patch worker_thread_add_asar_support.patch process_monitor_for_exit_with_kqueue_on_bsds_3441.patch process_bsd_handle_kevent_note_exit_failure_3451.patch reland_macos_use_posix_spawn_instead_of_fork_3257.patch process_reset_the_signal_mask_if_the_fork_fails_3537.patch process_only_use_f_dupfd_cloexec_if_it_is_defined_3512.patch unix_simplify_uv_cloexec_fcntl_3492.patch unix_remove_uv_cloexec_ioctl_3515.patch process_simplify_uv_write_int_calls_3519.patch macos_don_t_use_thread-unsafe_strtok_3524.patch process_fix_hang_after_note_exit_3521.patch feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch fix_preserve_proper_method_names_as-is_in_error_stack.patch macos_avoid_posix_spawnp_cwd_bug_3597.patch src_update_importmoduledynamically.patch fix_add_v8_enable_reverse_jsargs_defines_in_common_gypi.patch json_parse_errors_made_user-friendly.patch support_v8_sandboxed_pointers.patch build_ensure_v8_pointer_compression_sandbox_is_enabled_on_64bit.patch build_ensure_native_module_compilation_fails_if_not_using_a_new.patch fix_override_createjob_in_node_platform.patch